/* KayaCore — tiny hash router + nav context shared across the site.
   Routes:  #/  ·  #/v/<id>  ·  #/pricing  ·  #/contact
   Components read { route, navigate, goSection } via useRouter(). */
const KcRouterCtx = React.createContext({ route: { name: 'home' }, navigate() {}, goSection() {} });
function useRouter() { return React.useContext(KcRouterCtx); }

function kcParseHash() {
  const raw = (window.location.hash || '#/').replace(/^#/, '');
  const parts = raw.split('/').filter(Boolean);
  if (parts[0] === 'v' && parts[1]) return { name: 'vertical', param: parts[1] };
  if (parts[0] === 'pricing') return { name: 'pricing' };
  if (parts[0] === 'contact') return { name: 'contact', param: parts[1] || null };
  return { name: 'home' };
}

function KcRouterProvider({ children }) {
  const [route, setRoute] = React.useState(kcParseHash());
  const pendingScroll = React.useRef(null);

  React.useEffect(() => {
    const onHash = () => setRoute(kcParseHash());
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // On route change: jump to top, unless we have a pending in-page section scroll.
  React.useEffect(() => {
    if (pendingScroll.current) {
      const id = pendingScroll.current;
      pendingScroll.current = null;
      requestAnimationFrame(() => {
        const el = document.getElementById(id);
        if (el) window.scrollTo({ top: el.offsetTop - 70, behavior: 'smooth' });
      });
    } else {
      window.scrollTo({ top: 0, behavior: 'auto' });
    }
  }, [route]);

  const navigate = React.useCallback((to) => {
    const target = to === '/' ? '#/' : '#' + to;
    if (window.location.hash === target) {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } else {
      window.location.hash = target;
    }
  }, []);

  // Scroll to a homepage section; route home first if needed.
  const goSection = React.useCallback((id) => {
    if (kcParseHash().name === 'home') {
      const el = document.getElementById(id);
      if (el) window.scrollTo({ top: el.offsetTop - 70, behavior: 'smooth' });
    } else {
      pendingScroll.current = id;
      window.location.hash = '#/';
    }
  }, []);

  const value = React.useMemo(() => ({ route, navigate, goSection }), [route, navigate, goSection]);
  return <KcRouterCtx.Provider value={value}>{children}</KcRouterCtx.Provider>;
}

Object.assign(window, { KcRouterCtx, useRouter, KcRouterProvider, kcParseHash });
