/**
 * This API is reusable just pass in the root dom node to the constructor
 */

class TabbedContent {
  tabIds = [];


  constructor(el) {
    this.rootEl = el;

    this.selectBox = this.rootEl.querySelector('.tabbed-content-selector');
    this.tabElements = this.rootEl.querySelectorAll('.tabbed-content-tab');
    this.articles = this.rootEl.querySelectorAll('.tabbed-content-article');

    if (!el || !this.selectBox || !this.tabElements || !this.articles) {
      throw new Error('Error initializing DOM');
    }

    this.setTabIdsFromAnchorEls();
    this.init();
  }

  /**
   * ids are set from textContent of each anchor
   * must watch for putting special chars in anchor content
   */
  setTabIdsFromAnchorEls() {
    const options = [];

    [...this.tabElements].forEach((anchor, idx) => {
      this.tabIds.push(
        anchor.textContent
          .trim()
          .replace(/[^\w\s-]/g, '')
          .replace(/\s/g, '-')
          .toLowerCase()
      );

      anchor.href = `#${this.tabIds[idx]}`;

      options.push(`<option value="${this.tabIds[idx]}">${anchor.textContent}</option>`);
    });

    [...this.articles].forEach((article, idx) => article.setAttribute('data-tab-id', this.tabIds[idx]));

    this.selectBox.innerHTML = options.join('');
  }

  isRegisteredTab(tab) {
    return this.tabIds.includes(tab);
  }

  toggleContent(tab) {
    const selectedContent = this.rootEl.querySelector(`[data-tab-id=${tab}]`);
    const content = this.rootEl.querySelectorAll('.tabbed-content-article');

    if (!selectedContent) return;

    content.forEach(article => article.classList.add('hidden'));
    selectedContent.classList.remove('hidden');
    selectedContent.classList.add('block');
  }

  toggleNav(tab) {
    this.selectBox.value = tab;

    const nav = this.rootEl.querySelectorAll('.tabbed-content-tab');
    const selectedNav = this.rootEl.querySelector(`a[href="#${tab}"]`);
    if (!selectedNav) return;

    nav.forEach(navItem => navItem.classList.remove('active'));
    selectedNav.classList.toggle('active');
  }

  handleHashChange = e => {
    e.preventDefault();

    const tab = window.location.hash.substring(1);
    if (!this.isRegisteredTab(tab)) {
      return;
    }
    this.toggleContent(tab);
    this.toggleNav(tab);
  };

  handleSelectChange = e => (window.location.hash = e.target.value);

  /**
   * If hash is present use it, if not it will default to the first tab for every
   * registered tabber and wait for a hash change, hash chnage will not effect any other
   * tabber on the page, it will remain dormant until it is triggered by a hash change for an id that it owns
   */
  init() {
    window.addEventListener('hashchange', this.handleHashChange);
    this.selectBox.addEventListener('change', this.handleSelectChange);

    const tab = window.location.hash.substring(1);

    if (this.isRegisteredTab(tab)) {
      this.toggleContent(tab);
      this.toggleNav(tab);
    } else {
      this.toggleContent(this.tabIds[0]);
      this.toggleNav(this.tabIds[0]);
    }
  }
}





