/* HTML5 history router — clean paths like /platform, /pricing (no #/).
   An in-page anchor may be appended: /platform#batch-upload routes to
   /platform then scrolls to id="batch-upload".

   Requires a server/SPA fallback that serves index.html for unknown paths
   (see the project _redirects file for Cloudflare Pages), plus <base href="/">
   in index.html so assets resolve from the root on any route. */
const { createContext, useContext } = React;

const RouterCtx = React.createContext({ route: '/', go: () => {} });

// Current route = pathname; in-page anchor = the real URL hash (if any).
function parseLocation() {
  return {
    route: window.location.pathname || '/',
    anchor: window.location.hash ? window.location.hash.slice(1) : null
  };
}

// Split a Link target like "/platform#batch-upload" into path + anchor.
function splitTo(to) {
  const i = to.indexOf('#');
  if (i === -1) return { path: to || '/', anchor: null };
  return { path: to.slice(0, i) || '/', anchor: to.slice(i + 1) || null };
}

// SPA navigation: push a clean URL and notify the provider. Usable anywhere
// (components without router context can call window.navigate(...)).
function navigate(to) {
  const { path, anchor } = splitTo(to);
  const url = path + (anchor ? '#' + anchor : '');
  window.history.pushState({}, '', url);
  window.dispatchEvent(new PopStateEvent('popstate'));
}

// Scroll to an in-page anchor, retrying across frames because the destination
// route component may not have committed to the DOM yet on a cross-route jump.
// Falls back to scroll-top only if the element never appears.
function scrollToAnchor(id, { smooth = true } = {}) {
  const deadline = Date.now() + 1200; // keep trying for up to ~1.2s
  const tick = () => {
    const el = document.getElementById(id);
    if (el) {
      el.scrollIntoView({ behavior: smooth ? 'smooth' : 'instant', block: 'start' });
      return;
    }
    if (Date.now() < deadline) {
      requestAnimationFrame(tick);
    } else {
      window.scrollTo({ top: 0, behavior: 'instant' });
    }
  };
  requestAnimationFrame(tick);
}

function RouterProvider({ children }) {
  const [{ route, anchor }, setState] = React.useState(parseLocation());
  React.useEffect(() => {
    // Fires on browser back/forward AND on our own navigate() (synthetic popstate).
    const onChange = () => {
      const next = parseLocation();
      setState(next);
      if (next.anchor) {
        scrollToAnchor(next.anchor);
      } else {
        window.scrollTo({ top: 0, behavior: 'instant' });
      }
    };
    window.addEventListener('popstate', onChange);
    // Honour an initial anchor on first load
    if (anchor) {
      scrollToAnchor(anchor);
    }
    return () => window.removeEventListener('popstate', onChange);
  }, []);
  const go = React.useCallback((to) => navigate(to), []);
  return <RouterCtx.Provider value={{ route, go }}>{children}</RouterCtx.Provider>;
}

function useRoute() { return React.useContext(RouterCtx); }

function Link({ to, children, style, onClick, ...rest }) {
  return (
    <a
      href={to}
      onClick={(e) => {
        // Let the browser handle new-tab / modifier / non-left clicks natively.
        if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;
        e.preventDefault();
        if (onClick) onClick(e);
        navigate(to);
      }}
      style={style}
      {...rest}
    >{children}</a>
  );
}

Object.assign(window, { RouterProvider, useRoute, Link, navigate, scrollToAnchor });
