/* global React, Ic, Chip, Sparkline, ScoreBar, KPI, Panel, Av */

function Dispatch() {
  const trucks = [
    { id: "KW-48217", driver: "C. Mendez",  carrier: "Hidalgo",   x: 18, y: 60, status: "atrisk",   eta: "+1h42", note: "ON CALL · DETENTION RISK" },
    { id: "KW-48216", driver: "R. Singh",   carrier: "BluePeak",  x: 38, y: 35, status: "moving",   eta: "21:14", note: "I-65 N, 312mi out" },
    { id: "KW-48211", driver: "T. Petrov",  carrier: "Wasatch",   x: 50, y: 48, status: "moving",   eta: "22:00", note: "On schedule" },
    { id: "KW-48207", driver: "K. Walker",  carrier: "Heartland", x: 60, y: 40, status: "arrived",  eta: "DOCK",  note: "Meijer #4" },
    { id: "KW-48210", driver: "J. Reyes",   carrier: "Pinecone",  x: 14, y: 24, status: "delayed",  eta: "+0h45", note: "Shipper holding" },
    { id: "KW-48212", driver: "M. Garcia",  carrier: "Gulf Trans",x: 70, y: 72, status: "delivered",eta: "DONE",  note: "POD captured" },
    { id: "KW-48209", driver: "L. Brown",   carrier: "Eastern",   x: 78, y: 36, status: "moving",   eta: "tmrw 12:00", note: "I-95 N" },
    { id: "KW-48205", driver: "A. Kowalski",carrier: "Apex",      x: 68, y: 46, status: "warning",  eta: "delayed", note: "DEF warning · TA stop" },
    { id: "KW-48208", driver: "—",          carrier: "—",         x: 42, y: 22, status: "open",     eta: "—",     note: "Posted DAT @ $1.85" },
  ];
  const statusColor = (s) => ({ atrisk: "var(--danger)", moving: "var(--blue)", arrived: "var(--ok)", delayed: "var(--warn)", delivered: "var(--text-dim)", warning: "var(--warn)", open: "var(--accent)" }[s]);
  const [sel, setSel] = React.useState(trucks[0]);

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Dispatch & Tracking</div>
          <div className="page-sub">147 active · 38 in transit · 6 at risk · auto-checked every 2h</div>
        </div>
        <div className="page-actions">
          <span className="chip ok"><span className="dot pulse" /> GPS LIVE · 312 PINGS/MIN</span>
          <div className="toggle-row">
            <button className="on">MAP</button><button>TIMELINE</button><button>GANTT</button>
          </div>
          <button className="btn"><Ic.bot style={{ width: 12, height: 12 }} /> Re-route AI</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 380px", minHeight: 640 }}>
        <div className="mapbg" style={{ position: "relative", overflow: "hidden" }}>
          <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" />
            {/* lane traces */}
            <path d="M18,60 Q30,55 38,35" stroke="var(--blue)" strokeWidth="0.3" fill="none" strokeDasharray="1 1" opacity="0.6" />
            <path d="M14,24 Q30,30 50,48" stroke="var(--warn)" strokeWidth="0.3" fill="none" strokeDasharray="1 1" opacity="0.6" />
            <path d="M70,72 Q80,55 78,36" stroke="var(--text-dim)" strokeWidth="0.3" fill="none" strokeDasharray="1 1" opacity="0.4" />
          </svg>

          {trucks.map(t => (
            <div key={t.id} onClick={() => setSel(t)} style={{
              position: "absolute",
              left: `${t.x}%`, top: `${t.y}%`,
              transform: "translate(-50%, -50%)",
              cursor: "pointer",
            }}>
              <div style={{
                width: 16, height: 16, background: statusColor(t.status),
                borderRadius: t.status === "open" ? 2 : "50%",
                boxShadow: `0 0 0 ${sel.id === t.id ? 8 : 0}px rgba(45,212,191,0.2), 0 0 12px ${statusColor(t.status)}`,
                border: "2px solid var(--bg-0)",
              }} />
              {(t.status === "atrisk" || sel.id === t.id) && (
                <div style={{
                  position: "absolute", left: 16, top: -6, whiteSpace: "nowrap",
                  background: "var(--bg-1)", border: `1px solid ${statusColor(t.status)}`,
                  padding: "3px 7px", borderRadius: 3, fontSize: 10,
                  fontFamily: "var(--font-mono)",
                }}>
                  {t.driver} · {t.id}
                </div>
              )}
            </div>
          ))}

          {/* legend */}
          <div style={{ position: "absolute", left: 16, bottom: 16, background: "rgba(14,24,34,0.85)", border: "1px solid var(--line)", padding: 10, borderRadius: 4, fontSize: 11, lineHeight: 1.8 }}>
            <div className="h-rule" style={{ marginBottom: 4 }}>FLEET STATUS</div>
            <div><span style={{ display: "inline-block", width: 8, height: 8, background: "var(--blue)", borderRadius: "50%", marginRight: 8 }} /> Moving · 4</div>
            <div><span style={{ display: "inline-block", width: 8, height: 8, background: "var(--ok)", borderRadius: "50%", marginRight: 8 }} /> Arrived · 1</div>
            <div><span style={{ display: "inline-block", width: 8, height: 8, background: "var(--warn)", borderRadius: "50%", marginRight: 8 }} /> Delayed/Warn · 2</div>
            <div><span style={{ display: "inline-block", width: 8, height: 8, background: "var(--danger)", borderRadius: "50%", marginRight: 8 }} /> At risk · 1</div>
            <div><span style={{ display: "inline-block", width: 8, height: 8, background: "var(--accent)", borderRadius: 1, marginRight: 8 }} /> Open · 1</div>
          </div>
        </div>

        <aside className="inspector">
          <div style={{ padding: 14, borderBottom: "1px solid var(--line)" }}>
            <div className="h-rule">SELECTED · {sel.id}</div>
            <div style={{ marginTop: 10 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <Av name={sel.driver === "—" ? "Open" : sel.driver} />
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>{sel.driver === "—" ? "Unassigned" : sel.driver}</div>
                  <div className="mono dim" style={{ fontSize: 10 }}>{sel.carrier} · {sel.note}</div>
                </div>
              </div>
            </div>
          </div>

          <div style={{ padding: 14, borderBottom: "1px solid var(--line)" }}>
            <div className="h-rule">TIMELINE</div>
            <div style={{ marginTop: 8, fontSize: 12, display: "flex", flexDirection: "column", gap: 4 }}>
              <Tl t="06:14" what="Arrived Laredo" ok />
              <Tl t="08:31" what="Loaded · BOL OK" ok />
              <Tl t="09:48" what="GPS ping · Cotulla TX" />
              <Tl t="12:48" what="No GPS · 4h12m" warn />
              <Tl t="13:02" what="AI check-call started" live />
              <Tl t="13:02:42" what="ETA pushed to 20:00" />
              <Tl t="—" what="Memphis dock @ 18:00" dim />
            </div>
          </div>

          <div style={{ padding: 14, borderBottom: "1px solid var(--line)" }}>
            <div className="h-rule">HOS / COMPLIANCE</div>
            <div style={{ marginTop: 10, fontSize: 11, lineHeight: 1.8 }}>
              <HosBar label="Drive" used={3} total={11} />
              <HosBar label="On-duty" used={5.5} total={14} />
              <HosBar label="Cycle (70h)" used={42} total={70} />
              <HosBar label="Break (8/2)" used={6.2} total={8} note="break needed in 1h48m" />
            </div>
          </div>

          <div style={{ padding: 14 }}>
            <div className="h-rule">QUICK ACTIONS</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6, marginTop: 10 }}>
              <button className="btn ghost sm"><Ic.phone style={{ width: 10, height: 10 }} /> Call driver</button>
              <button className="btn ghost sm">SMS</button>
              <button className="btn ghost sm">Send POD link</button>
              <button className="btn ghost sm">Email shipper</button>
              <button className="btn sm" style={{ gridColumn: "span 2", background: "var(--accent)", color: "#051A19" }}>Hand off to AI agent</button>
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

function Tl({ t, what, ok, warn, live, dim }) {
  const c = ok ? "var(--ok)" : warn ? "var(--warn)" : live ? "var(--danger)" : dim ? "var(--text-faint)" : "var(--text-mid)";
  return (
    <div style={{ display: "grid", gridTemplateColumns: "12px 70px 1fr", gap: 8, alignItems: "center" }}>
      <span style={{ color: c, fontSize: 9 }}>●</span>
      <span className="mono dim" style={{ fontSize: 10 }}>{t}</span>
      <span style={{ color: dim ? "var(--text-dim)" : "var(--text)" }}>{what}{live && <Chip kind="danger" pulse>LIVE</Chip>}</span>
    </div>
  );
}

function HosBar({ label, used, total, note }) {
  const pct = (used / total) * 100;
  const color = pct > 80 ? "var(--warn)" : "var(--accent)";
  return (
    <div style={{ marginBottom: 6 }}>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 2 }}>
        <span>{label}</span>
        <span className="mono dim">{used}h / {total}h</span>
      </div>
      <div style={{ height: 4, background: "var(--bg-3)", borderRadius: 2 }}>
        <div style={{ width: `${pct}%`, height: "100%", background: color, borderRadius: 2 }} />
      </div>
      {note && <div className="mono dim" style={{ fontSize: 9, marginTop: 2 }}>{note}</div>}
    </div>
  );
}

window.Dispatch = Dispatch;
