/* App · router + Tweaks + handoff overlay.
   The mockup is an SPA with hash routing so it can render any of the
   sub-pages cleanly without separate HTML files. */

const { useEffect, useRef } = React;

// ============================================================================
// Tweak defaults — wrapped in EDITMODE markers so the host can rewrite them.
// ============================================================================

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroVariant": "C",
  "showAudienceStrip": true,
  "socotraLive": false,
  "ctaTarget": "request-quote"
}/*EDITMODE-END*/;

// ============================================================================
// Router — a tiny hash router
// ============================================================================

const ROUTES = [
  "/", "/approach", "/partners", "/investors",
  "/press", "/about", "/team",
  "/careers", "/contact", "/faq", "/legal", "/quote",
];

const ROUTE_TITLES = {
  "/":          "Solas · Predict and prevent",
  "/approach":  "Approach · Solas",
  "/partners":  "Partners · Solas",
  "/investors": "Investors · Solas",
  "/press":     "Press &amp; journal · Solas",
  "/about":     "About · Solas",
  "/team":      "Team · Solas",
  "/careers":   "Careers · Solas",
  "/contact":   "Contact · Solas",
  "/faq":       "FAQ · Solas",
  "/legal":     "Legal · Solas",
  "/quote":     "Request a quote · Solas",
};

const useHashRouter = () => {
  const [route, setRoute] = React.useState(() => {
    const h = window.location.hash.replace(/^#/, "");
    return h && ROUTES.includes(h.split("#")[0]) ? h.split("#")[0] : "/";
  });
  const historyRef = useRef([route]);

  useEffect(() => {
    const onHash = () => {
      const h = window.location.hash.replace(/^#/, "");
      const r = h && ROUTES.includes(h.split("#")[0]) ? h.split("#")[0] : "/";
      setRoute(r);
      if (historyRef.current[historyRef.current.length - 1] !== r) {
        historyRef.current.push(r);
      }
      window.scrollTo({ top: 0, left: 0 });
      document.title = ROUTE_TITLES[r] || "Solas";
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const onNav = (path) => {
    window.location.hash = path;
  };

  return { route, onNav, history: historyRef.current };
};

// ============================================================================
// Handoff overlay — shows the Claude Code package layout
// ============================================================================

const HANDOFF_FILES = [
  { n: "CLAUDE.md",            d: "Build instructions for Claude Code" },
  { n: "README.md",            d: "Project overview &amp; quickstart" },
  { n: "routes.md",            d: "Routing map · URL structure · seams" },
  { n: "components.md",        d: "Component inventory with props" },
  { n: "content.schema.ts",    d: "MDX content schema · TS types" },
  { n: "voice.md",             d: "Brand voice &amp; copy rules" },
  { n: "cursor-copy-guide.md", d: "Editing copy in Cursor without breaking layout" },
  { n: "acceptance.md",        d: "Acceptance criteria, per page" },
  { n: "integrations.md",      d: "Hubspot, Socotra PAS, connected-home API seams" },
  { n: "tokens.css",            d: "Design tokens (copied from design system)" },
  { n: "package.json",         d: "Next.js + TypeScript + MDX stack" },
];

const HandoffOverlay = ({ open, onClose }) => (
  <aside
    className={"handoff-overlay" + (open ? " is-open" : "")}
    aria-hidden={!open}
    data-screen-label="Handoff overlay"
  >
    <button className="handoff-overlay__close" onClick={onClose} aria-label="Close">Close ×</button>
    <span className="handoff-overlay__lbl">§ Claude Code handoff</span>
    <h2 className="handoff-overlay__t">The package ready to send.</h2>
    <div className="handoff-overlay__rule" />
    <p style={{ fontSize: 14, lineHeight: 1.6, margin: 0, maxWidth: "42ch", color: "var(--fg)" }}>
      Eleven files in <code style={{ fontFamily: "ui-monospace, monospace", fontSize: 12 }}>/claude-code/</code>.
      Each is a single-purpose document Claude Code can read top-to-bottom.
      The mock you're looking at is the visual contract.
    </p>
    <div className="handoff-overlay__files">
      {HANDOFF_FILES.map((f, i) => (
        <div key={i} className="handoff-overlay__file">
          <span className="handoff-overlay__file__n">{f.n}</span>
          <span className="handoff-overlay__file__d" dangerouslySetInnerHTML={{ __html: f.d }} />
        </div>
      ))}
    </div>
    <p style={{ fontSize: 13, lineHeight: 1.6, margin: 0, color: "var(--fg-muted)", maxWidth: "44ch" }}>
      The package opens as a folder you can drop into a fresh repo and read in
      order. <code>CLAUDE.md</code> is the front door — it tells the agent
      what to build, in what sequence, against which constraints.
    </p>
    <a
      href="claude-code/CLAUDE.md"
      className="handoff-overlay__cta"
      target="_blank"
      rel="noreferrer"
    >Open CLAUDE.md →</a>
  </aside>
);

// ============================================================================
// TweaksPanel — variations + handoff trigger
// ============================================================================

const SolasTweaks = ({ tweaks, setTweak, onOpenHandoff }) => (
  <TweaksPanel title="Tweaks">
    <TweakSection label="Homepage hero">
      <TweakRadio
        label="Hero variant"
        value={tweaks.heroVariant}
        options={[
          { value: "A", label: "A · Quote" },
          { value: "B", label: "B · Full" },
          { value: "C", label: "C · Spot" },
        ]}
        onChange={(v) => setTweak("heroVariant", v)}
      />
      <p style={{ fontSize: 11, lineHeight: 1.5, color: "var(--fg-muted)", margin: "0 0 4px" }}>
        A · Founder pull-quote · B · Wedge sentence at scale · C · Underwriter spotlight
      </p>
    </TweakSection>

    <TweakSection label="Site chrome">
      <TweakToggle
        label="Audience strip on home"
        value={tweaks.showAudienceStrip}
        onChange={(v) => setTweak("showAudienceStrip", v)}
      />
      <TweakSelect
        label="Top-nav CTA"
        value={tweaks.ctaTarget}
        options={[
          { value: "investor-brief", label: "Investor brief (B2B-first)" },
          { value: "request-quote",  label: "Request a quote (consumer-led)" },
          { value: "partner-memo",   label: "Partner memo (broker-led)" },
        ]}
        onChange={(v) => setTweak("ctaTarget", v)}
      />
    </TweakSection>

    <TweakSection label="/quote · Socotra switch">
      <TweakToggle
        label="Socotra is live"
        value={tweaks.socotraLive}
        onChange={(v) => setTweak("socotraLive", v)}
      />
      <p style={{ fontSize: 11, lineHeight: 1.5, color: "var(--fg-muted)", margin: "0 0 4px" }}>
        Off: waitlist form (Hubspot). On: full Socotra quote intake.
      </p>
    </TweakSection>

    <TweakSection label="Claude Code handoff">
      <TweakButton label="Open handoff package →" onClick={onOpenHandoff} />
    </TweakSection>
  </TweaksPanel>
);

// ============================================================================
// CTA mapping for the top nav based on tweaks
// ============================================================================

const CTA_MAP = {
  "investor-brief": { target: "/investors", label: "Investor brief" },
  "request-quote":  { target: "/quote",     label: "Join the waitlist" },
  "partner-memo":   { target: "/partners",  label: "Partner memo" },
};

// ============================================================================
// App
// ============================================================================

const App = () => {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const { route, onNav, history } = useHashRouter();
  const [handoffOpen, setHandoffOpen] = React.useState(false);

  const cta = CTA_MAP[tweaks.ctaTarget] || CTA_MAP["investor-brief"];

  // Map route → active nav id
  const navActive = ({
    "/approach":  "approach",
    "/partners":  "partners",
    "/investors": "investors",
    "/press":     "press",
    "/about":     "about",
    "/team":      "about",   // Team lives under "About" in the nav grouping
    "/careers":   "about",
    "/contact":   "about",
    "/faq":       "about",
    "/legal":     null,
    "/quote":     null,
  })[route] || null;

  // Audience strip is only on homepage
  // (declared in renderPage's tweak pass-through)

  const renderPage = () => {
    switch (route) {
      case "/":          return <HomePage onNav={onNav} heroVariant={tweaks.heroVariant} audience="investors" showAudienceStrip={tweaks.showAudienceStrip} />;
      case "/approach":  return <ApproachPage onNav={onNav} />;
      case "/partners":  return <PartnersPage onNav={onNav} />;
      case "/investors": return <InvestorsPage onNav={onNav} />;
      case "/press":     return <PressPage onNav={onNav} />;
      case "/about":     return <AboutPage onNav={onNav} />;
      case "/team":      return <TeamPage onNav={onNav} />;
      case "/careers":   return <CareersPage onNav={onNav} />;
      case "/contact":   return <ContactPage onNav={onNav} />;
      case "/faq":       return <FaqPage onNav={onNav} />;
      case "/legal":     return <LegalPage onNav={onNav} />;
      case "/quote":     return <QuotePage onNav={onNav} socotraLive={tweaks.socotraLive} />;
      default:           return <HomePage onNav={onNav} heroVariant={tweaks.heroVariant} audience="investors" showAudienceStrip={tweaks.showAudienceStrip} />;
    }
  };

  return (
    <React.Fragment>
      {/* BrowserChrome SPA URL-bar mock removed per CTO Domain 2 remediation —
          it read as broken pre-launch chrome on a real preview link and
          hard-coded the wrong domain. The mockup now presents as the real
          site would, framed by the actual browser. */}
      <Nav
        active={navActive}
        onNav={onNav}
        ctaTarget={cta.target}
        ctaLabel={cta.label}
      />
      <main>
        {renderPage()}
      </main>
      <Footer onNav={onNav} />

      <SolasTweaks
        tweaks={tweaks}
        setTweak={setTweak}
        onOpenHandoff={() => setHandoffOpen(true)}
      />
      <HandoffOverlay open={handoffOpen} onClose={() => setHandoffOpen(false)} />
    </React.Fragment>
  );
};

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