/* global React, Ic, Chip, Waveform, Sparkline, KPI, Panel, Av, AiBand */

const CALLS = [
  {
    id: "CALL-9182",
    status: "LIVE",
    load: "KW-48217",
    driver: "Carlos Mendez",
    phone: "+1 (956) 555-0142",
    carrier: "Hidalgo Logistics",
    duration: 42,
    started: "13:02:18",
    sentiment: "neutral",
    intent: "status-update",
    location: "I-35 N · 12mi N of San Antonio, TX",
    eta: "05/26 19:42",
    etaDelta: "+1h42",
    confidence: 91,
    lat: 29.6,
    lon: -98.5,
    risk: "DETENTION",
    transcript: [
      { who: "ai",     t: "00:00", say: "Hi, this is Keelway calling about Walmart load KW-48217 for Hidalgo. Is this Carlos?" },
      { who: "driver", t: "00:04", say: "Yeah, Carlos here." },
      { who: "ai",     t: "00:06", say: "Got it. Where are you right now and what's your ETA into Memphis?" },
      { who: "driver", t: "00:11", say: "I'm just north of San Antonio on 35. Had to stop for fuel and the scale was backed up bad." },
      { who: "ai",     t: "00:19", say: "Understood. So you're roughly 660 miles out. Are you running team or solo?" },
      { who: "driver", t: "00:25", say: "Solo. I'll need to break tonight, probably around Dallas." },
      { who: "ai",     t: "00:32", say: "Okay. That puts your delivery around 20:00 CT tomorrow — about 2 hours past the 18:00 appointment. Want me to call Memphis receiving to push the slot?" },
      { who: "driver", t: "00:39", say: "Yeah, that'd help. Can you text my dispatcher too?" },
      { who: "ai",     t: "00:42", say: "Texting Hidalgo now. Drive safe — I'll check in at 22:00.", live: true },
    ],
    extracted: [
      { field: "Current location", value: "I-35 N, 12mi N of San Antonio, TX", confidence: 98 },
      { field: "ETA Memphis",      value: "05/26 ~20:00 CT", confidence: 91 },
      { field: "Reason for delay", value: "Fuel stop + DOT scale backup", confidence: 87 },
      { field: "Driver status",    value: "Solo, planning Dallas break", confidence: 95 },
      { field: "Detention risk",   value: "~2hr past appointment", confidence: 89 },
    ],
  },
  { id: "CALL-9181", status: "QUEUED", load: "KW-48216", driver: "Ravi Singh",    carrier: "BluePeak",       duration: 0,  eta: "05/25 21:14", confidence: null, intent: "eta-confirm" },
  { id: "CALL-9180", status: "COMPLETE", load: "KW-48211", driver: "T. Petrov",    carrier: "Wasatch Lines",  duration: 38, eta: "05/25 22:00", confidence: 94, intent: "status-update", outcome: "ON-TIME" },
  { id: "CALL-9179", status: "COMPLETE", load: "KW-48207", driver: "K. Walker",    carrier: "Heartland",      duration: 22, eta: "05/25 13:18", confidence: 97, intent: "arrival-confirm", outcome: "ARRIVED" },
  { id: "CALL-9178", status: "COMPLETE", load: "KW-48210", driver: "J. Reyes",     carrier: "Pinecone",       duration: 64, eta: "05/26 03:30", confidence: 78, intent: "delay-report", outcome: "DELAYED 90M", risk: true },
  { id: "CALL-9177", status: "FAILED",   load: "KW-48209", driver: "L. Brown",     carrier: "Eastern Star",   duration: 12, intent: "status-update", outcome: "VOICEMAIL — retry @ 14:30" },
  { id: "CALL-9176", status: "COMPLETE", load: "KW-48212", driver: "M. Garcia",    carrier: "Gulf Trans",     duration: 28, eta: "delivered", confidence: 99, intent: "pod-confirm", outcome: "POD CAPTURED" },
];

function CheckCalls({ ctx }) {
  const variant = ctx.callVariant || "live";

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">AI Check Calls</div>
          <div className="page-sub">Auto-calling 147 active drivers · 12 today · 91% pickup rate</div>
        </div>
        <div className="page-actions">
          <span className="chip ok"><span className="dot pulse" /> AGENT LIVE</span>
          <span className="dim mono" style={{ fontSize: 11 }}>VOICE: KEELWAY-V3 · EN-US · WARM</span>
          <button className="btn ghost"><Ic.filter style={{ width: 12, height: 12 }} /> Filter</button>
          <button className="btn"><Ic.bot style={{ width: 12, height: 12 }} /> Call rules</button>
          <button className="btn primary"><Ic.phone style={{ width: 12, height: 12 }} /> Start call</button>
        </div>
      </div>

      <div className="grid cols-4 pad" style={{ paddingBottom: 0 }}>
        <KPI label="Calls Today" value="312" delta="22" spark={[18,22,24,26,28,30,32,35,40,38,42,44]} />
        <KPI label="Pickup Rate" value="91%" delta="2.4pt" spark={[80,82,84,85,86,88,90,89,91,91,92,91]} />
        <KPI label="Avg Duration" value="47s" delta="3s" deltaKind="down" spark={[60,58,55,52,52,50,49,48,47,46,47,47]} />
        <KPI label="At-Risk Surfaced" value="6" delta="2" spark={[2,3,2,4,3,5,4,5,6,6,7,6]} />
      </div>

      <div className="tabs" style={{ marginTop: 16 }}>
        <div className={`tab ${variant === "live" ? "active" : ""}`} onClick={() => ctx.setTweak("callVariant", "live")}>
          Live monitor <span className="count">3</span>
        </div>
        <div className={`tab ${variant === "queue" ? "active" : ""}`} onClick={() => ctx.setTweak("callVariant", "queue")}>
          Post-call queue <span className="count">12</span>
        </div>
        <div className={`tab ${variant === "map" ? "active" : ""}`} onClick={() => ctx.setTweak("callVariant", "map")}>
          Map view
        </div>
        <div className={`tab ${variant === "thread" ? "active" : ""}`} onClick={() => ctx.setTweak("callVariant", "thread")}>
          Threads (driver-centric)
        </div>
        <div style={{ marginLeft: "auto", padding: "4px 0", fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-dim)", letterSpacing: "0.12em" }}>
          VARIANT — TRY ALL FOUR
        </div>
      </div>

      {variant === "live"   && <CallsLive />}
      {variant === "queue"  && <CallsQueue />}
      {variant === "map"    && <CallsMap />}
      {variant === "thread" && <CallsThread />}
    </div>
  );
}

/* ─────────── VARIANT 1 — Live monitor with transcript ─────────── */
function CallsLive() {
  const call = CALLS[0];
  return (
    <div style={{ display: "grid", gridTemplateColumns: "260px 1fr 360px", minHeight: 600 }}>
      {/* Left: queue list */}
      <div style={{ borderRight: "1px solid var(--line)", overflowY: "auto" }}>
        <div className="h-rule" style={{ padding: "12px 14px 6px" }}>QUEUE · 12</div>
        {CALLS.map(c => (
          <CallListRow key={c.id} call={c} active={c.id === "CALL-9182"} />
        ))}
      </div>

      {/* Middle: live transcript */}
      <div style={{ display: "flex", flexDirection: "column" }}>
        <div style={{ padding: 16, borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 14 }}>
          <Av name={call.driver} />
          <div>
            <div style={{ fontWeight: 600 }}>{call.driver}</div>
            <div className="mono dim" style={{ fontSize: 11 }}>{call.carrier} · {call.phone} · LOAD {call.load}</div>
          </div>
          <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 12 }}>
            <Chip kind="danger" pulse>● ON CALL · 00:{String(call.duration).padStart(2,"0")}</Chip>
            <Waveform bars={36} active />
            <button className="btn ghost sm"><Ic.pause style={{ width: 10, height: 10 }} /></button>
            <button className="btn danger sm">End</button>
          </div>
        </div>

        <div style={{ padding: "12px 20px", borderBottom: "1px solid var(--line)", background: "var(--bg-1)", display: "flex", gap: 14, fontSize: 12 }}>
          <span><span className="dim mono" style={{ fontSize: 10 }}>INTENT</span> <Chip kind="info">STATUS UPDATE</Chip></span>
          <span><span className="dim mono" style={{ fontSize: 10 }}>SENTIMENT</span> <Chip>NEUTRAL · COOPERATIVE</Chip></span>
          <span><span className="dim mono" style={{ fontSize: 10 }}>RISK</span> <Chip kind="warn" pulse>DETENTION ~2H</Chip></span>
          <span style={{ marginLeft: "auto" }}><span className="dim mono" style={{ fontSize: 10 }}>CONFIDENCE</span> <span className="mono">{call.confidence}%</span></span>
        </div>

        <div style={{ padding: 20, overflowY: "auto", flex: 1 }} className="transcript">
          {call.transcript.map((t, i) => (
            <div key={i} className={`turn ${t.who}`}>
              <div className="who">{t.who === "ai" ? "KEELWAY" : "DRIVER"} <span className="faint">{t.t}</span></div>
              <div className="said">
                {renderSaid(t.say)}
                {t.live && <span className="chip danger" style={{ marginLeft: 6 }}><span className="dot pulse" /> SPEAKING</span>}
              </div>
            </div>
          ))}
        </div>

        <AiBand
          confidence={94}
          text={<>Keelway will text dispatcher and call Memphis receiving to push the appointment to 20:30. Continue?</>}
          actions={<>
            <button className="btn ghost sm">Modify</button>
            <button className="btn primary sm">Approve</button>
          </>}
        />
      </div>

      {/* Right: extracted facts + actions */}
      <aside className="inspector">
        <div style={{ padding: 14, borderBottom: "1px solid var(--line)" }}>
          <div className="h-rule">EXTRACTED · LIVE</div>
          <div style={{ marginTop: 10, display: "flex", flexDirection: "column", gap: 10 }}>
            {call.extracted.map((e, i) => (
              <div key={i}>
                <div className="kpi-label" style={{ marginBottom: 2 }}>{e.field}</div>
                <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12 }}>
                  <span style={{ flex: 1 }}>{e.value}</span>
                  <span className="mono dim" style={{ fontSize: 10 }}>{e.confidence}%</span>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={{ padding: 14, borderBottom: "1px solid var(--line)" }}>
          <div className="h-rule">CONTEXT</div>
          <div style={{ marginTop: 10, fontSize: 12, lineHeight: 1.7 }}>
            <div><span className="dim mono" style={{ fontSize: 10 }}>SHIPPER</span> Walmart DC #7034 (Memphis)</div>
            <div><span className="dim mono" style={{ fontSize: 10 }}>APPT</span> 05/26 18:00 CT (FCFS no)</div>
            <div><span className="dim mono" style={{ fontSize: 10 }}>HOS</span> 8h31m drive remaining</div>
            <div><span className="dim mono" style={{ fontSize: 10 }}>LAST PING</span> 4h12m ago (Cotulla TX)</div>
            <div><span className="dim mono" style={{ fontSize: 10 }}>PRIOR DETENTION</span> 2× in last 90d</div>
          </div>
        </div>

        <div style={{ padding: 14 }}>
          <div className="h-rule">SUGGESTED ACTIONS</div>
          <div style={{ marginTop: 10, display: "flex", flexDirection: "column", gap: 6 }}>
            <Suggest text="Text dispatcher with new ETA" conf={98} on />
            <Suggest text="Call Memphis receiving — push to 20:30" conf={94} on />
            <Suggest text="Email customer success @ Walmart" conf={71} />
            <Suggest text="Flag carrier for chronic detention" conf={62} />
          </div>
        </div>
      </aside>
    </div>
  );
}

function renderSaid(s) {
  // highlight key facts
  const re = /(I-35 N|Memphis|San Antonio|Dallas|20:00 CT|18:00 appointment|2 hours past|Hidalgo)/g;
  const parts = [];
  let last = 0, m;
  while ((m = re.exec(s)) !== null) {
    if (m.index > last) parts.push(s.slice(last, m.index));
    parts.push(<span key={m.index} className="hl">{m[0]}</span>);
    last = m.index + m[0].length;
  }
  parts.push(s.slice(last));
  return parts;
}

function CallListRow({ call, active }) {
  const stChip = {
    LIVE: { kind: "danger", pulse: true, label: "LIVE" },
    QUEUED: { kind: "warn", label: "QUEUED" },
    COMPLETE: { kind: "ok", label: "DONE" },
    FAILED: { kind: "", label: "FAILED" },
  }[call.status];
  return (
    <div style={{
      padding: "10px 14px",
      borderBottom: "1px solid var(--line)",
      background: active ? "var(--bg-sel)" : "transparent",
      borderLeft: active ? "2px solid var(--accent)" : "2px solid transparent",
      cursor: "pointer",
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
        <Chip kind={stChip.kind} pulse={stChip.pulse}>{stChip.label}</Chip>
        <span className="mono dim" style={{ fontSize: 10, marginLeft: "auto" }}>{call.id}</span>
      </div>
      <div style={{ fontSize: 12, fontWeight: 500 }}>{call.driver}</div>
      <div className="mono dim" style={{ fontSize: 10 }}>{call.carrier} · {call.load}</div>
      {call.outcome && <div style={{ fontSize: 11, marginTop: 4, color: call.risk ? "var(--warn)" : "var(--text-mid)" }}>{call.outcome}</div>}
    </div>
  );
}

function Suggest({ text, conf, on }) {
  return (
    <label style={{ display: "flex", alignItems: "center", gap: 8, padding: 8, background: on ? "var(--accent-bg)" : "var(--bg-2)", border: `1px solid ${on ? "var(--accent)" : "var(--line)"}`, borderRadius: 4, fontSize: 12, cursor: "pointer" }}>
      <input type="checkbox" defaultChecked={on} style={{ accentColor: "var(--accent)" }} />
      <span style={{ flex: 1 }}>{text}</span>
      <span className="mono dim" style={{ fontSize: 10 }}>{conf}%</span>
    </label>
  );
}

/* ─────────── VARIANT 2 — Post-call summary cards ─────────── */
function CallsQueue() {
  const cards = [
    { id: "CALL-9180", driver: "T. Petrov",   load: "KW-48211", outcome: "ON-TIME · ETA 05/25 22:00", chips: [{ k: "ok", l: "ON TIME" }], summary: "Driver confirmed Kansas City delivery on schedule. No issues. Will arrive 22:00 CT, ahead of 22:30 appt.", actions: 0, confidence: 94, dur: 38 },
    { id: "CALL-9178", driver: "J. Reyes",    load: "KW-48210", outcome: "DELAYED 90M · DETENTION", chips: [{ k: "danger", l: "DELAYED" }, { k: "warn", l: "DETENTION RISK" }], summary: "Shipper held driver 90 minutes at dock. Reno delivery now 03:30. Suggested: file detention claim, notify Raley's.", actions: 2, confidence: 78, dur: 64 },
    { id: "CALL-9179", driver: "K. Walker",   load: "KW-48207", outcome: "ARRIVED DETROIT 13:18", chips: [{ k: "ok", l: "ARRIVED" }], summary: "Driver at Meijer DC dock 4. POD will be captured at unload.", actions: 1, confidence: 97, dur: 22 },
    { id: "CALL-9177", driver: "L. Brown",    load: "KW-48209", outcome: "VOICEMAIL — RETRY 14:30", chips: [{ k: "", l: "NO ANSWER" }], summary: "Driver did not answer. Voicemail left. Retry scheduled for 14:30 (per call rules — 2nd attempt before SMS escalation).", actions: 1, confidence: null, dur: 12 },
    { id: "CALL-9176", driver: "M. Garcia",   load: "KW-48212", outcome: "POD CAPTURED · INVOICED", chips: [{ k: "ok", l: "POD" }, { k: "ok", l: "INVOICED" }], summary: "Tampa delivery complete. POD photo captured during call. Invoice 24011-A sent to Publix accounting.", actions: 0, confidence: 99, dur: 28 },
    { id: "CALL-9175", driver: "A. Kowalski", load: "KW-48205", outcome: "EQUIPMENT ISSUE", chips: [{ k: "warn", l: "MECHANICAL" }], summary: "Driver reports DEF system warning. Pulling into TA-Wytheville for diagnostic. May delay 2-4hr.", actions: 3, confidence: 84, dur: 51 },
  ];
  return (
    <div className="grid cols-3 pad">
      {cards.map(c => (
        <div className="panel" key={c.id} style={{ padding: 0 }}>
          <div style={{ padding: 12, display: "flex", alignItems: "center", gap: 8, borderBottom: "1px solid var(--line)" }}>
            <Av name={c.driver} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 600 }}>{c.driver}</div>
              <div className="mono dim" style={{ fontSize: 10 }}>{c.load} · {c.dur}s · {c.id}</div>
            </div>
            {c.confidence && <span className="mono dim" style={{ fontSize: 10 }}>{c.confidence}%</span>}
          </div>
          <div style={{ padding: 12 }}>
            <div style={{ display: "flex", gap: 6, marginBottom: 10, flexWrap: "wrap" }}>
              {c.chips.map((ch, i) => <Chip key={i} kind={ch.k}>{ch.l}</Chip>)}
            </div>
            <div style={{ fontSize: 12, color: "var(--text-mid)", lineHeight: 1.55 }}>{c.summary}</div>
          </div>
          <div style={{ padding: "8px 12px", borderTop: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 8 }}>
            <span className="mono dim" style={{ fontSize: 10 }}>
              {c.actions > 0 ? `${c.actions} ACTIONS QUEUED` : "NO ACTIONS"}
            </span>
            <button className="btn ghost sm" style={{ marginLeft: "auto" }}>Transcript</button>
            {c.actions > 0 && <button className="btn primary sm">Approve</button>}
          </div>
        </div>
      ))}
    </div>
  );
}

/* ─────────── VARIANT 3 — Map-centric ─────────── */
function CallsMap() {
  const pins = [
    { x: 18, y: 60, label: "C. Mendez", load: "KW-48217", status: "LIVE",     kind: "danger" },
    { x: 36, y: 38, label: "R. Singh",  load: "KW-48216", status: "QUEUED",   kind: "warn" },
    { x: 58, y: 52, label: "T. Petrov", load: "KW-48211", status: "DONE",     kind: "ok" },
    { x: 72, y: 42, label: "K. Walker", load: "KW-48207", status: "DONE",     kind: "ok" },
    { x: 12, y: 22, label: "J. Reyes",  load: "KW-48210", status: "DELAYED",  kind: "warn" },
    { x: 78, y: 70, label: "M. Garcia", load: "KW-48212", status: "DONE",     kind: "ok" },
    { x: 48, y: 78, label: "L. Brown",  load: "KW-48209", status: "FAILED",   kind: "" },
  ];
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 320px", minHeight: 640 }}>
      <div className="mapbg" style={{ position: "relative", overflow: "hidden" }}>
        {/* dashed US-ish outline */}
        <svg viewBox="0 0 100 80" preserveAspectRatio="none" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
          <path d="M5,30 Q10,10 30,12 Q55,8 70,15 Q90,18 95,35 Q92,55 80,65 Q60,75 40,72 Q15,68 8,55 Z" stroke="var(--line-strong)" strokeDasharray="2 3" fill="none" />
          {pins.map((p, i) => pins.slice(i + 1).map((q, j) => (
            <line key={`${i}-${j}`} x1={p.x} y1={p.y} x2={q.x} y2={q.y} stroke="var(--line)" strokeWidth="0.1" opacity="0.4" />
          )))}
        </svg>
        {pins.map((p, i) => (
          <div key={i} style={{ position: "absolute", left: `${p.x}%`, top: `${p.y}%`, transform: "translate(-50%, -100%)" }}>
            <div style={{
              background: "var(--bg-1)",
              border: `1px solid var(--${p.kind === "danger" ? "danger" : p.kind === "warn" ? "warn" : p.kind === "ok" ? "ok" : "line-strong"})`,
              borderRadius: 4,
              padding: "4px 8px",
              fontSize: 11,
              whiteSpace: "nowrap",
              boxShadow: "0 4px 12px rgba(0,0,0,0.4)",
              display: "flex", alignItems: "center", gap: 6,
            }}>
              <Chip kind={p.kind} pulse={p.status === "LIVE"}>{p.status}</Chip>
              <span>{p.label}</span>
              <span className="mono dim" style={{ fontSize: 9 }}>{p.load}</span>
            </div>
            <div style={{ width: 10, height: 10, background: `var(--${p.kind === "danger" ? "danger" : p.kind === "warn" ? "warn" : p.kind === "ok" ? "ok" : "text-faint"})`, borderRadius: "50%", margin: "4px auto 0", boxShadow: "0 0 8px currentColor" }} />
          </div>
        ))}
        <div style={{ position: "absolute", left: 16, bottom: 16, fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-dim)", letterSpacing: "0.1em" }}>
          LIVE FLEET · {pins.length} ACTIVE · UPDATED 13:02:18
        </div>
      </div>
      <aside className="inspector">
        <div style={{ padding: 14, borderBottom: "1px solid var(--line)" }}>
          <div className="h-rule">SELECTED</div>
          <div style={{ marginTop: 10 }}>
            <div style={{ fontSize: 14, fontWeight: 600 }}>C. Mendez · KW-48217</div>
            <div className="mono dim" style={{ fontSize: 11 }}>Hidalgo Logistics · I-35 N</div>
            <div style={{ marginTop: 8 }}><Chip kind="danger" pulse>● ON CALL · 00:42</Chip></div>
          </div>
        </div>
        <div style={{ padding: 14, borderBottom: "1px solid var(--line)" }}>
          <div className="h-rule">CLUSTER · MIDWEST</div>
          <div style={{ fontSize: 12, lineHeight: 1.8, marginTop: 6 }}>
            <div className="row"><span className="chip ok"><span className="dot" /> ON TRACK</span><span className="mono">4 drivers</span></div>
            <div className="row"><span className="chip warn"><span className="dot" /> DELAYED</span><span className="mono">2 drivers</span></div>
            <div className="row"><span className="chip danger"><span className="dot pulse" /> AT RISK</span><span className="mono">1 driver</span></div>
          </div>
        </div>
        <div style={{ padding: 14 }}>
          <div className="h-rule">SCHEDULED CALLS</div>
          <div style={{ marginTop: 8, fontSize: 12, display: "flex", flexDirection: "column", gap: 6 }}>
            <ScheduledRow t="13:14" who="R. Singh" reason="ETA confirm" />
            <ScheduledRow t="13:30" who="A. Kowalski" reason="Mechanical follow-up" />
            <ScheduledRow t="14:30" who="L. Brown" reason="Voicemail retry" />
            <ScheduledRow t="15:00" who="A. Patel" reason="Pre-pickup" />
            <ScheduledRow t="16:15" who="S. Iqbal" reason="Overnight check" />
          </div>
        </div>
      </aside>
    </div>
  );
}

function ScheduledRow({ t, who, reason }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "40px 1fr", gap: 8, padding: "4px 6px", borderRadius: 3 }}>
      <span className="mono accent" style={{ color: "var(--accent)" }}>{t}</span>
      <span>{who} <span className="dim">· {reason}</span></span>
    </div>
  );
}

/* ─────────── VARIANT 4 — Inbox / thread style ─────────── */
function CallsThread() {
  const threads = [
    { driver: "Carlos Mendez", carrier: "Hidalgo Logistics", load: "KW-48217", last: "13:02", preview: "Yeah, that'd help. Can you text my dispatcher too?", unread: 1, live: true },
    { driver: "Ravi Singh", carrier: "BluePeak Carriers", load: "KW-48216", last: "11:48", preview: "Should hit Chicago around 21:14, give or take 20 min.", unread: 0 },
    { driver: "T. Petrov", carrier: "Wasatch Lines", load: "KW-48211", last: "10:22", preview: "Yeah everything's smooth. KC by 22:00 no problem.", unread: 0 },
    { driver: "J. Reyes", carrier: "Pinecone Hauling", load: "KW-48210", last: "09:54", preview: "Shipper kept me 90 minutes. Reno's gonna be late.", unread: 2, warn: true },
    { driver: "M. Garcia", carrier: "Gulf Trans", load: "KW-48212", last: "Yesterday", preview: "POD photo coming through now.", unread: 0 },
    { driver: "A. Kowalski", carrier: "Apex Lines", load: "KW-48205", last: "08:11", preview: "DEF light just came on, pulling into TA.", unread: 1, warn: true },
  ];
  return (
    <div style={{ display: "grid", gridTemplateColumns: "320px 1fr", minHeight: 600 }}>
      <div style={{ borderRight: "1px solid var(--line)" }}>
        <div style={{ padding: "10px 14px", borderBottom: "1px solid var(--line)", display: "flex", gap: 8 }}>
          <input className="cmdk" style={{ margin: 0, flex: 1 }} placeholder="Search threads" />
        </div>
        {threads.map((th, i) => (
          <div key={i} style={{
            padding: "10px 14px",
            borderBottom: "1px solid var(--line)",
            background: i === 0 ? "var(--bg-sel)" : "transparent",
            borderLeft: i === 0 ? "2px solid var(--accent)" : "2px solid transparent",
            cursor: "pointer",
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
              <Av name={th.driver} />
              <span style={{ fontWeight: 600, fontSize: 12 }}>{th.driver}</span>
              {th.live && <Chip kind="danger" pulse>LIVE</Chip>}
              {th.warn && !th.live && <Chip kind="warn">FLAG</Chip>}
              <span className="mono dim" style={{ fontSize: 10, marginLeft: "auto" }}>{th.last}</span>
            </div>
            <div className="mono dim" style={{ fontSize: 10, marginBottom: 2 }}>{th.carrier} · {th.load}</div>
            <div style={{ fontSize: 11, color: "var(--text-mid)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{th.preview}</div>
          </div>
        ))}
      </div>
      <div style={{ display: "flex", flexDirection: "column" }}>
        <div style={{ padding: 14, borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 10 }}>
          <Av name="Carlos Mendez" />
          <div>
            <div style={{ fontWeight: 600 }}>Carlos Mendez</div>
            <div className="mono dim" style={{ fontSize: 11 }}>Hidalgo Logistics · 4 calls past 30d · 96% pickup rate</div>
          </div>
          <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
            <button className="btn ghost sm">Profile</button>
            <button className="btn sm">SMS</button>
            <button className="btn primary sm"><Ic.phone style={{ width: 10, height: 10 }} /> Call</button>
          </div>
        </div>
        <div className="transcript" style={{ padding: 20, flex: 1, overflowY: "auto" }}>
          <ThreadDay label="TODAY · 05/25" />
          <ThreadBubble who="ai" t="13:02:00">Calling about Walmart load KW-48217. Where are you and what's your ETA?</ThreadBubble>
          <ThreadBubble who="driver" t="13:02:11">North of San Antonio on 35. Fuel stop and scale backup slowed me down.</ThreadBubble>
          <ThreadBubble who="ai" t="13:02:19">~660 miles out. Running team or solo?</ThreadBubble>
          <ThreadBubble who="driver" t="13:02:25">Solo. Breaking in Dallas tonight.</ThreadBubble>
          <ThreadBubble who="ai" t="13:02:32">Delivery ~20:00 tomorrow — 2h past appt. Want me to push the slot?</ThreadBubble>
          <ThreadBubble who="driver" t="13:02:39" live>Yeah that'd help. Can you text my dispatcher too?</ThreadBubble>
          <ThreadDay label="YESTERDAY · 05/24" />
          <ThreadBubble who="ai" t="09:42">Hidalgo accepted KW-48217 at $2,450. Pre-pickup call scheduled 05/25 06:00.</ThreadBubble>
        </div>
        <div style={{ borderTop: "1px solid var(--line)", padding: 12, display: "flex", gap: 8 }}>
          <input className="cmdk" style={{ margin: 0, flex: 1 }} placeholder="Type to AI agent or compose SMS…" />
          <button className="btn ghost">SMS</button>
          <button className="btn primary"><Ic.phone style={{ width: 12, height: 12 }} /> Call back</button>
        </div>
      </div>
    </div>
  );
}

function ThreadDay({ label }) {
  return <div style={{ display: "flex", alignItems: "center", gap: 10, fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.14em", color: "var(--text-dim)", margin: "12px 0 6px" }}>{label}<span style={{ flex: 1, height: 1, background: "var(--line)" }} /></div>;
}
function ThreadBubble({ who, t, live, children }) {
  const isAi = who === "ai";
  return (
    <div style={{ display: "flex", justifyContent: isAi ? "flex-start" : "flex-end", marginBottom: 6 }}>
      <div style={{
        maxWidth: "70%",
        padding: "8px 12px",
        background: isAi ? "var(--bg-2)" : "var(--accent-bg)",
        border: `1px solid ${isAi ? "var(--line)" : "var(--accent)"}`,
        borderRadius: 8,
        fontSize: 12,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.12em", color: isAi ? "var(--accent)" : "var(--blue)", marginBottom: 2 }}>
          <span>{isAi ? "KEELWAY AI" : "C. MENDEZ"}</span>
          <span className="faint">{t}</span>
          {live && <Chip kind="danger" pulse>SPEAKING</Chip>}
        </div>
        <div>{children}</div>
      </div>
    </div>
  );
}

window.CheckCalls = CheckCalls;
