/**
 * Header Dropdown Menus
 * Handle dropdown menu interactions
 */

document.addEventListener('DOMContentLoaded', () => {
  const dropdowns = document.querySelectorAll('.header-dropdown');
  
  dropdowns.forEach(dropdown => {
    const button = dropdown.querySelector('.header-btn');
    const menu = dropdown.querySelector('.header-dropdown-menu');
    
    if (!button || !menu) return;
    
    // Toggle dropdown on button click
    button.addEventListener('click', (e) => {
      e.stopPropagation();
      
      // Close other dropdowns
      dropdowns.forEach(other => {
        if (other !== dropdown) {
          other.classList.remove('active');
        }
      });
      
      // Toggle current dropdown
      dropdown.classList.toggle('active');
    });
    
    // Close dropdown when clicking menu items
    const menuItems = menu.querySelectorAll('.dropdown-item');
    menuItems.forEach(item => {
      item.addEventListener('click', () => {
        dropdown.classList.remove('active');
      });
    });
  });
  
  // Close dropdowns when clicking outside
  document.addEventListener('click', (e) => {
    if (!e.target.closest('.header-dropdown')) {
      dropdowns.forEach(dropdown => {
        dropdown.classList.remove('active');
      });
    }
  });
  
  // Close dropdowns on Escape key
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      dropdowns.forEach(dropdown => {
        dropdown.classList.remove('active');
      });
    }
  });
  
  // Enable/disable AI menu based on image state
  const aiMenuBtn = document.getElementById('aiMenuBtn');
  const editMenuBtn = document.getElementById('editMenuBtn');
  
  // Watch for image changes to enable menus
  const observer = new MutationObserver(() => {
    const hasImage = document.getElementById('previewImage')?.src;
    if (hasImage && aiMenuBtn) {
      aiMenuBtn.disabled = false;
    }
    if (hasImage && editMenuBtn) {
      editMenuBtn.disabled = false;
    }
  });
  
  const imageContainer = document.getElementById('imageContainer');
  if (imageContainer) {
    observer.observe(imageContainer, { 
      attributes: true, 
      attributeFilter: ['style'] 
    });
  }
  
  console.log('✓ Header dropdown menus initialized');
});
