import { Controller } from '@hotwired/stimulus';

export default class extends Controller<HTMLDivElement> {
   initialize(): void {
      const links = document.querySelectorAll(COMPONENTS['Search:Tabs:Tab:Link'].selector) as NodeListOf<HTMLDivElement>;
      links.forEach((link)=> {
         link.onclick = () => {
            link.classList.contains('active') ? this.hideTab(link) : this.activateTab(link);
         }
      });
   }

   hideTab(link: HTMLDivElement): void {
      const tab = this.element.querySelector(link.dataset['target']);
      link.classList.remove('active');
      tab.classList.remove('active');
   }

   activateTab(link: HTMLElement) {
      const tab = this.element.querySelector(link.dataset['target']);
      document.querySelectorAll(COMPONENTS['Search:Tabs:Tab:Link'].selector).forEach((item) => {
         item?.classList.remove('active');
      });
      this.element.querySelectorAll(COMPONENTS['Search:Tabs:Tab'].selector + '.active').forEach((item) => {
         item?.classList.remove('active');
      });
      document.querySelectorAll(COMPONENTS['Search:Tabs:Tab:Link'].selector + '[data-target="' + link.dataset['target'] + '"]').forEach((item) => {
         item.classList.add('active');
      });
      tab.classList.add('active');
   }
}
