const enableTab = (drawer, index) => {
  const nodes = drawer.querySelectorAll('[data-tab]');

  // disable all
  nodes.forEach(node => node.classList.remove('active'));

  // enable by tab id
  const active = drawer.querySelector('[data-tab="' + (index + 1) + '"]');
  if (active) {
    active.classList.add('active');
  }
};

const tabsNavigator = () => {
  const btns = document.querySelectorAll('ul.tab-navigator li');
  const indicator = document.querySelector('ul.tab-navigator .indicator');
  const drawer = document.querySelector('.navigator-drawer');

  if (btns.length && indicator && drawer) {
    let indi = 0;
    const width = btns[0].offsetWidth; // indicator size based on li-s

    // on init, check if there is a data-current-tab on indicator (initial state)
    if (indicator.dataset.currentTab) {
      indi = parseInt(indicator.dataset.currentTab);
    }

    // set initial indicator size/position
    indicator.style.width = width + 'px';
    indicator.style.marginLeft = (indi * width) + 'px';

    // enable first/default tab
    enableTab(drawer, indi);

    btns.forEach(btn => {
      btn.addEventListener('click', evt => {
        // get element's data-tab
        const tab = parseInt(btn.dataset.tab) - 1;

        // set indicator margin
        indicator.style.marginLeft = tab * width + 'px';

        // save the state for next init (in case of resize, for example)
        indicator.dataset.currentTab = tab;

        // activate current tab
        enableTab(drawer, tab);
      });
    });
  }
};

export default tabsNavigator;
