import './style.css';

/**
 * Handles panel switching for the Posts Tab widget.
 */
const initPostsTab = (widget) => {
  const buttons = Array.from(widget.querySelectorAll('.calio-posts-tab-button'));
  const panels = Array.from(widget.querySelectorAll('.calio-posts-tab-panel'));

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

  const activate = (targetId) => {
    buttons.forEach((button) => {
      const isActive = button.dataset.target === targetId;
      button.classList.toggle('is-active', isActive);
      button.setAttribute('aria-selected', isActive ? 'true' : 'false');
    });

    panels.forEach((panel) => {
      panel.classList.toggle('is-active', panel.id === targetId);
      panel.classList.toggle('is-entering', panel.id === targetId);
    });
  };

  buttons.forEach((button) => {
    button.addEventListener('click', () => {
      activate(button.dataset.target || '');
    });
  });
};

const initPostsTabScope = (scope = document) => {
  const root = scope instanceof HTMLElement || scope instanceof Document ? scope : document;
  root.querySelectorAll('.calio-posts-tab').forEach(initPostsTab);
};

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

let calioPostsTabHookBound = false;
const bindElementorPostsTab = () => {
  if (calioPostsTabHookBound) {
    return true;
  }

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

  window.elementorFrontend.hooks.addAction('frontend/element_ready/calio-posts-tab.default', ($scope) => {
    const root = $scope?.[0] || document;
    initPostsTabScope(root);
  });

  calioPostsTabHookBound = true;
  return true;
};

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