// Alpha Z · App entry — hash router, Tweaks, splash

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "s2Emphasis": true,
  "s3RightCol": "axis"
}/*EDITMODE-END*/;

function parseRoute() {
  const h = (location.hash || "#/").replace(/^#/, "");
  // "/" | "/careers" | "/careers/<slug>" | "/applications/<slug>" | "/#approach"
  if (h.startsWith("/applications/")) {
    return { name: "application", slug: h.split("/")[2] };
  }
  if (h.startsWith("/careers/")) {
    return { name: "career", slug: h.split("/")[2] };
  }
  if (h.startsWith("/careers")) return { name: "careers" };
  return { name: "home" };
}

/* B3 · Per-route SEO meta. Updates <title> + <meta description> on
   route change so search engines and shares see the right context. */
function updateMeta(route) {
  let title = "Alpha Z — AI for decision-making";
  let desc  = "Alpha Z is an AI research lab building the decision layer for complex problems — formulate, solve, explain, compound. Verifiable plans, grounded judgment.";

  if (route.name === "careers") {
    title = "Careers — Alpha Z";
    desc  = "Alpha Z is hiring builders, researchers, and product engineers. We're early, small, and writing the rules for how AI supports real-world decisions.";
  } else if (route.name === "career") {
    const roles = window.ROLES || [];
    const role = roles.find(r => r.slug === route.slug);
    // Archived roles render as 404 — meta should match.
    if (role && !role.archived) {
      title = `${role.title} (${role.type}) — Alpha Z`;
      desc  = `Open role at Alpha Z. ${role.short}`;
    } else {
      title = "Not found — Alpha Z";
      desc  = "This role doesn't exist (yet).";
    }
  } else if (route.name === "application") {
    const apps = window.APPLICATIONS || [];
    const app = apps.find(a => a.slug === route.slug);
    if (app) {
      title = `${app.title} — Alpha Z`;
      desc  = `${app.short} How Alpha Z frames, searches, and explains plans for this domain.`;
    } else {
      title = "Not found — Alpha Z";
      desc  = "This application scenario doesn't exist (yet).";
    }
  }

  document.title = title;
  const metaDesc = document.querySelector('meta[name="description"]');
  if (metaDesc) metaDesc.setAttribute("content", desc);
  const ogTitle = document.querySelector('meta[property="og:title"]');
  if (ogTitle) ogTitle.setAttribute("content", title);
  const ogDesc  = document.querySelector('meta[property="og:description"]');
  if (ogDesc) ogDesc.setAttribute("content", desc);
  const twTitle = document.querySelector('meta[name="twitter:title"]');
  if (twTitle) twTitle.setAttribute("content", title);
  const twDesc  = document.querySelector('meta[name="twitter:description"]');
  if (twDesc) twDesc.setAttribute("content", desc);
}

function useRoute() {
  const [route, setRoute] = React.useState(parseRoute());
  React.useEffect(() => {
    // Initial meta sync (in case the page is loaded directly to /careers etc.)
    updateMeta(parseRoute());

    const prefersReduced =
      window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const scrollBehavior = prefersReduced ? "auto" : "smooth";

    const onHash = () => {
      const newRoute = parseRoute();
      setRoute(newRoute);
      updateMeta(newRoute);
      // anchor scroll for hash like #/#approach
      const h = location.hash.replace(/^#/, "");
      const anchor = h.includes("#") ? h.split("#").pop() : null;
      if (anchor) {
        requestAnimationFrame(() => {
          const el = document.getElementById(anchor);
          if (el) {
            const y = el.getBoundingClientRect().top + window.scrollY - 112;
            window.scrollTo({ top: y, behavior: scrollBehavior });
          }
        });
      } else {
        window.scrollTo({ top: 0, behavior: scrollBehavior });
      }
    };
    window.addEventListener("hashchange", onHash);
    // handle initial anchor
    const h = location.hash.replace(/^#/, "");
    if (h.includes("#")) {
      const anchor = h.split("#").pop();
      setTimeout(() => {
        const el = document.getElementById(anchor);
        if (el) {
          const y = el.getBoundingClientRect().top + window.scrollY - 112;
          window.scrollTo({ top: y, behavior: scrollBehavior });
        }
      }, 50);
    }
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  return route;
}

function useTweaksPanel(defaults) {
  // local — re-use the starter useTweaks hook for persistence
  return window.useTweaks ? window.useTweaks(defaults) : [defaults, () => {}];
}

function App() {
  const route = useRoute();
  const [tweaks, setTweak] = useTweaksPanel(TWEAK_DEFAULTS);

  // Splash kept as a fallback only — shown if the bundle stalls or fails to mount.
  // Default state hides it on a normal load (React mounts → splashGone stays true).
  // To force-show during slow loads, swap initial value to `false` and pair with a
  // mount-completion signal (e.g. setSplashGone(true) at the end of first effect).
  const [splashGone] = React.useState(true);

  React.useEffect(() => {
    // scroll to top on route change unless it's a hash-anchor home jump
    const h = location.hash.replace(/^#/, "");
    if (!h.includes("#") || h === "/") {
      const prefersReduced =
        window.matchMedia('(prefers-reduced-motion: reduce)').matches;
      window.scrollTo({ top: 0, behavior: prefersReduced ? "auto" : "smooth" });
    }
  }, [route.name, route.slug]);

  return (
    <>
      <Splash gone={splashGone} />
      <Nav route={route.name} />
      <ScrollProgress />
      <main>
        {route.name === "home" && <HomePage tweaks={tweaks} />}
        {route.name === "careers" && <CareersPage />}
        {route.name === "career" && <CareerDetailPage slug={route.slug} />}
        {route.name === "application" && <ApplicationDetailPage slug={route.slug} />}
      </main>
      <Footer />
      <TweaksPanel title="Tweaks">
        <TweakSection label="§H · §2 emphasis">
          <TweakToggle
            label="Bold subjects"
            value={tweaks.s2Emphasis}
            onChange={v => setTweak("s2Emphasis", v)}
          />
        </TweakSection>

        <TweakSection label="§H · §3 right column">
          <TweakSelect
            label="Treatment"
            value={tweaks.s3RightCol}
            options={[
              { label: "Sparse (empty)",   value: "sparse" },
              { label: "Mono pull-quote",  value: "pullquote" },
              { label: "Axis line + ticks", value: "axis" },
            ]}
            onChange={v => setTweak("s3RightCol", v)}
          />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
