// ============================================================
// LEADERBOARD PREVIEW + INDEPENDENCE ACCORDION
// ============================================================

function TierPill({ tier, theme }) {
  const palette = {
    Gold: { bg: "#d4a73a", fg: "#2a1f08", ring: "#e8c25b" },
    Silver: { bg: "#b6c1d0", fg: "#1f2a3a", ring: "#c4cfde" },
    Bronze: { bg: "#b8804a", fg: "#3a2614", ring: "#caa17a" },
    "None": { bg: theme.chip, fg: theme.mute, ring: theme.cardBorder },
  };
  const p = palette[tier] || palette["None"];
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 6,
        padding: "3px 10px",
        borderRadius: 999,
        background: p.bg,
        color: p.fg,
        fontSize: 11,
        fontWeight: 600,
        fontFamily: "'JetBrains Mono', monospace",
        letterSpacing: 0.4,
        border: `1px solid ${p.ring}`,
      }}
    >
      {tier !== "None" && (
        <svg width="9" height="9" viewBox="0 0 12 12">
          <circle cx="6" cy="6" r="5" fill={p.fg} opacity="0.25" />
          <circle cx="6" cy="6" r="2" fill={p.fg} />
        </svg>
      )}
      {tier === "None" ? "Pending" : tier}
    </span>
  );
}

function ScoreBar({ value, theme }) {
  // value is 0-100 or null
  if (value == null)
    return (
      <span style={{ color: theme.mute, fontFamily: "'JetBrains Mono', monospace", fontSize: 12 }}>
        n/a
      </span>
    );
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
      <div
        style={{
          width: 60,
          height: 5,
          background: theme.dark ? "rgba(255,255,255,0.08)" : "rgba(22,26,43,0.08)",
          borderRadius: 3,
          overflow: "hidden",
          flexShrink: 0,
        }}
      >
        <div
          style={{
            width: `${value}%`,
            height: "100%",
            background:
              value >= 90 ? "#d4a73a" : value >= 80 ? "#b6c1d0" : value >= 70 ? "#b8804a" : theme.mute,
            borderRadius: 3,
          }}
        />
      </div>
      <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 12.5, color: theme.ink, minWidth: 26 }}>
        {value}
      </span>
    </div>
  );
}

function LeaderboardSection({ theme }) {
  const { Section, Eyebrow } = window;
  const { isMobile } = window.useViewport();
  const [filter, setFilter] = React.useState("All");

  // Fictional codename systems — clearly mock data
  const rows = [
    { rank: 1, system: "Atlas-Helios v4.2", category: "Foundation", tier: "Gold", r: 94, a: 92, i: 91, overall: 92, eval: "to confirm" },
    { rank: 2, system: "Nimbus Pro", category: "Productivity", tier: "Gold", r: 91, a: 93, i: 89, overall: 91, eval: "to confirm" },
    { rank: 3, system: "Halo Linguist", category: "Assistive", tier: "Silver", r: 88, a: 91, i: 84, overall: 87, eval: "to confirm" },
    { rank: 4, system: "Beacon-7", category: "Foundation", tier: "Silver", r: 86, a: 82, i: 87, overall: 85, eval: "to confirm" },
    { rank: 5, system: "Mosaic Studio", category: "Productivity", tier: "Bronze", r: 79, a: 76, i: 74, overall: 76, eval: "to confirm" },
    { rank: 6, system: "Quill Reader", category: "Assistive", tier: "Bronze", r: 74, a: 78, i: 72, overall: 74, eval: "to confirm" },
    { rank: 7, system: "Glyph-3", category: "Foundation", tier: "None", r: 68, a: 64, i: 61, overall: 64, eval: "to confirm" },
    { rank: 8, system: "Helix Classroom", category: "Assistive", tier: "None", r: 62, a: 58, i: 56, overall: 59, eval: "to confirm" },
  ];

  const filtered = filter === "All" ? rows : rows.filter((r) => r.category === filter);
  const categories = ["All", "Foundation", "Productivity", "Assistive"];

  return (
    <Section id="leaderboard" theme={theme} padding="40px 0 120px" style={{ background: theme.surface }}>
      <window.Reveal>
      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1.4fr", gap: isMobile ? 24 : 80, marginBottom: isMobile ? 28 : 40, alignItems: "end" }}>
        <div>
          <Eyebrow theme={theme}>The leaderboard</Eyebrow>
          <h2
            style={{
              fontSize: "clamp(26px, 4.4vw, 56px)",
              lineHeight: 1.02,
              fontWeight: 700,
              letterSpacing: -1.3,
              margin: 0,
              color: theme.ink,
              textWrap: "balance",
            }}
          >
            One public table.
            <br />
            <span style={{ color: theme.accent, fontStyle: "italic", fontWeight: 600 }}>
              Same terms for everyone.
            </span>
          </h2>
        </div>
        <p style={{ fontSize: 17, lineHeight: 1.6, color: theme.sub, margin: 0, maxWidth: 540 }}>
          Anyone (developers, procurement teams, the neurodivergent community) can
          see how systems compare. Vendors can respond on the record. Below is a{" "}
          <strong style={{ color: theme.ink }}>preview with mock data</strong>; the live
          leaderboard launches with the first cohort.
        </p>
      </div>
      </window.Reveal>

      <window.Reveal delay={110}>
      <div
        style={{
          background: theme.dark ? "rgba(8,16,30,0.55)" : "rgba(255,255,255,0.5)",
          backdropFilter: "blur(10px)",
          border: `1px solid ${theme.cardBorder}`,
          borderRadius: 18,
          overflow: "hidden",
        }}
      >
        {/* preview banner */}
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 10,
            padding: "10px 20px",
            background: `${theme.accent}15`,
            borderBottom: `1px solid ${theme.accent}40`,
            fontSize: 12,
            color: theme.accent,
            fontFamily: "'JetBrains Mono', monospace",
            letterSpacing: 0.4,
          }}
        >
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: theme.accent, boxShadow: `0 0 8px ${theme.accent}` }} />
          PREVIEW · mock data · live launch with first cohort, Q3 2026
        </div>

        {/* filter bar */}
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            padding: "18px 20px",
            borderBottom: `1px solid ${theme.cardBorder}`,
            gap: 16,
            flexWrap: "wrap",
          }}
        >
          <div style={{ display: "flex", gap: 6 }}>
            {categories.map((c) => (
              <button
                key={c}
                onClick={() => setFilter(c)}
                style={{
                  padding: "7px 14px",
                  borderRadius: 999,
                  background: filter === c ? theme.accent : "transparent",
                  color: filter === c ? "#161a2b" : theme.sub,
                  border: `1px solid ${filter === c ? theme.accent : theme.chipBorder}`,
                  fontSize: 12.5,
                  fontWeight: 500,
                  cursor: "pointer",
                  fontFamily: "inherit",
                  transition: "all 150ms",
                }}
              >
                {c}
              </button>
            ))}
          </div>
          <div style={{ fontSize: 12, color: theme.mute, fontFamily: "'JetBrains Mono', monospace" }}>
            {filtered.length} system{filtered.length === 1 ? "" : "s"} · sorted by overall
          </div>
        </div>

        {/* table */}
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13.5 }}>
            <thead>
              <tr
                style={{
                  background: theme.dark ? "rgba(0,0,0,0.2)" : "rgba(22,26,43,0.03)",
                }}
              >
                {["#", "System", "Tier", "Reliable", "Affirming", "Inclusive", "Overall", "Last eval"].map((h, i) => (
                  <th
                    key={h}
                    style={{
                      textAlign: i === 0 ? "center" : "left",
                      padding: "12px 16px",
                      fontSize: 10.5,
                      letterSpacing: 1.4,
                      textTransform: "uppercase",
                      color: theme.mute,
                      fontWeight: 600,
                      fontFamily: "'JetBrains Mono', monospace",
                      borderBottom: `1px solid ${theme.cardBorder}`,
                      whiteSpace: "nowrap",
                    }}
                  >
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map((row, i) => (
                <tr
                  key={row.system}
                  style={{
                    borderBottom: i === filtered.length - 1 ? "none" : `1px solid ${theme.cardBorder}`,
                  }}
                >
                  <td style={{ padding: "16px", textAlign: "center", color: theme.mute, fontFamily: "'JetBrains Mono', monospace", fontSize: 12.5, width: 40 }}>
                    {row.rank}
                  </td>
                  <td style={{ padding: "16px", color: theme.ink, fontWeight: 500 }}>
                    {row.system}
                    <div style={{ fontSize: 11, color: theme.mute, marginTop: 2, fontFamily: "'JetBrains Mono', monospace" }}>
                      {row.category}
                    </div>
                  </td>
                  <td style={{ padding: "16px" }}>
                    <TierPill tier={row.tier} theme={theme} />
                  </td>
                  <td style={{ padding: "16px" }}>
                    <ScoreBar value={row.r} theme={theme} />
                  </td>
                  <td style={{ padding: "16px" }}>
                    <ScoreBar value={row.a} theme={theme} />
                  </td>
                  <td style={{ padding: "16px" }}>
                    <ScoreBar value={row.i} theme={theme} />
                  </td>
                  <td style={{ padding: "16px", color: theme.ink, fontWeight: 600, fontFamily: "'JetBrains Mono', monospace", fontSize: 14 }}>
                    {row.overall}
                  </td>
                  <td style={{ padding: "16px", color: theme.mute, fontFamily: "'JetBrains Mono', monospace", fontSize: 11.5 }}>
                    {row.eval}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* footer */}
        <div
          style={{
            padding: "14px 20px",
            borderTop: `1px solid ${theme.cardBorder}`,
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            fontSize: 12,
            color: theme.mute,
            fontFamily: "'JetBrains Mono', monospace",
            flexWrap: "wrap",
            gap: 12,
          }}
        >
          <span>System names shown are illustrative, drawn for preview purposes only.</span>
          <a href="#methodology" style={{ color: theme.accent, textDecoration: "none", fontWeight: 600 }}>
            Read the methodology →
          </a>
        </div>
      </div>
      </window.Reveal>
    </Section>
  );
}

// ============================================================
// METHODOLOGY & INDEPENDENCE — accordion
// ============================================================

function AccordionItem({ item, open, onToggle, theme }) {
  const { isMobile } = window.useViewport();
  return (
    <div style={{ borderBottom: `1px solid ${theme.cardBorder}` }}>
      <button
        onClick={onToggle}
        style={{
          width: "100%",
          padding: isMobile ? "18px 0" : "24px 0",
          background: "transparent",
          border: "none",
          color: theme.ink,
          textAlign: "left",
          cursor: "pointer",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          fontFamily: "inherit",
          fontSize: isMobile ? 16 : 19,
          fontWeight: 600,
          letterSpacing: -0.2,
        }}
      >
        <span>{item.q}</span>
        <span
          style={{
            color: theme.accent,
            fontSize: 22,
            transform: open ? "rotate(45deg)" : "rotate(0deg)",
            transition: "transform 250ms",
            lineHeight: 1,
            fontWeight: 300,
          }}
        >
          +
        </span>
      </button>
      <div
        style={{
          maxHeight: open ? 500 : 0,
          overflow: "hidden",
          transition: "max-height 300ms ease",
        }}
      >
        <div
          style={{
            paddingBottom: 26,
            fontSize: 16,
            lineHeight: 1.6,
            color: theme.sub,
            maxWidth: 760,
          }}
        >
          {item.a}
        </div>
      </div>
    </div>
  );
}

function MethodologySection({ theme }) {
  const { Section, Eyebrow, Placeholder } = window;
  const { isMobile } = window.useViewport();
  const [open, setOpen] = React.useState(0);
  const items = [
    {
      q: "How is independence kept?",
      a: (
        <>
          Philanthropic funding sits in a separate operating account from Benchmark
          scoring. The team that runs evaluations does not see funder identity for
          systems under test.
        </>
      ),
    },
    {
      q: "Who sets the criteria?",
      a: (
        <>
          The BRAINS Trust, a standing committee of neurodivergent clinicians,
          researchers, ethicists, educators, and policy professionals, owns the
          rubric. Criteria changes go through public consultation and a Trust vote.
        </>
      ),
    },
    {
      q: "How are evaluations reproduced?",
      a: (
        <>
          Every evaluation publishes the pinned system version, the exact prompts,
          the quantitative test harness, and a representative sample of Trust
          transcripts. An external lab can run the same harness against the same
          version and arrive at the same score, within a published tolerance.
        </>
      ),
    },
    {
      q: "How do vendors appeal a score?",
      a: (
        <>
          Vendors can request a re-evaluation when they ship a material change to the
          system under test. Disputes go to a Trust sub-panel that did not run the
          original evaluation; the appeal record is published whether or not the
          score moves.
        </>
      ),
    },
    {
      q: "Does BRAINS evaluate its own products on the same terms?",
      a: (
        <>
          Yes. BRAINS Incubator products and BRAINS partner products are evaluated on
          exactly the same rubric, by the same Trust panel rotation, and shown on
          the same leaderboard. Conflicts of interest are disclosed inline on the
          system's profile.
        </>
      ),
    },
  ];

  return (
    <Section id="methodology" theme={theme} padding="120px 0">
      <window.Reveal>
      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1.4fr", gap: isMobile ? 24 : 80, alignItems: "start" }}>
        <div>
          <Eyebrow theme={theme}>Methodology & independence</Eyebrow>
          <h2
            style={{
              fontSize: "clamp(26px, 4.4vw, 56px)",
              lineHeight: 1.02,
              fontWeight: 700,
              letterSpacing: -1.3,
              margin: "0 0 24px 0",
              color: theme.ink,
              textWrap: "balance",
            }}
          >
            The score only holds up if the{" "}
            <span style={{ color: theme.accent, fontStyle: "italic", fontWeight: 600 }}>
              method is open.
            </span>
          </h2>
          <p style={{ fontSize: 16, lineHeight: 1.6, color: theme.sub, margin: 0, maxWidth: 400 }}>
            Benchmark is a product of the BRAINS Incubator, and it evaluates the
            Incubator's other products, and our partners' products, on exactly the same
            terms as any other AI system.
          </p>
        </div>
        <div>
          {items.map((it, i) => (
            <AccordionItem
              key={it.q}
              item={it}
              open={open === i}
              onToggle={() => setOpen(open === i ? -1 : i)}
              theme={theme}
            />
          ))}
        </div>
      </div>
      </window.Reveal>
    </Section>
  );
}

window.LeaderboardSection = LeaderboardSection;
window.MethodologySection = MethodologySection;
