/* Fix studio — defect → applied fix → verified (post-resolution call detail) */

const TRANSCRIPT = [
  { ts: "00:38.420", who: "caller", text: "Hi, I need to change my flight. Booking is A-B-one-zero-zero.",
    eventKey: null },
  { ts: "00:42.110", who: "agent",  text: "Got it — pulling up A-B-one-zero-O now—",
    eventKey: "interruption", meta: "interruption +180ms" },
  { ts: "00:43.880", who: "caller", text: "—no, it's one-zero-zero, all numbers.",
    eventKey: "interruption" },
  { ts: "00:46.220", who: "agent",  text: "lookup_booking(\"AB10O\")", tool: true,
    eventKey: "tool_failure", meta: "latency 2.1s" },
  { ts: "00:49.610", who: "tool",   text: "booking_not_found", tool: true,
    eventKey: "tool_failure" },
  { ts: "00:50.450", who: "agent",  text: "Hmm, I'm not finding that. Could you spell it again?",
    eventKey: null },
  { ts: "00:54.110", who: "caller", text: "[silence 3.4s] \u201CI just said AB100. One hundred.\u201D",
    eventKey: "silence", meta: "silence 3.4s" },
  { ts: "00:58.420", who: "agent",  text: "lookup_booking(\"AB100\") \u2192 confirmed", tool: true,
    eventKey: null },
  { ts: "00:59.880", who: "agent",  text: "Got it \u2014 AB100, JFK to Frankfurt, May 30th. What\u2019s the new date?",
    eventKey: null },
  { ts: "01:01.420", who: "caller", text: "June 4th, morning if possible.",
    eventKey: null },
  { ts: "01:03.220", who: "agent",  text: "lookup_availability(\"AB100\", \"2026-06-04\")", tool: true,
    eventKey: null, meta: "latency 1.4s" },
  { ts: "01:06.110", who: "agent",  text: "Three morning options. The 07:15 keeps your connection \u2014 want me to confirm that one?",
    eventKey: null },
];

/* Waveform events — all amber, three failure moments.
   Positions are stylized for visual spread (literal timestamps in transport). */
const EVENTS = [
  { key: "interruption", pos: 0.25, span: 0.04, label: "interruption", timeStr: "00:42", linkTo: 0 },
  { key: "tool_failure", pos: 0.46, span: 0.08, label: "tool failure", timeStr: "00:49", linkTo: 1 },
  { key: "silence",      pos: 0.62, span: 0.05, label: "silence",      timeStr: "00:54", linkTo: null },
];

const DEFECTS = [
  {
    sev: "high",
    h: "LLM digit/letter confusion: 0 \u2192 O",
    when: "00:42.110",
    detail: "ASR transcribed \u201Cone-zero-zero\u201D correctly; the LLM substituted O for the trailing 0 in its response, propagating into TTS readback and the lookup_booking arg.",
    eventKey: "interruption",
  },
  {
    sev: "med",
    h: "No canonicalization retry on tool failure",
    when: "00:49.610",
    detail: "lookup_booking returned not_found; agent re-asked instead of O\u21920 retry",
    eventKey: "tool_failure",
  },
  {
    sev: "low",
    h: "Missing read-back before high-stakes lookup",
    detail: "pattern across 14% of lookup_booking calls",
    eventKey: null,
  },
];

const VERIFIED = [
  { text: "47/47 regression tests passed" },
  { text: "p95 latency net \u22121.7s", sub: "(+0.4s read-back, \u22122.1s no retry loop)" },
  { text: "2 new tests added from this failure" },
];

const APPLIED_FIX = "Added alphanumeric-ID normalizer in tool args (O\u21920, I\u21921, S\u21925 when adjacent to digits). Required read-back confirmation for booking references before lookup_booking. Capped retries at 2 with auto-canonicalization.";

function ReplaySection() {
  /* Default to defect 0 (the origin defect — LLM digit confusion) */
  const [activeEventIdx, setActiveEventIdx] = React.useState(0);
  const activeEvent = EVENTS[activeEventIdx] || null;
  const activeEventKey = activeEvent ? activeEvent.key : null;
  const playhead = activeEvent ? activeEvent.pos : 0.25;
  const nowStr = activeEvent ? activeEvent.timeStr : "00:42";

  /* Click a defect card → scrub to its event */
  const selectDefect = (defectIdx) => {
    const d = DEFECTS[defectIdx];
    if (!d || !d.eventKey) return;
    const eventIdx = EVENTS.findIndex(e => e.key === d.eventKey);
    if (eventIdx >= 0) setActiveEventIdx(eventIdx);
  };

  const activeDefectIdx = DEFECTS.findIndex(d => d.eventKey && d.eventKey === activeEventKey);

  return (
    <section className="block" style={{ paddingTop: 60 }} data-screen-label="03 fix">
      <div className="wrap">
        <div className="fix-lede">
          <div className="section-eyebrow">Fix studio</div>
          <h2 className="section-title">
            From failure <span className="ink-soft">to verified.</span>
          </h2>
          <p className="section-sub">
            Audia pinpoints the defect, applies the fix, and runs the regression harness
            before you ship.
          </p>
        </div>

        <div className="replay-card" data-comment-anchor="replay-card">
          <div className="replay-head">
            <div className="breadcrumb">
              <span className="id">call_7f9a13</span>
            </div>
            <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
              <button className="btn" style={{ padding: "6px 10px", fontSize: 12 }}>export trace</button>
            </div>
          </div>

          <div className="replay-body">
            <div className="replay-main">
              <div className="transport">
                <button className="play" aria-label="Play"><Icon name="play" size={14} color="#FBFAF7"/></button>
                <div className="time">
                  <span className="now">{nowStr}</span>
                  <span style={{ color: "var(--mute-2)" }}> / 01:08</span>
                </div>
                <span className="speed" style={{ opacity: 0.55, border: "none", padding: "3px 4px" }}>1.8×</span>
                <span className="pill" style={{ marginLeft: 2, opacity: 0.55, borderColor: "var(--hair)" }}>follow playhead</span>
              </div>

              <div className="ts-track">
                <ReplayWave
                  playhead={playhead}
                  events={EVENTS}
                  activeIndex={activeEventIdx}
                  onSelectEvent={(i) => setActiveEventIdx(i)}
                />
                <div style={{
                  position: "absolute", left: 0, right: 0, bottom: 0,
                  display: "flex", justifyContent: "space-between",
                  padding: "0 12px 6px",
                  fontFamily: "Geist Mono, monospace", fontSize: 10, color: "var(--mute)"
                }}>
                  <span>00:00</span>
                  <span>00:08</span>
                  <span>00:17</span>
                  <span>00:25</span>
                  <span>00:34</span>
                  <span>00:42</span>
                  <span>00:51</span>
                  <span>01:00</span>
                  <span>01:08</span>
                </div>
              </div>

              <div className="transcript focal">
                {TRANSCRIPT.map((t, i) => {
                  const isActive = t.eventKey && t.eventKey === activeEventKey;
                  return (
                    <div key={i} className={
                      "turn" +
                      (isActive ? " flag" : "") +
                      (t.tool ? " tool-row" : "") +
                      (t.who === "tool" ? " tool-result" : "")
                    }>
                      <div className="t-ts">{t.ts}</div>
                      <div className="who">{t.who}</div>
                      <div className="text">
                        {t.tool
                          ? <span className="mono tool-text">{t.text}</span>
                          : t.text}
                      </div>
                      <div className="t-meta">
                        {t.meta && <span className="meta-pill">{t.meta}</span>}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            <div className="issues">
              {/* DEFECT — step 1 */}
              <div className="fix-card">
                <div className="fix-head">
                  <span className="num">1</span>
                  <h4>Defect</h4>
                  <span className="count">3 issues · click to scrub</span>
                </div>
                <div className="fix-body">
                  {DEFECTS.map((d, i) => {
                    const isActive = i === activeDefectIdx;
                    const clickable = !!d.eventKey;
                    return (
                      <div
                        className={"issue" + (isActive ? " active" : "")}
                        key={i}
                        onClick={() => clickable && selectDefect(i)}
                        role={clickable ? "button" : undefined}
                        tabIndex={clickable ? 0 : undefined}
                        style={{
                          cursor: clickable ? "pointer" : "default",
                          borderLeft: `3px solid ${isActive ? "oklch(0.62 0.20 60)" : "transparent"}`,
                          paddingLeft: 10
                        }}
                      >
                        <div className="top">
                          <span className="h">{d.h}</span>
                          <span className={"sev sev-" + d.sev}>{d.sev}</span>
                        </div>
                        {d.when && (
                          <div className="meta">
                            <span className="when" style={{ color: isActive ? "oklch(0.55 0.18 60)" : "var(--ink-soft)" }}>{d.when}</span>
                          </div>
                        )}
                        <div className="defect-detail">{d.detail}</div>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* PROPOSED FIX — step 2, drafted by Audia, shipped on your approval (PR) */}
              <div className="fix-card applied-banner">
                <div className="fix-head">
                  <span className="num">2</span>
                  <h4>Proposed fix</h4>
                </div>
                <div className="fix-body">
                  <p className="fix-prose">{APPLIED_FIX}</p>
                  <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
                    <button className="btn primary" style={{ padding: "6px 10px", fontSize: 12 }}>view PR #248</button>
                  </div>
                </div>
              </div>

              {/* VERIFIED — step 3, the differentiator, at the bottom */}
              <div className="fix-card verified verified-banner">
                <div className="fix-head">
                  <span className="num">3</span>
                  <h4>Verified</h4>
                  <span className="verified-stat">47<span className="of">/47</span></span>
                </div>
                <div className="fix-body">
                  <ul className="check-list">
                    {VERIFIED.map((v, i) => (
                      <li key={i}>
                        <span className="ck">✓</span>
                        <span>
                          {v.text}
                          {v.sub && <span className="v-sub"><br/>{v.sub}</span>}
                        </span>
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { ReplaySection });
