import { useEffect, useState } from 'react'

/**
 * PluginLoader Component
 * Lädt automatisch alle JS-Plugins aus dem /plugins Ordner
 * 
 * Jedes Plugin kann folgende Hooks nutzen:
 * - onPluginInit(pluginContext)
 * - onMessageSent(event)
 * - onResponseReceived(event)
 */
export default function PluginLoader({ onPluginsLoad }) {
  const [loadedCount, setLoadedCount] = useState(0)

  useEffect(() => {
    loadPlugins()
  }, [])

  const loadPlugins = async () => {
    try {
      // Import alle JS-Dateien aus dem plugins Ordner
      // Für Vite: Nutze import.meta.glob
      const pluginModules = import.meta.glob('/plugins/*.js', { eager: false })
      
      const loadedPlugins = []
      
      for (const [path, importFn] of Object.entries(pluginModules)) {
        try {
          const pluginName = path.split('/').pop().replace('.js', '')
          
          console.log(`🔌 Loading plugin: ${pluginName}`)
          
          // Plugin laden
          const module = await importFn()
          
          // Plugin-Kontext bereitstellen
          const pluginContext = {
            name: pluginName,
            log: (msg) => console.log(`[${pluginName}]`, msg),
            warn: (msg) => console.warn(`[${pluginName}]`, msg),
            error: (msg) => console.error(`[${pluginName}]`, msg),
          }
          
          // onPluginInit Hook aufrufen (wenn vorhanden)
          if (module.onPluginInit) {
            module.onPluginInit(pluginContext)
          }
          
          // Message-Hooks registrieren
          if (module.onMessageSent) {
            window.addEventListener('messageSent', (e) => {
              module.onMessageSent(pluginContext, e.detail)
            })
          }
          
          if (module.onResponseReceived) {
            window.addEventListener('responseReceived', (e) => {
              module.onResponseReceived(pluginContext, e.detail)
            })
          }
          
          loadedPlugins.push(pluginName)
          console.log(`✓ Plugin ${pluginName} initialized`)
          
        } catch (err) {
          console.error(`✗ Failed to load plugin from ${path}:`, err)
        }
      }
      
      setLoadedCount(loadedPlugins.length)
      onPluginsLoad?.(loadedPlugins)
      
      // Event für geladene Plugins
      window.dispatchEvent(new CustomEvent('pluginsLoaded', {
        detail: loadedPlugins
      }))
      
      console.log(`✓ Loaded ${loadedPlugins.length} plugin(s)`)
      
    } catch (err) {
      console.error('Error loading plugins:', err)
    }
  }

  return null // Dieser Component rendert nichts
}
