/* evaluation.jsx — Flow 7: business-facing model comparison + deploy */

function fmt(v, unit) {
  if (unit === "$") return "$" + v.toFixed(2);
  if (unit === "s") return v.toFixed(1) + "s";
  return v + unit;
}

function MetricRow({ m }) {
  const lowBetter = m.better === "low";
  // normalize bar widths to a shared scale per metric
  const max = Math.max(m.base, m.tuned) * 1.15;
  const wBase = (m.base / max) * 100, wTuned = (m.tuned / max) * 100;
  const improved = lowBetter ? m.tuned < m.base : m.tuned > m.base;
  const pct = Math.round(Math.abs((m.tuned - m.base) / m.base) * 100);
  return (
    <div style={{ padding: "14px 0", borderBottom: "1px solid var(--border)" }}>
      <div className="between" style={{ marginBottom: 9 }}>
        <span style={{ fontSize: 13.5, fontWeight: 600 }}>{m.key}</span>
        <span className={cx("delta", improved ? "up" : "down")}>
          {I(lowBetter ? "trend" : "trend", { style: { width: 13, height: 13, transform: improved && lowBetter ? "scaleY(-1)" : "none" } })}
          {improved ? "−" : "+"}{pct}% {lowBetter ? "lower" : "better"}
        </span>
      </div>
      <div className="stack" style={{ gap: 7 }}>
        <div className="row" style={{ gap: 10 }}>
          <span className="caption" style={{ width: 56, flex: "none" }}>Original</span>
          <div className="meter" style={{ height: 9 }}><i style={{ width: wBase + "%", background: "var(--viz-base)" }} /></div>
          <span className="tnum" style={{ width: 56, textAlign: "right", fontSize: 12.5, fontWeight: 600, color: "var(--ink-2)" }}>{fmt(m.base, m.unit)}</span>
        </div>
        <div className="row" style={{ gap: 10 }}>
          <span className="caption" style={{ width: 56, flex: "none", fontWeight: 700, color: "var(--ink)" }}>Tuned</span>
          <div className="meter" style={{ height: 9 }}><i style={{ width: wTuned + "%", background: improved ? "var(--good)" : "var(--bad)" }} /></div>
          <span className="tnum" style={{ width: 56, textAlign: "right", fontSize: 12.5, fontWeight: 700 }}>{fmt(m.tuned, m.unit)}</span>
        </div>
      </div>
    </div>
  );
}

function AnswerCompare({ pair }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }} className="ac-grid">
      <div className="card" style={{ overflow: "hidden", borderColor: "var(--border)" }}>
        <div className="card-hd between" style={{ padding: "11px 14px" }}>
          <span className="row" style={{ gap: 7, fontSize: 12.5, fontWeight: 700, color: "var(--ink-2)" }}><span className="dot" style={{ background: "var(--viz-base)" }} /> Original RAG + base</span>
          <span className="tnum" style={{ fontWeight: 700, color: TONE_VAR[toneFor(pair.baseScore)] }}>{pair.baseScore}</span>
        </div>
        <div className="card-pad" style={{ padding: 14, fontSize: 13, lineHeight: 1.55, color: "var(--ink-2)" }}>{pair.base}</div>
      </div>
      <div className="card" style={{ overflow: "hidden", borderColor: "var(--good-border)", boxShadow: "0 0 0 1px var(--good-border)" }}>
        <div className="card-hd between" style={{ padding: "11px 14px", background: "var(--good-bg)", borderColor: "var(--good-border)" }}>
          <span className="row" style={{ gap: 7, fontSize: 12.5, fontWeight: 700, color: "var(--good-strong)" }}>{I("spark", { style: { width: 13, height: 13 } })} Fine-tuned + RAG</span>
          <span className="tnum" style={{ fontWeight: 700, color: "var(--good-strong)" }}>{pair.tunedScore}</span>
        </div>
        <div className="card-pad" style={{ padding: 14, fontSize: 13, lineHeight: 1.55 }}>{pair.tuned}</div>
      </div>
    </div>
  );
}

function EvaluationView({ ctx }) {
  const { EVAL_METRICS, EVAL_PAIRS } = window.DEMO;
  const [pairIdx, setPairIdx] = React.useState(0);
  const [adv, setAdv] = React.useState(false);
  const winRate = 78;

  if (!ctx.ftReady) {
    return (
      <div className="page">
        <PageHead eyebrow="Improve · Evaluation" title="Evaluation" sub="Once you've fine-tuned a model, this is where you'll compare it head-to-head with your current chatbot." />
        <div className="card"><Empty icon="gauge" title="No fine-tuned model yet" sub="Train a model in the Fine-Tuning Studio to unlock a business-facing comparison." /></div>
        <div className="row" style={{ justifyContent: "center", marginTop: 18 }}><button className="btn btn-primary" onClick={() => ctx.setView("finetune")}>{I("layers")} Go to Fine-Tuning Studio</button></div>
      </div>
    );
  }

  return (
    <div className="page page-wide">
      <PageHead eyebrow="Improve · Evaluation"
        title="Evaluation & comparison"
        sub="Vela Support Model v1 (fine-tuned) vs. your original RAG chatbot, measured on 35 held-out customer questions." />

      {/* hero headline */}
      <div className="card card-pad fu fu-1" style={{ marginBottom: 20 }}>
        <div className="between wrap" style={{ gap: 24 }}>
          <div className="row" style={{ gap: 22 }}>
            <Ring value={winRate} size={92} stroke={9} tone="good" label="win rate" />
            <div>
              <div className="badge badge-good" style={{ marginBottom: 8 }}>{I("trend", { style: { width: 12, height: 12 } })} Recommended to deploy</div>
              <h2 className="h1" style={{ maxWidth: 460, lineHeight: 1.15 }}>Fine-tuned model wins <span style={{ color: "var(--good)" }}>{winRate}%</span> of eval cases</h2>
              <p className="lead" style={{ fontSize: 14, marginTop: 6 }}>Better accuracy and brand voice, fewer hallucinations, and lower cost per request.</p>
            </div>
          </div>
          <div className="stack" style={{ gap: 8, minWidth: 200 }}>
            <div className="caption">Head-to-head preference</div>
            <div className="row" style={{ height: 30, borderRadius: 8, overflow: "hidden", border: "1px solid var(--border)" }}>
              <div style={{ width: winRate + "%", background: "var(--good)", color: "#fff", display: "flex", alignItems: "center", paddingLeft: 10, fontSize: 12, fontWeight: 700 }}>{winRate}%</div>
              <div style={{ width: (100 - winRate) + "%", background: "var(--surface-3)", color: "var(--ink-2)", display: "flex", alignItems: "center", justifyContent: "flex-end", paddingRight: 10, fontSize: 12, fontWeight: 700 }}>{100 - winRate}%</div>
            </div>
            <div className="between caption"><span>Fine-tuned</span><span>Original</span></div>
          </div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20, alignItems: "start" }} className="ev-grid">
        {/* metrics */}
        <div className="card card-pad fu fu-2">
          <div className="between" style={{ marginBottom: 6 }}>
            <span className="h3">Business metrics</span>
            <div className="row" style={{ gap: 12 }}>
              <span className="row caption" style={{ gap: 5 }}><span className="dot" style={{ background: "var(--viz-base)" }} /> Original</span>
              <span className="row caption" style={{ gap: 5 }}><span className="dot" style={{ background: "var(--good)" }} /> Tuned</span>
            </div>
          </div>
          <div className="stack">
            {EVAL_METRICS.map(m => <MetricRow key={m.key} m={m} />)}
          </div>
          <button className="row" onClick={() => setAdv(a => !a)} style={{ gap: 6, marginTop: 13, background: "none", border: "none", color: "var(--ink-2)", cursor: "pointer", fontSize: 12.5, fontWeight: 600, padding: 0 }}>
            {I(adv ? "chevD" : "chevR", { style: { width: 14, height: 14 } })} Advanced training details
          </button>
          {adv && (
            <div className="fu" style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 10, marginTop: 12 }}>
              {[["Final train loss", "0.54"], ["Final val loss", "0.61"], ["Eval cases", "35"], ["Epochs", "3"], ["LoRA rank", "16"], ["Tokens trained", "1.2M"]].map(([l, v]) => (
                <div key={l} className="tile" style={{ padding: 11 }}><div className="caption">{l}</div><div className="mono" style={{ fontSize: 14, fontWeight: 700, marginTop: 2 }}>{v}</div></div>
              ))}
            </div>
          )}
        </div>

        {/* side by side answers */}
        <div className="stack fu fu-3" style={{ gap: 14 }}>
          <div className="card card-pad">
            <div className="h3" style={{ marginBottom: 4 }}>Same question, side by side</div>
            <div className="caption" style={{ marginBottom: 13 }}>See how the fine-tuned model handles real customer questions.</div>
            <div className="stack" style={{ gap: 7 }}>
              {EVAL_PAIRS.map((p, i) => (
                <button key={i} onClick={() => setPairIdx(i)} className="row" style={{ gap: 9, textAlign: "left", padding: "10px 12px", borderRadius: "var(--r-md)", cursor: "pointer", border: "1px solid", borderColor: pairIdx === i ? "var(--primary)" : "var(--border)", background: pairIdx === i ? "var(--primary-soft)" : "var(--surface)" }}>
                  <span style={{ color: "var(--ink-3)", flex: "none" }}>{I("chat", { style: { width: 15, height: 15 } })}</span>
                  <span style={{ fontSize: 12.5, fontWeight: 500, flex: 1 }}>{p.q}</span>
                  <LabelTag id={p.label} />
                </button>
              ))}
            </div>
          </div>
          <AnswerCompare pair={EVAL_PAIRS[pairIdx]} />
        </div>
      </div>

      {/* final cta */}
      <div className="card card-pad between wrap fu" style={{ gap: 16, marginTop: 22, background: "var(--primary)", borderColor: "var(--primary)" }}>
        <div className="row" style={{ gap: 14 }}>
          <div style={{ width: 44, height: 44, borderRadius: "var(--r-md)", background: "rgba(255,255,255,.14)", color: "var(--primary-ink)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>{I("rocket", { style: { width: 22, height: 22 } })}</div>
          <div>
            <div className="h3" style={{ color: "var(--primary-ink)" }}>Deploy the fine-tuned model</div>
            <div style={{ fontSize: 12.5, color: "var(--primary-ink)", opacity: .72 }}>Serves <b>Fine-tuned model + RAG</b> — RAG for knowledge, fine-tuning for behavior & voice.</div>
          </div>
        </div>
        <button className="btn btn-lg" style={{ background: "var(--primary-ink)", color: "var(--primary)" }}
          onClick={() => { ctx.setModel({ ...ctx.model, tier: "Vela Support v1 (tuned)" }); ctx.setDeployed(true); ctx.setView("deploy"); }}>
          {I("rocket")} Deploy fine-tuned model
        </button>
      </div>
      <style>{`@media(max-width:1040px){.ev-grid{grid-template-columns:1fr !important}}@media(max-width:560px){.ac-grid{grid-template-columns:1fr !important}}`}</style>
    </div>
  );
}
window.EvaluationView = EvaluationView;
