/**
 * Accordion Enhancement - Optional Progressive Enhancement
 * Works without this JS - this just adds extra features
 */

class AccordionEnhancer {
  constructor() {
    this.init();
  }

  init() {
    // Find all accordion groups
    this.groups = document.querySelectorAll('.accordion-group');
    
    // Initialize exclusive accordions
    this.initExclusiveAccordions();
    
    // Add keyboard navigation
    this.initKeyboardNav();
    
    // Add URL hash support
    this.initHashSupport();
  }

  /**
   * Exclusive mode - only one accordion open at a time
   */
  initExclusiveAccordions() {
    this.groups.forEach(group => {
      if (group.hasAttribute('data-exclusive')) {
        const details = group.querySelectorAll('details');
        
        details.forEach(detail => {
          detail.addEventListener('toggle', (e) => {
            if (e.target.open) {
              // Close all other accordions in this group
              details.forEach(other => {
                if (other !== e.target && other.open) {
                  other.open = false;
                }
              });
            }
          });
        });
      }
    });
  }

  /**
   * Keyboard navigation support
   */
  initKeyboardNav() {
    document.querySelectorAll('summary').forEach(summary => {
      summary.setAttribute('tabindex', '0');
      
      summary.addEventListener('keydown', (e) => {
        const details = summary.parentElement;
        const group = details.closest('.accordion-group');
        
        if (!group) return;
        
        const allDetails = [...group.querySelectorAll('details')];
        const currentIndex = allDetails.indexOf(details);
        
        switch(e.key) {
          case 'ArrowUp':
            e.preventDefault();
            if (currentIndex > 0) {
              allDetails[currentIndex - 1].querySelector('summary').focus();
            }
            break;
            
          case 'ArrowDown':
            e.preventDefault();
            if (currentIndex < allDetails.length - 1) {
              allDetails[currentIndex + 1].querySelector('summary').focus();
            }
            break;
            
          case 'Home':
            e.preventDefault();
            allDetails[0].querySelector('summary').focus();
            break;
            
          case 'End':
            e.preventDefault();
            allDetails[allDetails.length - 1].querySelector('summary').focus();
            break;
        }
      });
    });
  }

  /**
   * URL hash support - open accordion based on URL hash
   */
  initHashSupport() {
    // Check for hash on load
    this.openFromHash();
    
    // Listen for hash changes
    window.addEventListener('hashchange', () => this.openFromHash());
    
    // Add IDs to details if they don't have them
    document.querySelectorAll('details').forEach((details, index) => {
      if (!details.id && details.querySelector('summary')) {
        // Generate ID from summary text
        const summaryText = details.querySelector('summary').textContent;
        const id = this.slugify(summaryText) || `accordion-${index}`;
        details.id = id;
      }
    });
  }

  openFromHash() {
    const hash = window.location.hash.slice(1);
    if (hash) {
      const target = document.getElementById(hash);
      if (target && target.tagName === 'DETAILS') {
        target.open = true;
        target.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        
        // Focus for accessibility
        setTimeout(() => {
          target.querySelector('summary')?.focus();
        }, 100);
      }
    }
  }

  slugify(text) {
    return text
      .toLowerCase()
      .trim()
      .replace(/[^\w\s-]/g, '')
      .replace(/[\s_-]+/g, '-')
      .replace(/^-+|-+$/g, '');
  }
}

// Initialize when DOM is ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => new AccordionEnhancer());
} else {
  new AccordionEnhancer();
}

// Export for module use
export default AccordionEnhancer;