export class TabsComponent {
  constructor(element, options = {}) {
    this.element = element;
    this.options = {
      activeClass: 'tabs__tab--active',
      panelActiveClass: 'tabs__panel--active',
      keyboardNavigation: true,
      autoResponsive: true,
      ...options
    };

    this.tabs = [];
    this.panels = [];
    this.activeIndex = 0;

    this.init();
  }

  init() {
    this.bindElements();
    this.bindEvents();
    this.setInitialState();

    if (this.options.autoResponsive) {
      this.handleResponsive();
    }
  }

  bindElements() {
    this.tabNav = this.element.querySelector('.tabs__nav');
    this.tabContent = this.element.querySelector('.tabs__content');
    this.tabs = Array.from(this.element.querySelectorAll('.tabs__tab'));
    this.panels = Array.from(this.element.querySelectorAll('.tabs__panel'));

    if (!this.tabNav || !this.tabContent || this.tabs.length === 0) {
      console.warn('TabsComponent: Missing required elements');
      return;
    }
  }

  bindEvents() {
    // Tab click events
    this.tabs.forEach((tab, index) => {
      tab.addEventListener('click', (e) => {
        e.preventDefault();
        this.activateTab(index);
      });
    });

    // Keyboard navigation
    if (this.options.keyboardNavigation) {
      this.tabNav.addEventListener('keydown', (e) => {
        this.handleKeyboard(e);
      });
    }

    // Responsive handling
    if (this.options.autoResponsive) {
      window.addEventListener('resize', () => {
        this.handleResponsive();
      });
    }
  }

  setInitialState() {
    // Find initially active tab or default to first
    const activeTab = this.tabs.find(tab => 
      tab.classList.contains(this.options.activeClass)
    );
    
    if (activeTab) {
      this.activeIndex = this.tabs.indexOf(activeTab);
    }

    this.activateTab(this.activeIndex);
  }

  activateTab(index) {
    if (index < 0 || index >= this.tabs.length) return;

    // Remove active state from all tabs and panels
    this.tabs.forEach(tab => {
      tab.classList.remove(this.options.activeClass);
      tab.setAttribute('aria-selected', 'false');
      tab.setAttribute('tabindex', '-1');
    });

    this.panels.forEach(panel => {
      panel.classList.remove(this.options.panelActiveClass);
      panel.setAttribute('aria-hidden', 'true');
    });

    // Add active state to selected tab and panel
    const activeTab = this.tabs[index];
    const activePanel = this.panels[index];

    if (activeTab && activePanel) {
      activeTab.classList.add(this.options.activeClass);
      activeTab.setAttribute('aria-selected', 'true');
      activeTab.setAttribute('tabindex', '0');

      activePanel.classList.add(this.options.panelActiveClass);
      activePanel.setAttribute('aria-hidden', 'false');

      this.activeIndex = index;

      // Emit custom event
      this.element.dispatchEvent(new CustomEvent('tabchange', {
        detail: { 
          index, 
          tab: activeTab, 
          panel: activePanel 
        }
      }));
    }
  }

  handleKeyboard(e) {
    const { activeElement } = document;
    const currentIndex = this.tabs.indexOf(activeElement);

    if (currentIndex === -1) return;

    let newIndex = currentIndex;

    switch (e.key) {
      case 'ArrowLeft':
        e.preventDefault();
        newIndex = currentIndex > 0 ? currentIndex - 1 : this.tabs.length - 1;
        break;
      case 'ArrowRight':
        e.preventDefault();
        newIndex = currentIndex < this.tabs.length - 1 ? currentIndex + 1 : 0;
        break;
      case 'Home':
        e.preventDefault();
        newIndex = 0;
        break;
      case 'End':
        e.preventDefault();
        newIndex = this.tabs.length - 1;
        break;
      case 'Enter':
      case ' ':
        e.preventDefault();
        this.activateTab(currentIndex);
        return;
    }

    if (newIndex !== currentIndex) {
      this.tabs[newIndex].focus();
      this.activateTab(newIndex);
    }
  }

  handleResponsive() {
    const isMobile = window.innerWidth < 768;
    
    if (isMobile && !this.element.classList.contains('tabs--responsive')) {
      this.element.classList.add('tabs--responsive');
      this.convertToAccordion();
    } else if (!isMobile && this.element.classList.contains('tabs--responsive')) {
      this.element.classList.remove('tabs--responsive');
      this.convertToTabs();
    }
  }

  convertToAccordion() {
    // Add mobile accordion behavior
    this.panels.forEach((panel, index) => {
      const tab = this.tabs[index];
      if (tab && panel) {
        panel.setAttribute('data-tab-title', tab.textContent);
        
        panel.addEventListener('click', (e) => {
          if (e.target === panel.querySelector('::before') || 
              e.target.closest('.tabs__panel') === panel) {
            this.togglePanel(index);
          }
        });
      }
    });
  }

  convertToTabs() {
    // Remove mobile accordion behavior
    this.panels.forEach(panel => {
      panel.removeAttribute('data-tab-title');
    });
  }

  togglePanel(index) {
    const panel = this.panels[index];
    const isActive = panel.classList.contains(this.options.panelActiveClass);
    
    if (isActive) {
      panel.classList.remove(this.options.panelActiveClass);
    } else {
      this.activateTab(index);
    }
  }

  // Public API
  next() {
    const nextIndex = this.activeIndex < this.tabs.length - 1 ? 
      this.activeIndex + 1 : 0;
    this.activateTab(nextIndex);
  }

  prev() {
    const prevIndex = this.activeIndex > 0 ? 
      this.activeIndex - 1 : this.tabs.length - 1;
    this.activateTab(prevIndex);
  }

  goTo(index) {
    this.activateTab(index);
  }

  destroy() {
    // Remove event listeners and reset state
    this.tabs.forEach(tab => {
      tab.removeAttribute('aria-selected');
      tab.removeAttribute('tabindex');
    });

    this.panels.forEach(panel => {
      panel.removeAttribute('aria-hidden');
    });

    this.element.classList.remove('tabs--responsive');
  }
}