// ============================================================
// NAV — top bar with Viewing Preferences trigger
// ============================================================

function Nav({ theme, prefs, setPrefs, openReading, setOpenReading, current }) {
  const { isMobile } = window.useViewport();
  const [mobileMenuOpen, setMobileMenuOpen] = React.useState(false);
  const SHOW_FOUNDING = true;
  const links = [
    { label: "Benchmark", href: "/benchmark", key: "benchmark" },
    { label: "Incubator", href: "/incubator", key: "incubator" },
    { label: "Trust", href: "/trust", key: "trust" },
    { label: "Partners", href: "/partners", key: "partners" },
    { label: "About", href: "/about", key: "about" },
    { label: "Contact", href: "/contact", key: "contact" },
    { label: "Founding Partners", href: "/founding", key: "founding", accent: true, hidden: !SHOW_FOUNDING },
  ];
  return (
    <React.Fragment>
      <style>{`
        @media (max-width: 1100px) {
          .nav-link-about { display: none !important; }
          .nav-links { gap: 22px !important; }
        }
        @media (max-width: 960px) {
          .nav-founding-cta { display: none !important; }
        }
      `}</style>
    <nav
      style={{
        position: "fixed",
        top: 0,
        left: 0,
        right: 0,
        zIndex: 50,
        background: theme.dark
          ? "linear-gradient(to bottom, rgba(8,16,30,0.72), rgba(8,16,30,0))"
          : "linear-gradient(to bottom, rgba(246,241,226,0.7), rgba(246,241,226,0))",
        backdropFilter: "blur(12px) saturate(140%)",
        WebkitBackdropFilter: "blur(12px) saturate(140%)",
        padding: isMobile ? "14px 20px" : "18px 48px",
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        fontSize: 14,
        color: theme.ink,
      }}
    >
      <a
        href="/"
        style={{
          display: "flex",
          alignItems: "center",
          gap: isMobile ? 10 : 14,
          textDecoration: "none",
          color: "inherit",
        }}
      >
        <img
          src={theme.dark ? "../assets/brains-logo-yellow.png" : "../assets/brains-logo-full.png"}
          alt=""
          style={{ width: isMobile ? 32 : 36, height: isMobile ? 32 : 36, objectFit: "contain" }}
        />
        <div style={{ display: "flex", flexDirection: "column", lineHeight: 1.15 }}>
          <span style={{ fontWeight: 700, letterSpacing: 0.5, fontSize: isMobile ? 16 : 17 }}>
            BRAINS
          </span>
          {!isMobile && (
            <span
              style={{
                fontSize: 10,
                letterSpacing: 1.4,
                textTransform: "uppercase",
                color: theme.sub,
                fontWeight: 500,
              }}
            >
              AI that works for every mind
            </span>
          )}
        </div>
      </a>

      {!isMobile && (
        <div className="nav-links" style={{ display: "flex", alignItems: "center", gap: 28 }}>
          {links.filter((l) => !l.accent).map((l) => {
            const active = current === l.key;
            return (
              <a
                key={l.key}
                href={l.href}
                className={l.key === "about" ? "nav-link-about" : ""}
                style={{
                  color: active ? theme.ink : theme.sub,
                  textDecoration: "none",
                  fontSize: 14,
                  fontWeight: active ? 600 : 500,
                  transition: "color 200ms",
                  position: "relative",
                  paddingBottom: 4,
                  borderBottom: active ? `1.5px solid ${theme.accent}` : "1.5px solid transparent",
                  whiteSpace: "nowrap",
                }}
                onMouseEnter={(e) => (e.currentTarget.style.color = theme.ink)}
                onMouseLeave={(e) => (e.currentTarget.style.color = active ? theme.ink : theme.sub)}
              >
                {l.label}
              </a>
            );
          })}
        </div>
      )}

      <div style={{ display: "flex", alignItems: "center", gap: isMobile ? 8 : 14 }}>
        {!isMobile && SHOW_FOUNDING && (
          <a
            href="/founding"
            className="nav-founding-cta"
            style={{
              color: theme.accent,
              textDecoration: "none",
              fontSize: 14,
              fontWeight: 600,
              whiteSpace: "nowrap",
            }}
          >
            Founding Partners
          </a>
        )}
        <button
          onClick={() => setOpenReading(!openReading)}
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 8,
            padding: isMobile ? "9px 10px" : "8px 14px",
            borderRadius: 999,
            background: openReading ? theme.accent : "transparent",
            border: `1px solid ${openReading ? theme.accent : theme.chipBorder}`,
            color: openReading ? "#161a2b" : theme.ink,
            fontSize: 13,
            fontWeight: 500,
            cursor: "pointer",
            fontFamily: "inherit",
            transition: "all 200ms",
          }}
          aria-expanded={openReading}
          aria-label="Viewing Preferences"
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
            <circle cx="12" cy="12" r="5" stroke="currentColor" strokeWidth="2" />
            <path
              d="M12 2v3M12 19v3M2 12h3M19 12h3M4.5 4.5l2 2M17.5 17.5l2 2M4.5 19.5l2-2M17.5 6.5l2-2"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
            />
          </svg>
          {!isMobile && "Viewing Preferences"}
        </button>
        {isMobile && (
          <button
            onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
            style={{
              display: "inline-flex",
              alignItems: "center",
              justifyContent: "center",
              width: 40,
              height: 40,
              padding: 0,
              borderRadius: 999,
              background: mobileMenuOpen ? theme.accent : "transparent",
              border: `1px solid ${mobileMenuOpen ? theme.accent : theme.chipBorder}`,
              color: mobileMenuOpen ? "#161a2b" : theme.ink,
              cursor: "pointer",
              fontFamily: "inherit",
              transition: "all 200ms",
            }}
            aria-expanded={mobileMenuOpen}
            aria-label="Menu"
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
              {mobileMenuOpen ? (
                <path d="M6 6l12 12M6 18L18 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
              ) : (
                <path d="M4 7h16M4 12h16M4 17h16" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
              )}
            </svg>
          </button>
        )}
      </div>
    </nav>
    {isMobile && mobileMenuOpen && (
      <div
        style={{
          position: "fixed",
          top: 68,
          left: 12,
          right: 12,
          zIndex: 49,
          background: theme.surface,
          border: `1px solid ${theme.cardBorder}`,
          borderRadius: 16,
          padding: "12px 8px",
          boxShadow: theme.dark
            ? "0 30px 60px -20px rgba(0,0,0,0.6)"
            : "0 30px 60px -20px rgba(0,0,0,0.2)",
        }}
      >
        {links.filter((l) => !l.hidden).map((l) => {
          const active = current === l.key;
          return (
            <a
              key={l.key}
              href={l.href}
              onClick={() => setMobileMenuOpen(false)}
              style={{
                display: "block",
                padding: "14px 16px",
                color: l.accent ? theme.accent : (active ? theme.ink : theme.sub),
                textDecoration: "none",
                fontSize: 16,
                fontWeight: l.accent || active ? 600 : 500,
                borderRadius: 10,
                background: active ? theme.chip : "transparent",
              }}
            >
              {l.label}
            </a>
          );
        })}
      </div>
    )}
    </React.Fragment>
  );
}

// ============================================================
// READING PREFERENCES PANEL
// ============================================================

function ReadingPanel({ open, onClose, theme, prefs, setPrefs }) {
  const { isMobile } = window.useViewport();
  // Inject dyslexia-friendly font + body class management. Runs once.
  React.useEffect(() => {
    if (!document.getElementById("dyslexia-font-link")) {
      const link = document.createElement("link");
      link.id = "dyslexia-font-link";
      link.rel = "stylesheet";
      link.href = "https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible:wght@400;700&display=swap";
      document.head.appendChild(link);
    }
    if (!document.getElementById("dyslexia-style")) {
      const style = document.createElement("style");
      style.id = "dyslexia-style";
      style.textContent = `
        body.dyslexia-mode, body.dyslexia-mode * {
          font-family: 'Atkinson Hyperlegible', 'Verdana', system-ui, sans-serif !important;
          letter-spacing: 0.025em !important;
          word-spacing: 0.06em !important;
          font-style: normal !important;
        }
        body.dyslexia-mode code, body.dyslexia-mode pre {
          font-family: 'Atkinson Hyperlegible', 'Verdana', monospace !important;
        }
        /* Wider paragraph spacing — clearer block boundaries */
        body.dyslexia-mode p {
          margin-top: 0 !important;
          margin-bottom: 1.4em !important;
        }
        body.dyslexia-mode li {
          margin-bottom: 0.4em !important;
        }
        /* Hide decorative backdrops — constellation canvas, grid lattice,
           and any aria-hidden visual chrome — to cut visual noise. */
        body.dyslexia-mode canvas {
          display: none !important;
        }
        body.dyslexia-mode [aria-hidden="true"] {
          display: none !important;
        }
      `;
      document.head.appendChild(style);
    }
    // Line-spacing overrides target prose elements only (p, li). Inline
    // line-height on those elements wins over body's value, so we use !important.
    // Headings are excluded so their tight tracking stays intact.
    if (!document.getElementById("line-spacing-style")) {
      const style = document.createElement("style");
      style.id = "line-spacing-style";
      style.textContent = `
        body.spacing-tight p,
        body.spacing-tight li,
        body.spacing-tight dd {
          line-height: 1.42 !important;
        }
        body.spacing-roomy p,
        body.spacing-roomy li,
        body.spacing-roomy dd {
          line-height: 1.9 !important;
        }
      `;
      document.head.appendChild(style);
    }
  }, []);

  React.useEffect(() => {
    document.body.classList.toggle("dyslexia-mode", !!prefs.dyslexia);
  }, [prefs.dyslexia]);

  // Apply text-size as a global zoom on <html>. Inline px font-sizes don't
  // inherit from body, so this is the only thing that actually moves the dial.
  React.useEffect(() => {
    const scale = window.TEXT_SCALES[prefs.textSize] || window.TEXT_SCALES.M;
    document.documentElement.style.zoom = scale.zoom;
  }, [prefs.textSize]);

  // Apply line-spacing class on body. Dyslexia mode forces Roomy regardless of
  // the user's saved Line spacing pick.
  React.useEffect(() => {
    const cls = ["spacing-tight", "spacing-standard", "spacing-roomy"];
    document.body.classList.remove(...cls);
    const effective = prefs.dyslexia ? "Roomy" : (prefs.lineSpacing || "Standard");
    document.body.classList.add("spacing-" + effective.toLowerCase());
  }, [prefs.lineSpacing, prefs.dyslexia]);

  if (!open) return null;
  const row = {
    display: "flex",
    flexDirection: "column",
    gap: 8,
    paddingBottom: 18,
    borderBottom: `1px solid ${theme.cardBorder}`,
    marginBottom: 18,
  };
  const seg = (active) => ({
    flex: 1,
    padding: "10px 8px",
    background: active ? theme.accent : "transparent",
    color: active ? "#161a2b" : theme.ink,
    border: `1px solid ${active ? theme.accent : theme.chipBorder}`,
    borderRadius: 8,
    fontSize: 13,
    fontWeight: 500,
    cursor: "pointer",
    fontFamily: "inherit",
    transition: "all 150ms",
  });
  return (
    <div
      style={{
        position: "fixed",
        top: isMobile ? 68 : 84,
        right: isMobile ? 12 : 48,
        left: isMobile ? 12 : "auto",
        width: isMobile ? "auto" : 340,
        maxHeight: isMobile ? "calc(100vh - 80px)" : "auto",
        overflowY: isMobile ? "auto" : "visible",
        zIndex: 49,
        background: theme.surface,
        border: `1px solid ${theme.cardBorder}`,
        borderRadius: 16,
        padding: isMobile ? "20px 20px 16px" : "24px 24px 20px",
        color: theme.ink,
        boxShadow: theme.dark
          ? "0 30px 60px -20px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.04)"
          : "0 30px 60px -20px rgba(0,0,0,0.2)",
      }}
    >
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          marginBottom: 4,
        }}
      >
        <strong style={{ fontSize: 15 }}>Viewing Preferences</strong>
        <button
          onClick={onClose}
          aria-label="Close"
          style={{
            background: "transparent",
            border: "none",
            color: theme.sub,
            cursor: "pointer",
            fontSize: 18,
            lineHeight: 1,
          }}
        >
          ×
        </button>
      </div>
      <p style={{ fontSize: 12.5, color: theme.sub, margin: "0 0 22px 0", lineHeight: 1.5 }}>
        These settings stay with you while you browse. We don't track them.
      </p>

      <div style={row}>
        <label style={{ fontSize: 12.5, color: theme.sub, letterSpacing: 0.2 }}>
          Theme
        </label>
        <div style={{ display: "flex", gap: 8 }}>
          <button style={seg(prefs.theme === "midnight")} onClick={() => setPrefs({ ...prefs, theme: "midnight" })}>
            Midnight
          </button>
          <button style={seg(prefs.theme === "light")} onClick={() => setPrefs({ ...prefs, theme: "light" })}>
            Bone
          </button>
        </div>
      </div>

      <div style={row}>
        <label style={{ fontSize: 12.5, color: theme.sub, letterSpacing: 0.2 }}>
          Text size
        </label>
        <div style={{ display: "flex", gap: 8 }}>
          {["S", "M", "L"].map((s) => (
            <button key={s} style={seg(prefs.textSize === s)} onClick={() => setPrefs({ ...prefs, textSize: s })}>
              {s}
            </button>
          ))}
        </div>
      </div>

      <div style={row}>
        <label style={{ fontSize: 12.5, color: theme.sub, letterSpacing: 0.2 }}>
          Line spacing
        </label>
        <div style={{ display: "flex", gap: 8 }}>
          {["Tight", "Standard", "Roomy"].map((s) => (
            <button key={s} style={seg(prefs.lineSpacing === s)} onClick={() => setPrefs({ ...prefs, lineSpacing: s })}>
              {s}
            </button>
          ))}
        </div>
      </div>

      <div style={{ ...row, borderBottom: "none", marginBottom: 4, paddingBottom: 0 }}>
        <label style={{ fontSize: 12.5, color: theme.sub, letterSpacing: 0.2, display: "flex", alignItems: "center", gap: 8 }}>
          Dyslexia-friendly mode
        </label>
        <div style={{ display: "flex", gap: 8 }}>
          <button style={seg(!!prefs.dyslexia)} onClick={() => setPrefs({ ...prefs, dyslexia: true })}>
            On
          </button>
          <button style={seg(!prefs.dyslexia)} onClick={() => setPrefs({ ...prefs, dyslexia: false })}>
            Off
          </button>
        </div>
        <p style={{ fontSize: 11.5, color: theme.mute, margin: "8px 0 0", lineHeight: 1.5 }}>
          Switches to the Atkinson Hyperlegible typeface, adds letter and word spacing,
          forces roomy line height, and turns off all animation.
        </p>
      </div>
    </div>
  );
}

window.Nav = Nav;
window.ReadingPanel = ReadingPanel;
