import './style.css';

/**
 * Handles state and keyboard navigation for the Fancy Tabs widget.
 */
const initFancyTabs = (widget) => {
  if (widget.dataset.calioFancyTabsInit === 'yes') {
    return;
  }

  widget.dataset.calioFancyTabsInit = 'yes';

  const buttons = Array.from(widget.querySelectorAll('.calio-fancy-tabs-button'));
  const panels = Array.from(widget.querySelectorAll('.calio-fancy-tabs-panel'));
  const mobileToggles = Array.from(widget.querySelectorAll('.calio-fancy-tabs-mobile-toggle'));
  const orientation = widget.dataset.orientation === 'vertical' ? 'vertical' : 'horizontal';
  const mobileMode = widget.dataset.mobileMode || 'tabs';
  const mediaQuery = window.matchMedia('(max-width: 767px)');

  if (buttons.length === 0 || panels.length === 0) {
    return;
  }

  const isAccordionMode = () => mobileMode === 'accordion' && mediaQuery.matches;

  const setActiveState = (button, keepClosed = false) => {
    const targetId = button?.dataset.target || '';

    buttons.forEach((item) => {
      const isActive = item === button;
      item.classList.toggle('is-active', isActive);
      item.setAttribute('aria-selected', isActive ? 'true' : 'false');
      item.setAttribute('tabindex', isActive ? '0' : '-1');
    });

    panels.forEach((panel) => {
      const isActive = !keepClosed && panel.id === targetId;
      panel.classList.toggle('is-active', isActive);
      panel.hidden = isAccordionMode() ? false : !isActive;

      const toggle = panel.querySelector('.calio-fancy-tabs-mobile-toggle');
      if (toggle) {
        toggle.setAttribute('aria-expanded', isActive ? 'true' : 'false');
      }
    });
  };

  const ensureDesktopState = () => {
    const activeButton = buttons.find((button) => button.classList.contains('is-active')) || buttons[0];
    if (activeButton) {
      setActiveState(activeButton);
    }
  };

  buttons.forEach((button, index) => {
    button.addEventListener('click', () => {
      setActiveState(button);
    });

    button.addEventListener('keydown', (event) => {
      const isPrevKey = orientation === 'vertical'
        ? event.key === 'ArrowUp'
        : event.key === 'ArrowLeft';
      const isNextKey = orientation === 'vertical'
        ? event.key === 'ArrowDown'
        : event.key === 'ArrowRight';

      if (event.key === 'Home') {
        event.preventDefault();
        buttons[0]?.focus();
        setActiveState(buttons[0]);
        return;
      }

      if (event.key === 'End') {
        event.preventDefault();
        buttons[buttons.length - 1]?.focus();
        setActiveState(buttons[buttons.length - 1]);
        return;
      }

      if (!isPrevKey && !isNextKey) {
        return;
      }

      event.preventDefault();

      const nextIndex = isNextKey
        ? (index + 1) % buttons.length
        : (index - 1 + buttons.length) % buttons.length;

      buttons[nextIndex]?.focus();
      setActiveState(buttons[nextIndex]);
    });
  });

  mobileToggles.forEach((toggle) => {
    toggle.addEventListener('click', () => {
      if (!isAccordionMode()) {
        return;
      }

      const button = buttons.find((item) => item.dataset.target === toggle.dataset.target);
      const panel = panels.find((item) => item.id === toggle.dataset.target);
      const isOpen = panel?.classList.contains('is-active');

      if (!button || !panel) {
        return;
      }

      if (isOpen) {
        setActiveState(button, true);
        return;
      }

      setActiveState(button);
    });
  });

  const syncMode = () => {
    if (isAccordionMode()) {
      const openButton = buttons.find((button) => button.classList.contains('is-active')) || buttons[0];
      if (openButton) {
        setActiveState(openButton);
      }
      return;
    }

    ensureDesktopState();
  };

  syncMode();
  mediaQuery.addEventListener('change', syncMode);
};

const initAllFancyTabs = (scope = document) => {
  scope.querySelectorAll('.calio-fancy-tabs').forEach(initFancyTabs);
};

document.addEventListener('DOMContentLoaded', () => {
  initAllFancyTabs(document);
});

let calioFancyTabsHookBound = false;
const bindElementorFancyTabs = () => {
  if (calioFancyTabsHookBound) {
    return true;
  }

  if (!window.elementorFrontend?.hooks) {
    return false;
  }

  window.elementorFrontend.hooks.addAction('frontend/element_ready/calio-fancy-tabs.default', ($scope) => {
    const root = $scope?.[0] || null;
    if (root) {
      initAllFancyTabs(root);
    }
  });

  calioFancyTabsHookBound = true;
  return true;
};

window.addEventListener('elementor/frontend/init', bindElementorFancyTabs);
if (!bindElementorFancyTabs()) {
  let attempts = 0;
  const timer = window.setInterval(() => {
    attempts += 1;
    if (bindElementorFancyTabs() || attempts >= 40) {
      window.clearInterval(timer);
    }
  }, 250);
}
