export function initializeComponents() {
  console.log('🔧 Component Loader: Starting initialization...');
  
  const componentMap = new Map();
  
  // Component registry with lazy loading support
  const componentRegistry = {
    'tabs': () => import('../components/tabs.js').then(m => m.TabsComponent),
    'accordion': () => import('../components/accordion.js').then(m => m.AccordionComponent),
  };

  // Auto-initialize components based on data attributes
  async function autoInitialize() {
    for (const [componentName, loader] of Object.entries(componentRegistry)) {
      const elements = document.querySelectorAll(`[data-${componentName}]`);
      
      if (elements.length > 0) {
        try {
          const ComponentClass = await loader();
          
          elements.forEach(element => {
            const options = parseDataAttributes(element, componentName);
            const instance = new ComponentClass(element, options);
            componentMap.set(element, instance);
          });
          
          console.log(`✅ ${componentName}: ${elements.length} instances initialized`);
        } catch (error) {
          console.error(`❌ Failed to load ${componentName}:`, error);
        }
      }
    }
  }

  // Parse data attributes to options object
  function parseDataAttributes(element, componentName) {
    const options = {};
    const prefix = `data-${componentName}-`;
    
    Array.from(element.attributes).forEach(attr => {
      if (attr.name.startsWith(prefix)) {
        const optionName = toCamelCase(attr.name.substring(prefix.length));
        options[optionName] = parseValue(attr.value);
      }
    });
    
    return options;
  }

  // Convert kebab-case to camelCase
  function toCamelCase(str) {
    return str.replace(/-([a-z])/g, (match, letter) => letter.toUpperCase());
  }

  // Parse string values to appropriate types
  function parseValue(value) {
    // Boolean
    if (value === 'true') return true;
    if (value === 'false') return false;
    
    // Number
    if (!isNaN(value) && !isNaN(parseFloat(value))) {
      return parseFloat(value);
    }
    
    // JSON
    if (value.startsWith('{') || value.startsWith('[')) {
      try {
        return JSON.parse(value);
      } catch (e) {
        console.warn('Failed to parse JSON value:', value);
      }
    }
    
    // String
    return value;
  }

  // Manual component initialization
  function initializeComponent(element, componentName, options = {}) {
    const loader = componentRegistry[componentName];
    
    if (!loader) {
      console.error(`Component "${componentName}" not found in registry`);
      return null;
    }

    return loader().then(ComponentClass => {
      const instance = new ComponentClass(element, options);
      componentMap.set(element, instance);
      return instance;
    }).catch(error => {
      console.error(`Failed to initialize ${componentName}:`, error);
      return null;
    });
  }

  // Get component instance from element
  function getComponent(element) {
    return componentMap.get(element);
  }

  // Destroy component instance
  function destroyComponent(element) {
    const instance = componentMap.get(element);
    if (instance && typeof instance.destroy === 'function') {
      instance.destroy();
      componentMap.delete(element);
      return true;
    }
    return false;
  }

  // Reinitialize components (useful for dynamic content)
  function reinitialize() {
    // Destroy existing instances
    componentMap.forEach((instance, element) => {
      if (typeof instance.destroy === 'function') {
        instance.destroy();
      }
    });
    componentMap.clear();
    
    // Reinitialize
    return autoInitialize();
  }

  // Initialize on DOM ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', autoInitialize);
  } else {
    autoInitialize();
  }

  // Return public API
  return {
    initialize: initializeComponent,
    get: getComponent,
    destroy: destroyComponent,
    reinitialize,
    getAll: () => new Map(componentMap)
  };
}

// Utility for handling dynamic content
export function observeComponentChanges(callback) {
  if (typeof MutationObserver === 'undefined') {
    console.warn('MutationObserver not supported');
    return;
  }

  const observer = new MutationObserver(mutations => {
    let hasNewComponents = false;
    
    mutations.forEach(mutation => {
      mutation.addedNodes.forEach(node => {
        if (node.nodeType === Node.ELEMENT_NODE) {
          // Check if the node itself has component data attributes
          const hasDataAttr = Array.from(node.attributes || []).some(attr => 
            attr.name.startsWith('data-') && 
            ['tabs', 'accordion'].some(comp => 
              attr.name.includes(comp)
            )
          );
          
          // Check if any child elements have component data attributes
          const hasChildComponents = node.querySelectorAll && 
            node.querySelectorAll('[data-tabs], [data-accordion]').length > 0;
          
          if (hasDataAttr || hasChildComponents) {
            hasNewComponents = true;
          }
        }
      });
    });
    
    if (hasNewComponents && callback) {
      callback();
    }
  });

  observer.observe(document.body, {
    childList: true,
    subtree: true,
    attributes: false
  });

  return observer;
}

// Export default loader
export default initializeComponents;