/* hero-intro.jsx
 * The landing-page hero. Shows only when mode === "idle". Contains a big
 * pitch + the minimal config form. When user dispatches, the hero fades out
 * and the dashboard doors open to reveal gauges + trace log.
 */

function HeroIntro({ form, setForm, onStart, canStart, fading }) {
  return (
    <div className={`hero-intro${fading ? " fading" : ""}`}>
      <div className="hero-stack">
        <div className="hero-eyebrow">
          <span className="bug">b</span>
          byokicu · relay trust telemetry
        </div>
        <h1 className="hero-headline">
          Strap your relay<br/>
          to the <span className="phos">test bench.</span>
        </h1>
        <p className="hero-lede">
          We dispatch the canonical 7-case eval target against your BYOK relay
          and against a server baseline at the same time, then slam the two
          results together so the deviations declare themselves.
        </p>
        <form
          className="hero-form"
          onSubmit={(e) => { e.preventDefault(); if (canStart) onStart(); }}
        >
          <div className="hero-row">
            <label htmlFor="h-endpoint">API endpoint</label>
            <input
              id="h-endpoint"
              autoComplete="off"
              placeholder="https://my-relay.example.com/v1"
              value={form.endpoint}
              onChange={(e) => setForm({ ...form, endpoint: e.target.value })}
            />
          </div>
          <div className="hero-row two">
            <div>
              <label htmlFor="h-protocol">Protocol</label>
              <select
                id="h-protocol"
                value={form.protocol}
                onChange={(e) => setForm({ ...form, protocol: e.target.value })}
              >
                <option value="openai">OpenAI-compatible</option>
                <option value="anthropic">Anthropic-compatible</option>
              </select>
            </div>
            <div>
              <label htmlFor="h-provider">Provider ID</label>
              <input
                id="h-provider"
                autoComplete="off"
                placeholder="openai"
                value={form.provider}
                onChange={(e) => setForm({ ...form, provider: e.target.value })}
              />
            </div>
          </div>
          <div className="hero-row two">
            <div>
              <label htmlFor="h-model">Model</label>
              <input
                id="h-model"
                autoComplete="off"
                placeholder="gpt-4.1"
                value={form.model}
                onChange={(e) => setForm({ ...form, model: e.target.value })}
              />
            </div>
            <div>
              <label htmlFor="h-apikey">API key</label>
              <input
                id="h-apikey"
                type="password"
                autoComplete="off"
                placeholder="sk-…"
                value={form.apiKey}
                onChange={(e) => setForm({ ...form, apiKey: e.target.value })}
              />
            </div>
          </div>
          <button className="hero-start" type="submit" disabled={!canStart}>
            <span>Dispatch run</span>
            <span className="arrow">▶▶</span>
          </button>
          <p className="hero-fine">
            7 canonical cases · runs against your relay <b>and</b> the server baseline
            in parallel · key cleared after dispatch · scrubbed from logs.
          </p>
        </form>
      </div>
    </div>
  );
}

/* Card 21: home-page Leader Board — Top 20 relay models by trust score. Data
 * comes from the bridge (same-origin, proxied to console). Until console exposes
 * the endpoint this is empty (no fake data) — see card completion report. */
function LeaderBoard() {
  const [entries, setEntries] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    let alive = true;
    const bridge = window.byokicuBridge;
    if (!bridge || !bridge.loadLeaderboard) { setLoading(false); return undefined; }
    bridge.loadLeaderboard().then(
      (rows) => { if (alive) { setEntries(Array.isArray(rows) ? rows : []); setLoading(false); } },
      () => { if (alive) { setEntries([]); setLoading(false); } }
    );
    return () => { alive = false; };
  }, []);

  const fmtDate = (iso) => {
    const m = String(iso || "").match(/^(\d{4})-(\d{2})-(\d{2})/);
    return m ? `${m[1]}-${m[2]}-${m[3]}` : "—";
  };
  const fmtMs = (v) => (typeof v === "number" && isFinite(v) ? `${Math.round(v)}ms` : "—");
  const fmtPass = (e) =>
    typeof e.passCount === "number" && typeof e.total === "number" ? `${e.passCount}/${e.total}` : "—";
  // Card 92-10: `tr` is the global i18n helper (window.byokicuTr, declared in app.jsx).
  // Verdict comes from the backend as a fixed token (trusted/solid/partial/weak); map it,
  // but fall back to the raw value if it's ever something unmapped.
  const vlabel = (v) => {
    if (!v) return "—";
    const t = tr("verdict." + v);
    return t === "verdict." + v ? v : t;
  };

  return (
    <section id="leaderboard" className="leaderboard" aria-label="Relay leaderboard">
      <div className="leaderboard-head">
        <h2>{tr("lb.title")}</h2>
        <span className="muted">{tr("lb.subtitle")}</span>
      </div>
      {loading ? (
        <p className="leaderboard-empty">{tr("lb.loading")}</p>
      ) : entries.length === 0 ? (
        <p className="leaderboard-empty">
          {tr("lb.empty")}
        </p>
      ) : (
        <table className="leaderboard-table">
          <thead>
            <tr>
              <th>{tr("lb.col.rank")}</th><th>{tr("lb.col.endpoint")}</th><th>{tr("lb.col.model")}</th><th>{tr("lb.col.score")}</th><th>{tr("lb.col.verdict")}</th>
              <th>{tr("lb.col.tested")}</th><th>{tr("lb.col.latency")}</th><th>{tr("lb.col.pass")}</th>
            </tr>
          </thead>
          <tbody>
            {/* Card 92-11: relay endpoint (host) is the primary identity column, then model + score. */}
            {entries.map((e) => (
              <tr key={e.rank}>
                <td>{e.rank}</td>
                <td className="lb-endpoint">{e.host || "—"}</td>
                <td className="lb-model">{e.model || "—"}{e.provider ? <span className="lb-provider"> · {e.provider}</span> : null}</td>
                <td><b>{e.score}</b></td>
                <td>{vlabel(e.verdict)}</td>
                <td>{fmtDate(e.testedAt)}</td>
                <td>{fmtMs(e.latencyMs)}</td>
                <td>{fmtPass(e)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </section>
  );
}

Object.assign(window, { HeroIntro, LeaderBoard });
