/* Shared chrome: nav, footer, and small pieces every page uses */

function Logo({ size = 28 }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
      <svg width={size} height={size} viewBox="0 0 28 28" aria-hidden="true">
        <rect x="1" y="1" width="26" height="26" rx="7"
              fill="var(--brand-600)" />
        {/* benchtop bracket */}
        <path d="M7 18 L7 10 L21 10 L21 18" stroke="white" strokeWidth="1.8" fill="none" strokeLinecap="round" />
        <line x1="7" y1="18" x2="21" y2="18" stroke="white" strokeWidth="1.8" strokeLinecap="round" />
        <circle cx="11" cy="14" r="1.4" fill="white" />
        <circle cx="14" cy="14" r="1.4" fill="white" />
        <circle cx="17" cy="14" r="1.4" fill="white" />
      </svg>
      <div style={{ display: "flex", alignItems: "baseline", gap: 0, fontSize: 16, fontWeight: 600, letterSpacing: "-0.01em", color: "var(--ink-900)" }}>
        <span>Conduct</span>
        <span style={{ color: "var(--brand-700)" }}>Biology</span>
      </div>
    </div>
  );
}

const NAV_ITEMS = [
  { label: "Molecular", href: "/molecular", key: "molecular" },
  { label: "Population genetics", href: "/population", key: "population" },
  { label: "Study record", href: "/study", key: "study" },
  { label: "Pricing", href: "/#pricing", key: "pricing" },
];
const PILOT_HREF = "/signup?module=molecular";

// Sign-in with a ConductScience account. The session comes from /api/auth/session once
// per page; { enabled: false } (or no API, as on a plain static server) hides sign-in.
let accountRequest = null;
function loadAccount() {
  if (!accountRequest) {
    accountRequest = fetch("/api/auth/session", { credentials: "same-origin", cache: "no-store" })
      .then((r) => (r.ok ? r.json() : { enabled: false, user: null }))
      .catch(() => ({ enabled: false, user: null }));
  }
  return accountRequest;
}

function useAccount() {
  const [account, setAccount] = React.useState(null);
  React.useEffect(() => {
    let live = true;
    loadAccount().then((a) => { if (live) setAccount(a); });
    return () => { live = false; };
  }, []);
  return account;
}

function signInHref() {
  const here = `${window.location.pathname}${window.location.search}`;
  return `/api/auth/conductscience/start?next=${encodeURIComponent(here)}`;
}

async function signOut() {
  try { await fetch("/api/auth/logout", { method: "POST", credentials: "same-origin" }); } catch {}
  window.location.reload();
}

function accountInitials(user) {
  const parts = String(user.name || user.email || "?").trim().split(/\s+/);
  return ((parts[0] || "?")[0] + (parts.length > 1 ? parts[parts.length - 1][0] : "")).toUpperCase();
}

function NavAccount({ account }) {
  if (!account || !account.enabled) return null;
  if (!account.user) return <a href={signInHref()} className="nav-link">Sign in</a>;
  const user = account.user;
  return (
    <details className="nav-account">
      <summary aria-label={`Account: ${user.name}`}>
        <span className="nav-avatar" aria-hidden="true">{accountInitials(user)}</span>
        <span className="nav-account-name">{user.givenName || user.name}</span>
      </summary>
      <div className="nav-account-panel">
        <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink-900)" }}>{user.name}</div>
        <div style={{ fontSize: 12.5, color: "var(--ink-500)", overflowWrap: "anywhere" }}>{user.email}</div>
        <div style={{ fontSize: 12, color: "var(--ink-500)", marginTop: 6 }}>ConductScience account</div>
        {account.saving ? <a href="/saved" className="btn btn-primary btn-tap" style={{ marginTop: 10 }}>Saved work</a> : null}
        <a href="https://conductscience.com/my-account/" className="btn btn-ghost btn-tap" style={{ marginTop: account.saving ? 0 : 10 }}>Manage account</a>
        <button type="button" className="btn btn-ghost btn-tap" onClick={signOut}>Sign out</button>
      </div>
    </details>
  );
}

// The nav button invites visitors into the beta. Signed-in beta users get the tool for
// the page they are on, or the tool list.
function navAction(current, account) {
  if (account && account.user) {
    if (current === "molecular") return { label: "Open the tool", href: "/molecular/app" };
    if (current === "population") return { label: "Open the tool", href: "/population/app" };
    if (current === "study") return { label: "Open the tool", href: "/study/app" };
    if (current === "saved") return { label: "Open the tools", href: "/#modules" };
    return { label: "Open the tools", href: "/#modules" };
  }
  if (current === "signup") return { label: "See the tools", href: "/#modules" };
  return { label: "Join the beta", href: "/signup" };
}

function Nav({ current }) {
  // /adjudicate is unlisted for now (2026-08-13). The page still works at its URL;
  // add an item here to put it back in the nav.
  const menuRef = React.useRef(null);
  const closeMenu = () => { if (menuRef.current) menuRef.current.open = false; };
  const account = useAccount();
  const action = navAction(current, account);
  return (
    <nav style={{
      position: "sticky", top: 0, zIndex: 50,
      background: "rgba(255,255,255,.85)",
      backdropFilter: "saturate(180%) blur(8px)",
      WebkitBackdropFilter: "saturate(180%) blur(8px)",
      borderBottom: "1px solid var(--ink-200)",
    }}>
      <div className="nav-inner">
        <a href="/" aria-label="ConductBiology home" style={{ display: "flex" }}><Logo /></a>
        <div className="nav-links">
          {NAV_ITEMS.map(i => (
            <a key={i.key} href={i.href} className="nav-link"
               aria-current={current === i.key ? "page" : undefined}>{i.label}</a>
          ))}
          <NavAccount account={account} />
          <a href={action.href} className="btn btn-primary btn-sm">{action.label}</a>
        </div>
        <details className="nav-menu" ref={menuRef}>
          <summary>
            Menu
            <svg width="12" height="12" viewBox="0 0 12 12" aria-hidden="true">
              <path d="M2 4.5l4 3 4-3" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </summary>
          <div className="nav-menu-panel">
            {NAV_ITEMS.map(i => (
              <a key={i.key} href={i.href} onClick={closeMenu}
                 aria-current={current === i.key ? "page" : undefined}>{i.label}</a>
            ))}
            {account && account.enabled && !account.user ? <a href={signInHref()} onClick={closeMenu}>Sign in</a> : null}
            {account && account.user ? (
              <>
                <div className="nav-menu-account">Signed in as {account.user.name}<span>{account.user.email}</span></div>
                {account.saving ? <a href="/saved" onClick={closeMenu}>Saved work</a> : null}
                <button type="button" className="nav-menu-signout" onClick={signOut}>Sign out</button>
              </>
            ) : null}
            <a href={action.href} className="btn btn-primary" onClick={closeMenu}>{action.label}</a>
          </div>
        </details>
      </div>
    </nav>
  );
}

function Footer() {
  const groups = [
    {
      title: "Modules",
      links: [
        ["Molecular", "/molecular"],
        ["Population genetics", "/population"],
        ["Study record", "/study"],
      ],
    },
    {
      title: "Get started",
      links: [
        ["Join the beta", "/signup"],
        ["Molecular tool", "/molecular/app"],
        ["Population genetics tool", "/population/app"],
        ["Study record tool", "/study/app"],
        ["Request a study", PILOT_HREF],
        ["Pricing", "/#pricing"],
      ],
    },
    {
      title: "ConductScience",
      links: [
        ["ConductScience", "https://conductscience.com/"],
        ["Free lab tools", "https://conductscience.com/tools"],
        ["ConductVision", "https://conductscience.com/conductvision"],
        ["ConductSignal", "https://conductsignal.com/"],
        ["ConductCognition", "https://conductcognition.com/"],
        ["ConductColony", "https://conductcolony.com/"],
        ["ConductSpeech", "https://conductspeech.com/"],
      ],
    },
  ];

  return (
    <footer style={{ background: "var(--ink-50)", borderTop: "1px solid var(--ink-200)", marginTop: 80 }}>
      <div className="page-wrap" style={{ paddingTop: 56, paddingBottom: 36 }}>
        <div className="footer-grid">
          <div>
            <Logo />
            <p style={{ marginTop: 14, color: "var(--ink-600)", fontSize: 13.5, lineHeight: 1.6, maxWidth: 320 }}>
              Bench-biology tools that turn your lab's files into decisions you can check and rerun.
            </p>
          </div>
          {groups.map(g => (
            <div key={g.title}>
              <div style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: ".08em", textTransform: "uppercase", color: "var(--ink-500)" }}>
                {g.title}
              </div>
              <ul className="footer-links" style={{ listStyle: "none", margin: "14px 0 0", padding: 0, display: "grid", gap: 9 }}>
                {g.links.map(([label, href]) => (
                  <li key={label}>
                    <a href={href} style={{ fontSize: 13.5, color: "var(--ink-700)" }}>{label}</a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div className="footer-base" style={{
          marginTop: 48, paddingTop: 20, borderTop: "1px solid var(--ink-200)",
          display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap",
          fontSize: 12.5, color: "var(--ink-500)",
        }}>
          <div>© 2026 ConductScience · ConductBiology is part of the ConductScience research platform.</div>
          <div className="mono" style={{ fontSize: 11, letterSpacing: ".04em" }}>
            For research use only · no patient data
          </div>
        </div>
      </div>
    </footer>
  );
}

function SectionTitle({ eyebrow, title, sub, id }) {
  return (
    <div style={{ maxWidth: 740 }}>
      <div className="mono" style={{ fontSize: 11.5, color: "var(--brand-700)", letterSpacing: ".12em", textTransform: "uppercase", fontWeight: 600 }}>
        {eyebrow}
      </div>
      <h2 id={id} style={{ margin: "10px 0 0", fontSize: "clamp(26px, 3.4vw, 34px)", fontWeight: 700, letterSpacing: "-0.02em", color: "var(--ink-900)", lineHeight: 1.15, textWrap: "balance" }}>
        {title}
      </h2>
      {sub && <p style={{ margin: "12px 0 0", fontSize: 16, color: "var(--ink-600)", lineHeight: 1.6 }}>{sub}</p>}
    </div>
  );
}

function ArrowRight() { return <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M5 12h14M13 5l7 7-7 7"/></svg>; }
function CheckIcon(p={}) { return <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" {...p}><path d="M20 6L9 17l-5-5"/></svg>; }

Object.assign(window, { Logo, Nav, Footer, SectionTitle, ArrowRight, CheckIcon, PILOT_HREF, useAccount, loadAccount, signInHref, signOut });
