// Pellex router. Hash-based, single-document multi-page navigation.
// Exposes window.pellexNav(page) for any deep CTA to navigate.
// Pages: landing | map | kit | checkout | success | resource | business

window.pellexNav = function (page, opts = {}) {
  window.dispatchEvent(new CustomEvent('pellexnav', { detail: { page, opts } }));
};

function usePellexNav() {
  const initial = (window.location.hash || '#landing').slice(1).split('/')[0] || 'landing';
  const [page, setPage] = React.useState(initial);
  const [opts, setOpts] = React.useState({});

  React.useEffect(() => {
    const onHash = () => {
      const p = (window.location.hash || '#landing').slice(1).split('/')[0] || 'landing';
      setPage(p);
    };
    const onNav = (e) => {
      const { page, opts } = e.detail;
      window.history.pushState(null, '', '#' + page);
      setPage(page);
      setOpts(opts || {});
      requestAnimationFrame(() => {
        const sc = document.querySelector('.pellex-scroll');
        if (sc) sc.scrollTo({ top: 0, behavior: 'instant' });
      });
    };
    window.addEventListener('hashchange', onHash);
    window.addEventListener('pellexnav', onNav);
    return () => {
      window.removeEventListener('hashchange', onHash);
      window.removeEventListener('pellexnav', onNav);
    };
  }, []);

  return [page, opts, (next, o) => window.pellexNav(next, o)];
}

window.usePellexNav = usePellexNav;
