/* ============================================================
   Minimal client-side router — shimmed as window.ReactRouterDOM
   so the rest of the app can use the familiar Link/Routes/Route/
   useParams/useLocation/Navigate API without depending on an
   external CDN UMD build (unreliable across versions).
   ============================================================ */
const { createContext: createContext_r, useContext: useContext_r, useState: useState_r, useEffect: useEffect_r, Children: Children_r } = React;

const RouterCtx = createContext_r(null);
const ParamsCtx = createContext_r({});

// The app may be served from a nested path (e.g. this design tool's preview
// URL, or a static file opened directly) rather than a domain root. Detect
// that by looking for a literal ".../index.html" suffix — real clean-URL
// deployments (Vercel rewrites) never have one, so BASE is "/" there.
const BASE = (() => {
  const m = window.location.pathname.match(/^(.*\/)index\.html$/);
  return m ? m[1] : '/';
})();
function toAbsolute(to) { return BASE === '/' ? to : BASE.slice(0, -1) + to; }
function toRelative(pathname) {
  if (BASE === '/') return pathname;
  if (!pathname.startsWith(BASE)) return pathname;
  const rest = pathname.slice(BASE.length);
  return (rest === '' || rest === 'index.html') ? '/' : '/' + rest;
}
function currentPath() { return toRelative(window.location.pathname) + window.location.hash; }

function BrowserRouter({ children }) {
  const [path, setPath] = useState_r(currentPath());
  useEffect_r(() => {
    const onPop = () => setPath(currentPath());
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);
  const navigate = (to, opts = {}) => {
    const method = opts.replace ? 'replaceState' : 'pushState';
    window.history[method]({}, '', toAbsolute(to));
    setPath(to);
  };
  return <RouterCtx.Provider value={{ path, navigate }}>{children}</RouterCtx.Provider>;
}

function useLocation() {
  const { path } = useContext_r(RouterCtx);
  const [pathname, hash = ''] = path.split('#');
  return { pathname: pathname || '/', hash: hash ? `#${hash}` : '' };
}

function useNavigate() {
  const { navigate } = useContext_r(RouterCtx);
  return navigate;
}

function useParams() { return useContext_r(ParamsCtx); }

function Link({ to, children, onClick, ...rest }) {
  const navigate = useNavigate();
  return (
    <a
      href={toAbsolute(to)}
      {...rest}
      onClick={(e) => {
        if (onClick) onClick(e);
        if (e.defaultPrevented) return;
        if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
        e.preventDefault();
        navigate(to);
      }}
    >{children}</a>
  );
}

function Navigate({ to, replace }) {
  const navigate = useNavigate();
  useEffect_r(() => { navigate(to, { replace }); }, []);
  return null;
}

function compilePath(path) {
  if (path === '*') return { regex: /^.*$/, keys: [] };
  const keys = [];
  const pattern = path.replace(/:[^/]+/g, (m) => { keys.push(m.slice(1)); return '([^/]+)'; });
  return { regex: new RegExp(`^${pattern}/?$`), keys };
}

function Route() { return null; }

function Routes({ children }) {
  const { pathname } = useLocation();
  const items = Children_r.toArray(children);
  for (const child of items) {
    const { path, element } = child.props;
    const { regex, keys } = compilePath(path);
    const m = regex.exec(pathname);
    if (m) {
      const params = {};
      keys.forEach((k, i) => { params[k] = m[i + 1]; });
      return <ParamsCtx.Provider value={params}>{element}</ParamsCtx.Provider>;
    }
  }
  return null;
}

window.ReactRouterDOM = { BrowserRouter, Routes, Route, Link, Navigate, useParams, useLocation, useNavigate };

/* ============================================================
   SEO + scroll-restoration helpers
   ============================================================ */
const { useEffect: useEffect_lib } = React;

function useSEO({ title, description, path }) {
  useEffect_lib(() => {
    if (title) document.title = title;
    const url = `https://cyrion.ai${path || '/'}`;
    setMetaTag('description', description);
    setLinkTag('canonical', url);
    setPropTag('og:title', title);
    setPropTag('og:description', description);
    setPropTag('og:url', url);
    window.scrollTo(0, 0);
  }, [title, description, path]);
}

function setMetaTag(name, content) {
  if (!content) return;
  let el = document.querySelector(`meta[name="${name}"]`);
  if (!el) { el = document.createElement('meta'); el.setAttribute('name', name); document.head.appendChild(el); }
  el.setAttribute('content', content);
}
function setPropTag(property, content) {
  if (!content) return;
  let el = document.querySelector(`meta[property="${property}"]`);
  if (!el) { el = document.createElement('meta'); el.setAttribute('property', property); document.head.appendChild(el); }
  el.setAttribute('content', content);
}
function setLinkTag(rel, href) {
  let el = document.querySelector(`link[rel="${rel}"]`);
  if (!el) { el = document.createElement('link'); el.setAttribute('rel', rel); document.head.appendChild(el); }
  el.setAttribute('href', href);
}

/** Smooth-scrolls to the #hash target whenever the route/hash changes. */
function ScrollToHash() {
  const location = useLocation();
  useEffect_lib(() => {
    if (location.hash) {
      const id = location.hash.slice(1);
      const el = document.getElementById(id);
      if (el) { setTimeout(() => el.scrollIntoView({ behavior: 'smooth', block: 'start' }), 60); return; }
    }
    window.scrollTo(0, 0);
  }, [location.pathname, location.hash]);
  return null;
}

Object.assign(window, { useSEO, ScrollToHash });
