/* History-based router (clean URLs, no #/) */
const { useState, useEffect, useCallback, createContext, useContext } = React;

const RouterCtx = createContext({ path: '/', navigate: () => {}, region: 'GLOBAL', setRegion: () => {} });

function parsePath() {
  return window.location.pathname || '/';
}

function RouterProvider({ children }) {
  const [path, setPath] = useState(parsePath());
  const [region, setRegionState] = useState(() => localStorage.getItem('cortexa-region') || 'GLOBAL');

  useEffect(() => {
    const onPop = () => {
      setPath(parsePath());
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  const navigate = useCallback((to) => {
    if (!to) return;
    if (to.startsWith('http')) { window.open(to, '_blank'); return; }
    window.history.pushState(null, '', to);
    setPath(to);
    window.scrollTo({ top: 0, behavior: 'instant' });
  }, []);

  const setRegion = useCallback((r) => {
    setRegionState(r);
    localStorage.setItem('cortexa-region', r);
  }, []);

  return (
    <RouterCtx.Provider value={{ path, navigate, region, setRegion }}>
      {children}
    </RouterCtx.Provider>
  );
}

function useRouter() { return useContext(RouterCtx); }

function Link({ to, className, children, onClick, ...rest }) {
  const { navigate } = useRouter();
  return (
    <a
      href={to}
      className={className}
      onClick={(e) => { e.preventDefault(); if (onClick) onClick(e); navigate(to); }}
      {...rest}
    >
      {children}
    </a>
  );
}

/* Reveal-on-scroll hook */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal:not(.in)');
    if (!('IntersectionObserver' in window)) {
      els.forEach((el) => el.classList.add('in'));
      return;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add('in');
          io.unobserve(entry.target);
        }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -40px 0px' });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

Object.assign(window, { RouterProvider, useRouter, Link, useReveal });
