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

const LB_TABS = [
  { id: "all",      label: "All",          count: 147 },
  { id: "covered",  label: "Covered",      count: 84 },
  { id: "available",label: "Available",    count: 47 },
  { id: "intransit",label: "In Transit",   count: 38 },
  { id: "atrisk",   label: "At Risk",      count: 6,  kind: "danger" },
  { id: "delivered",label: "Delivered",    count: 16 },
];

const LB_LOADS = [
  { id: "KW-48217", status: "ATRISK",    pu: "Laredo, TX",       de: "Memphis, TN",     pickup: "05/25 08:00", deliver: "05/26 18:00", miles: 943,  rev: 2980, cost: 2450, gm: 530, gmPct: 17.8, carrier: "Hidalgo Logistics", driver: "C. Mendez", equip: "53' Dry", weight: 42100, customer: "Walmart DC", agent: "Maya O.", aiNote: "Driver hasn't checked in 4h. Calling now…", aiAction: "CALLING", priority: "high" },
  { id: "KW-48216", status: "INTRANSIT", pu: "Atlanta, GA",      de: "Chicago, IL",     pickup: "05/24 14:30", deliver: "05/25 22:00", miles: 717,  rev: 2200, cost: 1850, gm: 350, gmPct: 15.9, carrier: "BluePeak Carriers",  driver: "R. Singh",  equip: "53' Dry", weight: 38450, customer: "Home Depot",  agent: "Maya O.", aiNote: "ETA confirmed via auto-call · 21:14 CT", aiAction: "CONFIRMED" },
  { id: "KW-48215", status: "COVERED",   pu: "Long Beach, CA",   de: "Phoenix, AZ",     pickup: "05/25 10:00", deliver: "05/26 06:00", miles: 372,  rev: 1450, cost: 1140, gm: 310, gmPct: 21.4, carrier: "Coastal Freight",    driver: "—",         equip: "Reefer",  weight: 41200, customer: "Sprouts",     agent: "D. Patel",aiNote: "Rate cons sent · awaiting signature", aiAction: "WAITING" },
  { id: "KW-48214", status: "OFFERED",   pu: "Dallas, TX",       de: "Newark, NJ",      pickup: "05/26 06:00", deliver: "05/28 14:00", miles: 1547, rev: 3850, cost: 3150, gm: 700, gmPct: 18.2, carrier: "—",                  driver: "—",         equip: "53' Dry", weight: 36800, customer: "Target DC",   agent: "Maya O.", aiNote: "6 carriers contacted · 2 bids in", aiAction: "BIDDING", isAI: true },
  { id: "KW-48213", status: "AVAILABLE", pu: "Seattle, WA",      de: "Denver, CO",      pickup: "05/26 09:00", deliver: "05/27 18:00", miles: 1320, rev: 2940, cost: 2380, gm: 560, gmPct: 19.0, carrier: "—",                  driver: "—",         equip: "53' Dry", weight: 31200, customer: "Costco",       agent: "Maya O.", aiNote: "Suggested: Western Mtn (98% match)", aiAction: "SUGGEST" },
  { id: "KW-48212", status: "DELIVERED", pu: "Houston, TX",      de: "Tampa, FL",       pickup: "05/22 11:00", deliver: "05/24 09:00", miles: 956,  rev: 2480, cost: 2010, gm: 470, gmPct: 18.9, carrier: "Gulf Trans",          driver: "M. Garcia", equip: "Reefer",  weight: 39800, customer: "Publix",       agent: "D. Patel",aiNote: "POD captured · invoiced 05/24 11:14", aiAction: "DONE" },
  { id: "KW-48211", status: "INTRANSIT", pu: "Salt Lake City, UT",de:"Kansas City, MO", pickup: "05/24 06:00", deliver: "05/25 22:00", miles: 1080, rev: 2780, cost: 2310, gm: 470, gmPct: 16.9, carrier: "Wasatch Lines",       driver: "T. Petrov", equip: "53' Dry", weight: 40050, customer: "FedEx Freight",agent: "Maya O.", aiNote: "On-time · 312 mi remaining", aiAction: "OK" },
  { id: "KW-48210", status: "ATRISK",    pu: "Portland, OR",     de: "Reno, NV",        pickup: "05/25 13:00", deliver: "05/26 02:00", miles: 565,  rev: 1650, cost: 1450, gm: 200, gmPct: 12.1, carrier: "Pinecone Hauling",    driver: "J. Reyes",  equip: "53' Dry", weight: 33400, customer: "Raley's",      agent: "D. Patel",aiNote: "Detention risk · shipper running 90min late", aiAction: "WARN" },
  { id: "KW-48209", status: "COVERED",   pu: "Charlotte, NC",    de: "Boston, MA",      pickup: "05/26 04:00", deliver: "05/27 12:00", miles: 850,  rev: 2380, cost: 1980, gm: 400, gmPct: 16.8, carrier: "Eastern Star",        driver: "L. Brown",  equip: "53' Dry", weight: 37500, customer: "Stop & Shop",  agent: "S. Lee",  aiNote: "Booked via AI offer · saved $180", aiAction: "BOOKED" },
  { id: "KW-48208", status: "AVAILABLE", pu: "Minneapolis, MN",  de: "St Louis, MO",    pickup: "05/26 14:00", deliver: "05/27 09:00", miles: 555,  rev: 1480, cost: 1200, gm: 280, gmPct: 18.9, carrier: "—",                  driver: "—",         equip: "53' Dry", weight: 28900, customer: "Schnucks",     agent: "Maya O.", aiNote: "Posting to DAT in 2min @ $1.85/mi target", aiAction: "POSTING" },
  { id: "KW-48207", status: "INTRANSIT", pu: "Indianapolis, IN", de: "Detroit, MI",     pickup: "05/24 19:00", deliver: "05/25 13:00", miles: 290,  rev: 940,  cost: 760,  gm: 180, gmPct: 19.1, carrier: "Heartland Hauling",   driver: "K. Walker", equip: "53' Dry", weight: 26100, customer: "Meijer",       agent: "S. Lee",  aiNote: "ETA shifted +18min · within tolerance", aiAction: "OK" },
];

const STATUS_CHIPS = {
  ATRISK:    { kind: "danger",  label: "AT RISK",   pulse: true },
  INTRANSIT: { kind: "info",    label: "IN TRANSIT" },
  COVERED:   { kind: "accent",  label: "COVERED" },
  OFFERED:   { kind: "magenta", label: "AI OFFERING", pulse: true },
  AVAILABLE: { kind: "warn",    label: "AVAILABLE" },
  DELIVERED: { kind: "ok",      label: "DELIVERED" },
};

const AI_ACTION_CHIPS = {
  CALLING:   { kind: "danger", pulse: true,  label: "AI CALLING" },
  CONFIRMED: { kind: "ok",     label: "CONFIRMED" },
  WAITING:   { kind: "warn",   label: "AWAITING SIG" },
  BIDDING:   { kind: "accent", pulse: true,  label: "BIDDING" },
  SUGGEST:   { kind: "accent", label: "AI SUGGEST" },
  POSTING:   { kind: "info",   label: "POSTING" },
  WARN:      { kind: "warn",   pulse: true,  label: "DETENTION RISK" },
  BOOKED:    { kind: "ok",     label: "BOOKED BY AI" },
  OK:        { kind: "ok",     label: "ON TRACK" },
  DONE:      { kind: "",       label: "ARCHIVED" },
};

function LoadBoard() {
  const [tab, setTab] = React.useState("all");
  const [sel, setSel] = React.useState("KW-48214");
  const selected = LB_LOADS.find(l => l.id === sel);

  const visible = LB_LOADS.filter(l => {
    if (tab === "all") return true;
    if (tab === "covered") return l.status === "COVERED" || l.status === "OFFERED";
    if (tab === "available") return l.status === "AVAILABLE";
    if (tab === "intransit") return l.status === "INTRANSIT";
    if (tab === "atrisk") return l.status === "ATRISK";
    if (tab === "delivered") return l.status === "DELIVERED";
    return true;
  });

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Load Board</div>
          <div className="page-sub">147 loads · Today 05/25 · Maya Ortiz / Nashville</div>
        </div>
        <div className="page-actions">
          <span className="chip accent"><span className="dot pulse" /> 6 AGENTS ONLINE</span>
          <button className="btn ghost"><Ic.filter style={{ width: 12, height: 12 }} /> Filter</button>
          <button className="btn"><Ic.bot style={{ width: 12, height: 12 }} /> Ask Keelway</button>
          <button className="btn primary"><Ic.plus style={{ width: 12, height: 12 }} /> New Load</button>
        </div>
      </div>

      {/* KPI strip */}
      <div className="grid cols-4 pad" style={{ paddingBottom: 0 }}>
        <KPI label="Open / Active" value="147" delta="12" spark={[8,10,9,11,12,11,13,15,14,16,17,15]} />
        <KPI label="Today GM" value="$48,210" delta="6.2%" spark={[20,22,24,23,28,30,32,35,38,40,44,48]} />
        <KPI label="Avg Margin" value="17.3%" delta="0.4pt" spark={[14,15,15,16,16,17,17,17,18,17,18,17]} />
        <KPI label="At-Risk Loads" value="6" delta="2" deltaKind="down" spark={[3,4,5,4,6,5,7,8,7,6,7,6]} />
      </div>

      {/* Tabs */}
      <div className="tabs" style={{ marginTop: 16 }}>
        {LB_TABS.map(t => (
          <div key={t.id} className={`tab ${tab === t.id ? "active" : ""}`} onClick={() => setTab(t.id)}>
            {t.label} <span className="count" style={t.kind === "danger" ? { color: "var(--danger)", background: "var(--danger-bg)" } : {}}>{t.count}</span>
          </div>
        ))}
        <div style={{ marginLeft: "auto", display: "flex", gap: 8, alignItems: "center", padding: "4px 0" }}>
          <div className="toggle-row">
            <button className="on">TABLE</button>
            <button>BOARD</button>
            <button>MAP</button>
          </div>
        </div>
      </div>

      {/* Inline AI strip */}
      <AiBand
        confidence={94}
        text={<><b>Keelway</b> sees <b>3 backhaul opportunities</b> for in-transit loads ending in TX, OH and CA. Recovers ~$1,840 GM.</>}
        actions={<>
          <button className="btn ghost sm">Review</button>
          <button className="btn primary sm">Accept all</button>
        </>}
      />

      {/* Split: table + inspector */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 360px", minHeight: 540 }}>
        <div style={{ overflowX: "auto" }}>
          <table className="tbl">
            <thead>
              <tr>
                <th>Status</th>
                <th>Load #</th>
                <th>Pickup → Delivery</th>
                <th>Schedule</th>
                <th>Carrier / Driver</th>
                <th>Equip</th>
                <th className="num">Miles</th>
                <th className="num">Rev</th>
                <th className="num">Cost</th>
                <th className="num">GM</th>
                <th className="num">GM %</th>
                <th>AI Activity</th>
              </tr>
            </thead>
            <tbody>
              {visible.map(l => {
                const s = STATUS_CHIPS[l.status];
                const a = AI_ACTION_CHIPS[l.aiAction];
                return (
                  <tr key={l.id} className={`${sel === l.id ? "selected" : ""} ${l.isAI ? "ai-row" : ""}`} onClick={() => setSel(l.id)}>
                    <td><Chip kind={s.kind} pulse={s.pulse}>{s.label}</Chip></td>
                    <td className="mono">{l.id}</td>
                    <td>
                      <span>{l.pu}</span>
                      <span className="faint" style={{ margin: "0 6px" }}>→</span>
                      <span>{l.de}</span>
                    </td>
                    <td className="mono dim" style={{ fontSize: 11 }}>{l.pickup}<br/>{l.deliver}</td>
                    <td>
                      {l.carrier === "—" ? <span className="faint">— unassigned —</span> : (
                        <div style={{ display: "flex", flexDirection: "column", gap: 1 }}>
                          <span>{l.carrier}</span>
                          <span className="mono dim" style={{ fontSize: 10 }}>{l.driver}</span>
                        </div>
                      )}
                    </td>
                    <td className="mono dim" style={{ fontSize: 11 }}>{l.equip}</td>
                    <td className="num">{l.miles.toLocaleString()}</td>
                    <td className="num">${l.rev.toLocaleString()}</td>
                    <td className="num dim">${l.cost.toLocaleString()}</td>
                    <td className="num" style={{ color: l.gmPct < 15 ? "var(--warn)" : "var(--text)" }}>${l.gm}</td>
                    <td className="num">
                      <span style={{ color: l.gmPct < 15 ? "var(--warn)" : l.gmPct > 19 ? "var(--ok)" : "var(--text)" }}>{l.gmPct}%</span>
                    </td>
                    <td>
                      <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                        <Chip kind={a.kind} pulse={a.pulse}>{a.label}</Chip>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {/* Inspector */}
        <aside className="inspector">
          {selected && <LoadInspector load={selected} />}
        </aside>
      </div>
    </div>
  );
}

function LoadInspector({ load }) {
  const s = STATUS_CHIPS[load.status];
  return (
    <div>
      <div style={{ padding: "14px 16px", borderBottom: "1px solid var(--line)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <Chip kind={s.kind} pulse={s.pulse}>{s.label}</Chip>
          <span className="mono dim" style={{ fontSize: 11 }}>{load.id}</span>
          <button className="btn ghost sm" style={{ marginLeft: "auto" }}><Ic.more style={{ width: 12, height: 12 }} /></button>
        </div>
        <div style={{ marginTop: 10, fontSize: 14, fontWeight: 600 }}>
          {load.pu}
          <span className="faint" style={{ margin: "0 8px" }}>→</span>
          {load.de}
        </div>
        <div className="mono dim" style={{ fontSize: 11, marginTop: 4 }}>
          {load.customer} · {load.equip} · {load.weight.toLocaleString()} lbs · {load.miles.toLocaleString()} mi
        </div>
      </div>

      <div style={{ padding: 14, display: "flex", flexDirection: "column", gap: 12 }}>
        <div>
          <div className="h-rule">FINANCIALS</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, marginTop: 8 }}>
            <div><div className="kpi-label">REVENUE</div><div className="mono" style={{ fontSize: 16 }}>${load.rev.toLocaleString()}</div></div>
            <div><div className="kpi-label">COST</div><div className="mono dim" style={{ fontSize: 16 }}>${load.cost.toLocaleString()}</div></div>
            <div><div className="kpi-label">GM</div><div className="mono up" style={{ fontSize: 16 }}>${load.gm} · {load.gmPct}%</div></div>
          </div>
        </div>

        <div>
          <div className="h-rule">TIMELINE</div>
          <div style={{ marginTop: 8, display: "flex", flexDirection: "column", gap: 6, fontSize: 12 }}>
            <TimelineRow icon="●" color="var(--ok)" t="05/24 09:12" who="Maya O." what="Load tendered by Walmart EDI 204" />
            <TimelineRow icon="◆" color="var(--accent)" t="05/24 09:13" who="Keelway AI" what="Rate target set $2,980 — 18% GM (DAT median $2,790)" />
            <TimelineRow icon="◆" color="var(--accent)" t="05/24 09:42" who="Keelway AI" what="Booked Hidalgo Logistics @ $2,450 — saved $128 vs target" />
            <TimelineRow icon="●" color="var(--ok)" t="05/25 06:14" who="Driver" what="Arrived Laredo · checked in" />
            <TimelineRow icon="●" color="var(--ok)" t="05/25 08:31" who="Driver" what="Loaded · BOL received" />
            <TimelineRow icon="◇" color="var(--warn)" t="05/25 12:48" who="Keelway AI" what="No GPS update for 4h12m — initiating check call" />
            <TimelineRow live icon="◆" color="var(--danger)" t="05/25 13:02" who="Keelway AI" what="Calling driver C. Mendez · 30s on call" />
          </div>
        </div>

        <div>
          <div className="h-rule">AI ACTIONS QUEUED</div>
          <div style={{ marginTop: 8, display: "flex", flexDirection: "column", gap: 6 }}>
            <ActionRow text="Send detention threat email to Walmart receiver" conf={86} />
            <ActionRow text="Pre-book Atlanta backhaul (KW-48292) for this truck" conf={71} />
            <ActionRow text="Update ETA in shipper portal: 05/26 19:30 → 22:00" conf={98} />
          </div>
        </div>

        <div style={{ display: "flex", gap: 6, marginTop: 4 }}>
          <button className="btn ghost" style={{ flex: 1 }}>View full</button>
          <button className="btn primary" style={{ flex: 1 }}>Approve all (3)</button>
        </div>
      </div>
    </div>
  );
}

function TimelineRow({ icon, color, t, who, what, live }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "12px 70px 1fr", gap: 8, alignItems: "start" }}>
      <span style={{ color, fontSize: 10, paddingTop: 2 }}>{icon}</span>
      <span className="mono dim" style={{ fontSize: 10 }}>{t.split(" ")[1]}</span>
      <span><span className="dim" style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.1em", fontFamily: "var(--font-mono)" }}>{who}</span><br/>{what}{live && <span className="chip danger" style={{ marginLeft: 6, fontSize: 9 }}><span className="dot pulse" /> LIVE</span>}</span>
    </div>
  );
}

function ActionRow({ text, conf }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "6px 8px", background: "var(--bg-2)", border: "1px solid var(--line)", borderRadius: 4, fontSize: 12 }}>
      <span style={{ flex: 1 }}>{text}</span>
      <span className="mono dim" style={{ fontSize: 10 }}>{conf}%</span>
      <button className="btn ghost sm" style={{ padding: "0 6px" }}>✕</button>
      <button className="btn sm" style={{ padding: "0 6px", background: "var(--accent)", color: "#051A19" }}>✓</button>
    </div>
  );
}

window.LoadBoard = LoadBoard;
