/* global React, ReactDOM, Nav, Footer, Homepage,
  AorbitOverview, AorbitLayerPage, AorbitArchitecturePage,
  ArchitectureGap, CaseStudies,
  Augmentation, Training, Research,
  Banking, DigitalAssets, Government,
  DataSovereignty, Security,
  Blog, Whitepapers, About, Careers, TalkToArchitect, Demo,
  PrivacyPolicy, TermsOfUse, CookiePolicy, AccessibilityStatement,
  CookieConsent, GatedDownloadHost, SEOHead, Breadcrumbs,
  TweaksPanel, useTweaks, TweakSection, TweakRadio, TweakSelect, TweakToggle, TweakColor
*/

const { useState, useEffect } = React;

/* ===== Hash-based router =====
   Hashes can carry query strings: `#/talk-to-an-architect?interest=research`.
   We strip the query for route matching and stash the parsed params on
   `window.__routeQuery` so any form can pre-fill from them.
*/
function parseHash() {
  const h = window.location.hash.replace(/^#/, "");
  // Anchor fragments (#positions) are NOT query params — strip them too.
  const queryIdx = h.indexOf("?");
  const anchorIdx = h.indexOf("#");
  const cuts = [queryIdx, anchorIdx].filter((i) => i >= 0);
  const cut = cuts.length ? Math.min(...cuts) : -1;
  const path = cut >= 0 ? h.slice(0, cut) : h;
  const query = {};
  if (queryIdx >= 0) {
    const qs = h.slice(queryIdx + 1).split("#")[0];
    new URLSearchParams(qs).forEach((v, k) => { query[k] = v; });
  }
  const anchor = anchorIdx >= 0 ? h.slice(anchorIdx + 1) : "";
  return { path: path || "/", query, anchor };
}

function useRoute() {
  const [state, setState] = useState(() => parseHash());
  useEffect(() => {
    const onHash = () => {
      const next = parseHash();
      setState(next);
      window.__routeQuery = next.query;
      // Anchor scrolls handled by browser; otherwise jump to top.
      if (!next.anchor) {
        window.scrollTo({ top: 0, behavior: "instant" });
      } else {
        // Defer until the new page mounts.
        requestAnimationFrame(() => {
          const el = document.getElementById(next.anchor);
          if (el) el.scrollIntoView({ block: "start" });
        });
      }
    };
    window.__routeQuery = state.query;
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  const navigate = (path) => {
    window.location.hash = path;
  };
  return [state.path, navigate, state.query];
}

/* Hook for forms: returns parsed query object, re-renders on hashchange. */
function useRouteQuery() {
  const [q, setQ] = useState(() => parseHash().query);
  useEffect(() => {
    const on = () => setQ(parseHash().query);
    window.addEventListener("hashchange", on);
    return () => window.removeEventListener("hashchange", on);
  }, []);
  return q;
}
window.useRouteQuery = useRouteQuery;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroVariant": "v1",
  "dataFlow": "pipeline",
  "density": "comfortable",
  "motion": "confident",
  "accent": "#00D4AA"
}/*EDITMODE-END*/;

function App() {
  const [route, navigate] = useRoute();
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Apply density to body
  useEffect(() => {
    document.body.className = `density-${tweaks.density || "comfortable"}`;
  }, [tweaks.density]);

  // Apply accent to CSS var (curated swatches)
  useEffect(() => {
    if (tweaks.accent && tweaks.accent !== "#00D4AA") {
      document.documentElement.style.setProperty("--teal", tweaks.accent);
    } else {
      document.documentElement.style.removeProperty("--teal");
    }
  }, [tweaks.accent]);

  // Motion control
  useEffect(() => {
    if (tweaks.motion === "off") {
      const style = document.createElement("style");
      style.id = "no-motion";
      style.textContent = "*, *::before, *::after { animation-duration: 0.001ms !important; transition-duration: 0.001ms !important; }";
      document.head.appendChild(style);
      return () => { document.getElementById("no-motion")?.remove(); };
    }
  }, [tweaks.motion]);

  return (
    <>
      <Nav route={route} navigate={navigate} />
      <SEOHead route={route} />
      <Breadcrumbs route={route} navigate={navigate} />
      <Router route={route} navigate={navigate} tweaks={tweaks} setTweak={setTweak} />
      <Footer navigate={navigate} />
      <CookieConsent />
      <GatedDownloadHost />
      <TweaksUI tweaks={tweaks} setTweak={setTweak} />
    </>
  );
}

function Router({ route, navigate, tweaks, setTweak }) {
  // Homepage
  if (route === "/" || route === "") return <Homepage navigate={navigate} tweaks={tweaks} setTweak={setTweak} />;

  // AORBIT
  if (route === "/aorbit") return <AorbitOverview navigate={navigate} />;
  if (route === "/aorbit/foundation") return <AorbitLayerPage layer="foundation" navigate={navigate} />;
  if (route === "/aorbit/intelligence") return <AorbitLayerPage layer="intelligence" navigate={navigate} />;
  if (route === "/aorbit/frontier") return <AorbitLayerPage layer="frontier" navigate={navigate} />;
  if (route === "/aorbit/architecture") return <AorbitArchitecturePage navigate={navigate} />;

  // Services
  if (route === "/services/augmentation") return <Augmentation navigate={navigate} />;
  if (route === "/services/training") return <Training navigate={navigate} />;
  if (route === "/services/research") return <Research navigate={navigate} />;

  // Industries
  if (route === "/industries/banking") return <Banking navigate={navigate} />;
  if (route === "/industries/digital-assets") return <DigitalAssets navigate={navigate} />;
  if (route === "/industries/government") return <Government navigate={navigate} />;

  // Why Doblier
  if (route === "/why-doblier/architecture-gap") return <ArchitectureGap navigate={navigate} />;
  if (route === "/why-doblier/data-sovereignty") return <DataSovereignty navigate={navigate} />;
  if (route === "/why-doblier/case-studies") return <CaseStudies navigate={navigate} />;
  if (route === "/why-doblier/security") return <Security navigate={navigate} />;

  // Resources
  if (route === "/resources/blog") return <Blog navigate={navigate} />;
  if (route === "/resources/whitepapers") return <Whitepapers navigate={navigate} />;

  // Company
  if (route === "/company/about") return <About navigate={navigate} />;
  if (route === "/company/careers") return <Careers navigate={navigate} />;

  // CTA
  // The CTA Destination Map references /contact/architect — we keep the
  // existing /talk-to-an-architect route and alias /contact/architect to it.
  if (route === "/talk-to-an-architect" || route === "/contact/architect") return <TalkToArchitect navigate={navigate} />;
  if (route === "/contact/demo") return <Demo navigate={navigate} />;

  // Legal
  if (route === "/privacy") return <PrivacyPolicy navigate={navigate} />;
  if (route === "/terms") return <TermsOfUse navigate={navigate} />;
  if (route === "/cookies") return <CookiePolicy navigate={navigate} />;
  if (route === "/accessibility") return <AccessibilityStatement navigate={navigate} />;

  // 404 fallback
  return (
    <main style={{ padding: "120px 32px", textAlign: "center", minHeight: "60vh" }}>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.08em", color: "var(--teal)" }}>// 404</div>
      <h1 style={{ marginTop: 24 }}>This page hasn't been wired yet.</h1>
      <p className="lead" style={{ margin: "32px auto" }}>
        The route <code style={{ color: "var(--teal)" }}>{route}</code> is part of the site map but is still in draft. Try the nav.
      </p>
      <button className="btn btn-primary" onClick={() => navigate("/")}>← Back to home</button>
    </main>
  );
}

function TweaksUI({ tweaks, setTweak }) {
  return (
    <TweaksPanel title="Tweaks — Doblier">
      <TweakSection label="Hero treatment">
        <TweakRadio
          label="Variant"
          value={tweaks.heroVariant}
          onChange={(v) => setTweak("heroVariant", v)}
          options={[
            { value: "v1", label: "V1" },
            { value: "v2", label: "V2" },
            { value: "v3", label: "V3" },
          ]}
        />
      </TweakSection>

      <TweakSection label="Data flow">
        <TweakRadio
          label="Metaphor"
          value={tweaks.dataFlow}
          onChange={(v) => setTweak("dataFlow", v)}
          options={[
            { value: "pipeline", label: "Pipeline" },
            { value: "perimeter", label: "Perimeter" },
            { value: "orbit", label: "Orbit" },
          ]}
        />
      </TweakSection>

      <TweakSection label="System">
        <TweakRadio
          label="Density"
          value={tweaks.density}
          onChange={(v) => setTweak("density", v)}
          options={[
            { value: "compact", label: "Compact" },
            { value: "comfortable", label: "Default" },
            { value: "spacious", label: "Spacious" },
          ]}
        />
        <TweakRadio
          label="Motion"
          value={tweaks.motion}
          onChange={(v) => setTweak("motion", v)}
          options={[
            { value: "off", label: "Off" },
            { value: "subtle", label: "Subtle" },
            { value: "confident", label: "Full" },
          ]}
        />
        <TweakColor
          label="Accent"
          value={tweaks.accent}
          onChange={(v) => setTweak("accent", v)}
          options={["#00D4AA", "#33E5C2", "#22A87E", "#5BE3C5", "#00B894"]}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
