// /projects/survivable_hybrid_cloud/common/js/common.js
(function () {
  'use strict';

  console.log('[common.js] Loaded successfully');

  // ==========================================
  // DEFENSIVE COMPONENT LOADER
  // ==========================================
  async function loadComponent(selector, path) {
    const element = document.querySelector(selector);
    if (!element) {
      console.warn(`[loadComponent] Element not found: ${selector}`);
      return false;
    }

    try {
      const response = await fetch(path);
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${path}`);
      }
      const html = await response.text();
      element.innerHTML = html;
      
      // Execute any scripts in the loaded HTML
      const scripts = element.querySelectorAll('script');
      scripts.forEach(oldScript => {
        const newScript = document.createElement('script');
        Array.from(oldScript.attributes).forEach(attr => 
          newScript.setAttribute(attr.name, attr.value)
        );
        newScript.textContent = oldScript.textContent;
        oldScript.parentNode.replaceChild(newScript, oldScript);
      });
      
      console.log(`[loadComponent] ✓ Loaded: ${path}`);
      return true;
    } catch (err) {
      console.error(`[loadComponent] ✗ Failed: ${path}`, err);
      element.innerHTML = '<div style="color:red;padding:1rem;">Failed to load component</div>';
      return false;
    }
  }

  // ==========================================
  // JSON DATA LOADER (for menu configs, etc.)
  // ==========================================
  async function loadJSON(path) {
    try {
      const response = await fetch(path);
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${path}`);
      }
      const data = await response.json();
      console.log(`[loadJSON] ✓ Loaded: ${path}`);
      return data;
    } catch (err) {
      console.error(`[loadJSON] ✗ Failed: ${path}`, err);
      return null;
    }
  }

  // ==========================================
  // BUILD HAMBURGER MENU FROM JSON
  // ==========================================
  async function buildHamburgerMenu() {
    try {
      console.log('[buildMenu] Loading menu data...');
      
      const menuData = await loadJSON('./docs/hamburger.json');
      if (!menuData) {
        throw new Error('Failed to load menu data');
      }

      console.log('[buildMenu] ✓ Menu data loaded:', menuData);

      const menuList = document.getElementById('menuList');
      if (!menuList) {
        console.error('[buildMenu] #menuList not found');
        return;
      }

      // Clear loading message
      menuList.innerHTML = '';

      // Build menu items
      menuData.forEach((item) => {
        const li = document.createElement('li');
        
        const hasSubitems = item.subitems && item.subitems.length > 0;

        if (hasSubitems) {
          // Create card wrapper
          const card = document.createElement('div');
          card.className = 'menu-card';
          
          // Main item container
          const mainItemContainer = document.createElement('div');
          mainItemContainer.className = 'menu-main-container flex items-center justify-between';
          
          // Main menu link
          const mainLink = document.createElement('a');
          mainLink.href = item.url;
          mainLink.textContent = item.text;
          mainLink.className = 'menu-main-link flex-1';
          
          // Toggle button with chevron
          const toggleBtn = document.createElement('button');
          toggleBtn.className = 'menu-toggle-btn';
          toggleBtn.setAttribute('aria-expanded', 'false');
          toggleBtn.setAttribute('aria-label', 'Toggle submenu');
          toggleBtn.innerHTML = `
            <svg fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7"></path>
            </svg>
          `;
          
          mainItemContainer.appendChild(mainLink);
          mainItemContainer.appendChild(toggleBtn);
          card.appendChild(mainItemContainer);

          // Create submenu
          const subList = document.createElement('ul');
          subList.className = 'menu-submenu hidden';

          item.subitems.forEach(subitem => {
            const subLi = document.createElement('li');
            const subLink = document.createElement('a');
            subLink.href = subitem.url;
            subLink.textContent = subitem.text;
            subLink.className = 'menu-sublink';
            
            subLi.appendChild(subLink);
            subList.appendChild(subLi);
          });

          card.appendChild(subList);
          li.appendChild(card);

          // Toggle functionality
          toggleBtn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const isExpanded = toggleBtn.getAttribute('aria-expanded') === 'true';
            
            if (isExpanded) {
              subList.classList.add('hidden');
              toggleBtn.setAttribute('aria-expanded', 'false');
            } else {
              subList.classList.remove('hidden');
              toggleBtn.setAttribute('aria-expanded', 'true');
            }
          });

        } else {
          // Simple menu item without subitems
          const card = document.createElement('div');
          card.className = 'menu-card';
          
          const mainLink = document.createElement('a');
          mainLink.href = item.url;
          mainLink.textContent = item.text;
          mainLink.className = 'menu-main-link block';
          
          card.appendChild(mainLink);
          li.appendChild(card);
        }

        menuList.appendChild(li);
      });

      console.log('[buildMenu] ✓ Menu rendered successfully');

    } catch (error) {
      console.error('[buildMenu] ✗ Failed:', error);
      const menuList = document.getElementById('menuList');
      if (menuList) {
        menuList.innerHTML = '<li style="padding: 1rem; color: #ef4444; text-align: center;">Failed to load menu</li>';
      }
    }
  }

  // ==========================================
  // RESOLVE PATH (handles both root & subdirs)
  // ==========================================
  function resolveComponentPath(filename) {
    const depth = window.location.pathname.split('/').filter(Boolean).length;
    const prefix = depth > 2 ? './common/components/' : './common/components/';
    return prefix + filename;
  }

  // ==========================================
  // HAMBURGER MENU TOGGLE
  // ==========================================
  function initHamburgerMenu() {
    const hamburger = document.getElementById('hamburger');
    const menu = document.getElementById('mobileMenu');
    
    if (!hamburger || !menu) {
      console.warn('[hamburger] Elements not found');
      return;
    }

    hamburger.addEventListener('click', function(e) {
      e.preventDefault();
      menu.classList.toggle('hidden');
      
      const isExpanded = !menu.classList.contains('hidden');
      hamburger.setAttribute('aria-expanded', isExpanded);
      
      console.log(`[hamburger] Menu ${isExpanded ? 'opened' : 'closed'}`);
    });

    // Close menu on outside click
    document.addEventListener('click', function(e) {
      if (!hamburger.contains(e.target) && !menu.contains(e.target)) {
        menu.classList.add('hidden');
        hamburger.setAttribute('aria-expanded', 'false');
      }
    });

    // Close menu on ESC key
    document.addEventListener('keydown', function(e) {
      if (e.key === 'Escape' && !menu.classList.contains('hidden')) {
        menu.classList.add('hidden');
        hamburger.setAttribute('aria-expanded', 'false');
        hamburger.focus();
      }
    });

    // Close menu when clicking any menu link
    menu.addEventListener('click', function(e) {
      if (e.target.tagName === 'A') {
        menu.classList.add('hidden');
        hamburger.setAttribute('aria-expanded', 'false');
      }
    });
  }

  // ==========================================
  // MAIN INITIALIZATION
  // ==========================================
  document.addEventListener('DOMContentLoaded', async function() {
    console.log('[common.js] DOM Ready - Initializing...');

    // Load header (which includes menu container)
    await loadComponent('#header-container', resolveComponentPath('header.html'));
    
    // Load hamburger HTML structure
    await loadComponent('#menu-container', resolveComponentPath('hamburger.html'));
    
    // Build menu from JSON
    await buildHamburgerMenu();
    
    // Initialize hamburger toggle
    requestAnimationFrame(() => {
      initHamburgerMenu();
    });
    
    // Load footer component
    await loadComponent('#footer-container', resolveComponentPath('footer.html'));

    console.log('[common.js] ✓ Initialization complete');
  });

  // ==========================================
  // EXPOSE UTILITIES GLOBALLY (optional)
  // ==========================================
  window.AppUtils = {
    loadComponent,
    loadJSON,
    buildHamburgerMenu
  };

})();
/**
 * Analytics Integration
 * 
 * Add this code to the END of your common.js file
 * This will automatically load analytics.js on every page that includes common.js
 */

// Load analytics tracker on all pages
(function() {
  'use strict';
  
  // Check if analytics should be loaded
  // (You can add conditions here to exclude certain pages if needed)
  const shouldLoadAnalytics = true;
  
  if (shouldLoadAnalytics) {
    // Create script element
    const analyticsScript = document.createElement('script');
    analyticsScript.src = './common/js/analytics.js';
    analyticsScript.async = true;
    
    // Add to page
    document.head.appendChild(analyticsScript);
    
    console.log('[Common.js] Analytics loaded');
  }
})();