/* ============================================================
   Eval Pulse — sections
   ============================================================ */

/* synth a smooth ~N-point history that lands exactly on `end` */
function makeMini(end, delta, n = 18) {
  const start = Math.max(0.04, end - (delta || 0.02) * 2.4);
  const arr = [];
  for (let i = 0; i < n; i++) {
    const t = i / (n - 1);
    const base = start + (end - start) * t;
    const wob = Math.sin(i * 1.7) * 0.012 + Math.sin(i * 0.55) * 0.008;
    arr.push(Math.max(0.03, Math.min(0.99, +(base + wob).toFixed(3))));
  }
  arr[n - 1] = end;
  return arr;
}
function miniSeries(end, delta, n = 18) {
  return makeMini(end, delta, n).map((v, i) => ({
    pr: v, sy: v,
    label: i === 0 ? "30d ago" : i === n - 1 ? "today" : "",
    date: i === n - 1 ? "Today" : (n - 1 - i) + "d ago"
  }));
}
function fmtAsOf(iso) {
  const d = new Date(iso);
  const t = d.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", timeZone: "UTC" });
  const day = d.toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" });
  return `${day}, ${t} UTC`;
}

/* ---------------- Header ---------------- */
function Header({ data, theme, onToggle }) {
  const live = data.run_status === "live";
  return (
    <header className="topbar reveal">
      <div className="brand">
        <img className="wordmark" alt="Intuigence"
          src={theme === "dark" ? "assets/logo-wordmark-white.svg" : "assets/logo-wordmark-dark.svg"} />
        <span className="brand-sep"></span>
        <div className="product">
          <div className="product-name">Eval Pulse</div>
          <div className="product-meta">{data.customer} · <span className="mono">{data.judge_model}</span></div>
        </div>
      </div>
      <div className="topbar-right">
        <div className={`run-chip ${live ? "is-live" : "is-complete"}`}>
          {live ? <span className="live-dot"></span> : <Icon name="check" size={14} stroke={2.6} />}
          {live ? "Run in progress" : "Run complete"}
        </div>
        <button className="theme-btn" onClick={onToggle} aria-label="Toggle theme">
          <Icon name={theme === "dark" ? "sun" : "moon"} size={18} />
        </button>
      </div>
    </header>
  );
}

/* ---------------- Hero ---------------- */
function Hero({ data }) {
  const t = data.today, d = data.deltas;
  const live = data.run_status === "live";
  const b = t.bands, btot = b.pass + b.partial + b.fail;
  return (
    <section className="card hero reveal" style={{ "--i": 1 }}>
      <div className="card-head">
        <h2 className="card-title">Today's Score</h2>
        <span className="card-sub"><Icon name="clock" size={13} /> as of {fmtAsOf(data.as_of)}</span>
      </div>
      <div className="hero-body">
        <div className="hero-ring">
          <Ring size={250} stroke={24} progress={t.overall_pass_rate} color="#FF4F17">
            {live && <div className="live-badge"><span className="live-dot"></span>LIVE</div>}
            <div className="ring-num">{pct(t.overall_pass_rate)}<span className="ring-pctsign">%</span></div>
            <div className="ring-cap">Overall pass rate</div>
          </Ring>
        </div>
        <div className="hero-detail">
          <div className="stat-chips">
            <div className="stat-chip">
              <div className="stat-k">Cases done</div>
              <div className="stat-v">{t.cases_completed}<span className="stat-of"> / {t.cases_total}</span></div>
            </div>
            <div className="stat-chip">
              <div className="stat-k">Synthesis</div>
              <div className="stat-v">{t.synthesis_score_mean.toFixed(2)}</div>
            </div>
            <div className="stat-chip">
              <div className="stat-k">Errored</div>
              <div className={"stat-v " + (t.cases_errored > 0 ? "stat-warn" : "")}>{t.cases_errored}</div>
            </div>
          </div>
          <div className="bands">
            <div className="bands-bar">
              <span style={{ width: (b.pass / btot * 100) + "%", background: BAND_COLOR.pass }}></span>
              <span style={{ width: (b.partial / btot * 100) + "%", background: BAND_COLOR.partial }}></span>
              <span style={{ width: (b.fail / btot * 100) + "%", background: BAND_COLOR.fail }}></span>
            </div>
            <div className="bands-legend">
              <span><i style={{ background: BAND_COLOR.pass }}></i>{b.pass} Pass</span>
              <span><i style={{ background: BAND_COLOR.partial }}></i>{b.partial} Partial</span>
              <span><i style={{ background: BAND_COLOR.fail }}></i>{b.fail} Fail</span>
            </div>
          </div>
          <div className="delta-row">
            <DeltaPill value={d.vs_yesterday.pass_rate} label="vs Yesterday" />
            <DeltaPill value={d.vs_last_week.pass_rate} label="vs Last Week" />
            <DeltaPill value={d.vs_month_ago.pass_rate} label="vs Month Ago" />
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Trend ---------------- */
const RANGES = ["D", "W", "M", "6M", "Y"];
function TrendSection() {
  const [range, setRange] = useState("M");
  const [show, setShow] = useState({ pr: true, sy: true });
  const series = window.RANGE_SERIES[range];
  const meta = window.RANGE_META[range];
  function toggle(key) {
    setShow(s => {
      const next = { ...s, [key]: !s[key] };
      if (!next.pr && !next.sy) return s; // keep at least one
      return next;
    });
  }
  return (
    <section className="card reveal" style={{ "--i": 2 }}>
      <div className="card-head">
        <div>
          <h2 className="card-title">Trend</h2>
          <span className="card-sub">{meta.caption}</span>
        </div>
        <div className="legend">
          <button className={"leg-pill " + (show.pr ? "on" : "")} onClick={() => toggle("pr")}>
            <span className="dot" style={{ background: "#FF4F17" }}></span>Pass rate
          </button>
          <button className={"leg-pill " + (show.sy ? "on" : "")} onClick={() => toggle("sy")}>
            <span className="dot" style={{ background: "#0052B4" }}></span>Synthesis
          </button>
        </div>
      </div>
      <TrendChart series={series} show={show} height={300} />
      <div className="segmented">
        {RANGES.map(r => (
          <button key={r} className={"seg " + (range === r ? "active" : "")} onClick={() => setRange(r)}>{r}</button>
        ))}
      </div>
    </section>
  );
}

/* ---------------- Highlights ---------------- */
const TONE_ICON = { positive: "trending", watch: "alert", negative: "arrowDown" };
function Highlights({ items }) {
  return (
    <section className="hl-section reveal" style={{ "--i": 3 }}>
      <h2 className="section-title"><Icon name="sparkles" size={18} /> Highlights</h2>
      <div className="hl-row">
        {items.map((h, i) => (
          <div key={i} className={"hl-card tone-" + h.tone}>
            <div className="hl-ic"><Icon name={TONE_ICON[h.tone]} size={20} stroke={2.2} /></div>
            <div className="hl-tag">{h.tone === "positive" ? "Positive" : h.tone === "watch" ? "Watch" : "Down"}</div>
            <div className="hl-text">{h.text}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ---------------- Graders ---------------- */
function GraderRow({ g, open, onToggle }) {
  const c = bandColor(g.pass_rate);
  return (
    <div className={"grader " + (open ? "open" : "")}>
      <button className="grader-main" onClick={onToggle}>
        <span className="band-dot" style={{ background: c }}></span>
        <span className="grader-label">{g.label}</span>
        <span className="grader-spark"><Sparkline points={makeMini(g.pass_rate, g.delta_week, 14)} color={c} width={88} height={30} /></span>
        <span className="grader-pct" style={{ color: c }}>{pct(g.pass_rate)}%</span>
        <span className="grader-delta"><MiniDelta value={g.delta_week} /></span>
        <span className="grader-chev"><Icon name="chevron" size={16} /></span>
      </button>
      <div className="grader-detail" style={{ gridTemplateRows: open ? "1fr" : "0fr" }}>
        <div className="grader-detail-inner">
          <div className="gd-stats">
            <div className="gd-stat"><span>Pass rate</span><b style={{ color: c }}>{pct(g.pass_rate)}%</b></div>
            <div className="gd-stat"><span>Mean score</span><b>{g.mean_score.toFixed(2)}</b></div>
            <div className="gd-stat"><span>Band</span><b style={{ color: c }}>{bandLabel(g.pass_rate)}</b></div>
            <div className="gd-stat"><span>Week</span><b><MiniDelta value={g.delta_week} /></b></div>
          </div>
          {open && <TrendChart series={miniSeries(g.pass_rate, g.delta_week, 18)} show={{ pr: true, sy: false }} height={170} />}
        </div>
      </div>
    </div>
  );
}
function Graders({ items }) {
  const [openId, setOpenId] = useState(null);
  return (
    <section className="card reveal" style={{ "--i": 4 }}>
      <div className="card-head">
        <div>
          <h2 className="card-title">Grader Health</h2>
          <span className="card-sub">{items.length} Stage-1 LLM judges · tap to expand</span>
        </div>
      </div>
      <div className="grader-list">
        {items.map(g => (
          <GraderRow key={g.id} g={g} open={openId === g.id} onToggle={() => setOpenId(openId === g.id ? null : g.id)} />
        ))}
      </div>
    </section>
  );
}

/* ---------------- Domains ---------------- */
function DomainCard({ dom, open, onToggle }) {
  const c = bandColor(dom.pass_rate);
  return (
    <div className={"dom-card " + (open ? "open" : "")} onClick={onToggle}>
      <div className="dom-top">
        <div className="dom-name">
          <span className="band-dot" style={{ background: c }}></span>{dom.name}
        </div>
        <MiniDelta value={dom.delta_week} />
      </div>
      <div className="dom-ring">
        <Ring size={104} stroke={11} progress={dom.pass_rate} color="#FF4F17" glow={false}>
          <div className="dom-ring-num">{pct(dom.pass_rate)}<span>%</span></div>
        </Ring>
      </div>
      <div className="dom-foot">
        <div className="dom-meta">
          <span>Mean <b>{dom.mean_score.toFixed(2)}</b></span>
          <span>{dom.cases} cases</span>
        </div>
        <Sparkline points={makeMini(dom.pass_rate, dom.delta_week, 14)} color={c} width={72} height={26} />
      </div>
      <div className="dom-expand" style={{ gridTemplateRows: open ? "1fr" : "0fr" }}>
        <div className="dom-expand-inner">
          {open && <TrendChart series={miniSeries(dom.pass_rate, dom.delta_week, 18)} show={{ pr: true, sy: false }} height={150} />}
        </div>
      </div>
    </div>
  );
}
function Domains({ items }) {
  const [openName, setOpenName] = useState(null);
  return (
    <section className="dom-section reveal" style={{ "--i": 5 }}>
      <h2 className="section-title"><Icon name="grid" size={17} /> By Category</h2>
      <div className="dom-grid">
        {items.map(dom => (
          <DomainCard key={dom.name} dom={dom} open={openName === dom.name}
            onToggle={() => setOpenName(openName === dom.name ? null : dom.name)} />
        ))}
      </div>
    </section>
  );
}

/* ---------------- Regression ---------------- */
function RegRow({ label, m }) {
  const dPrev = m.current - m.previous;
  const dMonth = m.current - m.month_ago;
  return (
    <div className="reg-row">
      <div className="reg-label">{label}</div>
      <div className="reg-ladder">
        <div className="reg-step">
          <span className="reg-k">Month ago</span>
          <span className="reg-v muted">{pct(m.month_ago)}%</span>
        </div>
        <Icon name="chevron" size={15} className="reg-arrow" />
        <div className="reg-step">
          <span className="reg-k">Previous</span>
          <span className="reg-v muted">{pct(m.previous)}%</span>
        </div>
        <Icon name="chevron" size={15} className="reg-arrow" />
        <div className="reg-step">
          <span className="reg-k">Current</span>
          <span className="reg-v cur">{pct(m.current)}%</span>
        </div>
      </div>
      <div className="reg-deltas">
        <DeltaPill value={dPrev} label="vs prev" size="sm" />
        <DeltaPill value={dMonth} label="vs month" size="sm" />
      </div>
    </div>
  );
}
function Regression({ reg }) {
  return (
    <section className="card reveal" style={{ "--i": 6 }}>
      <div className="card-head">
        <div>
          <h2 className="card-title">Are we improving?</h2>
          <span className="card-sub">Current vs previous vs month-ago</span>
        </div>
        <Icon name="scale" size={20} className="reg-headic" />
      </div>
      <div className="reg-body">
        <RegRow label="Overall pass rate" m={reg.overall_pass_rate} />
        <div className="reg-div"></div>
        <RegRow label="Synthesis score" m={reg.synthesis_score} />
      </div>
    </section>
  );
}

Object.assign(window, { Header, Hero, TrendSection, Highlights, Graders, Domains, Regression });
