/**
 * DAM Asset Picker Bridge
 * 
 * Provides a JavaScript interface to open the Svelte AssetPicker component
 * from Gutenberg blocks
 */

(function() {
  // Create a global interface for blocks to use
  window.damAssetPicker = {
    open: function(options) {
      const {
        multiple = false,
        mimeTypeFilter = '',
        onSelect,
        onCancel
      } = options;

      // Create a mount point for the AssetPicker
      const mountPoint = document.createElement('div');
      mountPoint.id = 'dam-picker-mount';
      document.body.appendChild(mountPoint);

      // Dispatch custom event that the Svelte app will listen for
      const event = new CustomEvent('dam:openPicker', {
        detail: {
          multiple,
          mimeTypeFilter,
          mountPoint: mountPoint.id,
          onSelect: (assets) => {
            if (onSelect) {
              onSelect(assets);
            }
            // Cleanup
            if (mountPoint.parentNode) {
              mountPoint.parentNode.removeChild(mountPoint);
            }
          },
          onCancel: () => {
            if (onCancel) {
              onCancel();
            }
            // Cleanup
            if (mountPoint.parentNode) {
              mountPoint.parentNode.removeChild(mountPoint);
            }
          }
        }
      });

      window.dispatchEvent(event);
    }
  };

  // For debugging
  console.log('DAM Asset Picker bridge loaded');
})();
