/* global React, Ic, Chip, KPI, Panel, AiBand, ScoreBar */

function Compliance() {
  const [tab, setTab] = React.useState("hos");
  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Compliance & Safety</div>
          <div className="page-sub">HOS · ELD · CSA · Insurance · Audit Log — Samsara + Motive synced</div>
        </div>
        <div className="page-actions">
          <span className="chip ok"><span className="dot" /> ELD SYNCED 13:01</span>
          <button className="btn ghost">Audit log</button>
          <button className="btn primary">Export DOT</button>
        </div>
      </div>

      <div className="grid cols-4 pad" style={{ paddingBottom: 0 }}>
        <KPI label="Active Drivers (ELD)" value="184" delta="all green" />
        <KPI label="HOS Violations 30d" value="0" delta="↓ from 4" />
        <KPI label="COI Expiring 30d" value="6" delta="2 critical" />
        <KPI label="CSA Issues" value="2" delta="1 unsafe driving" />
      </div>

      <div className="tabs" style={{ marginTop: 16 }}>
        <div className={`tab ${tab === "hos" ? "active" : ""}`} onClick={() => setTab("hos")}>HOS / ELD <span className="count">184</span></div>
        <div className={`tab ${tab === "csa" ? "active" : ""}`} onClick={() => setTab("csa")}>CSA / SAFER</div>
        <div className={`tab ${tab === "ins" ? "active" : ""}`} onClick={() => setTab("ins")}>Insurance / COI <span className="count">6</span></div>
        <div className={`tab ${tab === "audit" ? "active" : ""}`} onClick={() => setTab("audit")}>Audit Log</div>
      </div>

      {tab === "hos" && <HosView />}
      {tab === "csa" && <CsaView />}
      {tab === "ins" && <InsView />}
      {tab === "audit" && <AuditView />}
    </div>
  );
}

function HosView() {
  const drivers = [
    { name: "C. Mendez",   carrier: "Hidalgo",     drive: 3.0,  duty: 5.5,  cycle: 42, status: "ok",   note: "8/2 break in 1h48m" },
    { name: "R. Singh",    carrier: "BluePeak",    drive: 8.4,  duty: 11.2, cycle: 58, status: "warn", note: "Approaching 11h drive" },
    { name: "T. Petrov",   carrier: "Wasatch",     drive: 6.2,  duty: 9.4,  cycle: 38, status: "ok",   note: "On schedule" },
    { name: "K. Walker",   carrier: "Heartland",   drive: 4.8,  duty: 7.2,  cycle: 28, status: "ok",   note: "At dock" },
    { name: "J. Reyes",    carrier: "Pinecone",    drive: 9.2,  duty: 12.4, cycle: 62, status: "warn", note: "Must break in 1h" },
    { name: "M. Garcia",   carrier: "Gulf Trans",  drive: 0,    duty: 0,    cycle: 18, status: "ok",   note: "Off duty" },
    { name: "L. Brown",    carrier: "Eastern",     drive: 5.4,  duty: 8.2,  cycle: 44, status: "ok",   note: "On schedule" },
    { name: "A. Kowalski", carrier: "Apex",        drive: 4.0,  duty: 6.4,  cycle: 36, status: "warn", note: "Mechanical hold · DEF" },
  ];
  return (
    <div style={{ padding: 16 }}>
      <Panel title="LIVE HOS · ELD-CONNECTED DRIVERS" actions={<span className="mono dim" style={{ fontSize: 10 }}>SAMSARA · MOTIVE · KEEPTRUCKIN · GEOTAB</span>}>
        <table className="tbl">
          <thead>
            <tr><th>Driver</th><th>Carrier</th><th>Drive (11h)</th><th>On-Duty (14h)</th><th>Cycle (70h)</th><th>Status</th><th>AI Note</th></tr>
          </thead>
          <tbody>
            {drivers.map((d, i) => (
              <tr key={i}>
                <td>{d.name}</td>
                <td className="dim">{d.carrier}</td>
                <td style={{ minWidth: 120 }}><HosCell used={d.drive} total={11} /></td>
                <td style={{ minWidth: 120 }}><HosCell used={d.duty} total={14} /></td>
                <td style={{ minWidth: 120 }}><HosCell used={d.cycle} total={70} /></td>
                <td><Chip kind={d.status}>{d.status === "ok" ? "OK" : "AT LIMIT"}</Chip></td>
                <td style={{ fontSize: 11, color: "var(--text-mid)" }}>{d.note}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Panel>
    </div>
  );
}

function HosCell({ used, total }) {
  const pct = (used / total) * 100;
  const color = pct > 90 ? "var(--danger)" : pct > 75 ? "var(--warn)" : "var(--accent)";
  return (
    <div>
      <div style={{ height: 4, background: "var(--bg-3)", borderRadius: 2 }}>
        <div style={{ width: `${pct}%`, height: "100%", background: color, borderRadius: 2 }} />
      </div>
      <div className="mono dim" style={{ fontSize: 10, marginTop: 2 }}>{used}h / {total}h</div>
    </div>
  );
}

function CsaView() {
  return (
    <div style={{ padding: 16 }}>
      <div className="grid cols-3" style={{ marginBottom: 16 }}>
        <CsaCard cat="UNSAFE DRIVING" pct={48} threshold={65} status="ok" />
        <CsaCard cat="HOS COMPLIANCE" pct={32} threshold={65} status="ok" />
        <CsaCard cat="DRIVER FITNESS" pct={28} threshold={80} status="ok" />
        <CsaCard cat="CONTROLLED SUBSTANCE" pct={12} threshold={80} status="ok" />
        <CsaCard cat="VEHICLE MAINT" pct={72} threshold={80} status="warn" />
        <CsaCard cat="HAZMAT" pct={0} threshold={80} status="ok" />
      </div>

      <Panel title="CARRIER SAFETY ALERTS · 30D">
        <table className="tbl">
          <thead><tr><th>Carrier</th><th>MC</th><th>Issue</th><th>Severity</th><th>Detected</th><th>AI Action</th></tr></thead>
          <tbody>
            <tr><td>Pinecone Hauling</td><td className="mono">MC-441002</td><td>Vehicle OOS rate 11.2% (median 6%)</td><td><Chip kind="warn">B</Chip></td><td className="mono dim">12d ago</td><td>Cap loads at 4/mo</td></tr>
            <tr><td>Apex Lines</td><td className="mono">MC-882144</td><td>DEF emission violation reported</td><td><Chip kind="warn">B</Chip></td><td className="mono dim">8d ago</td><td>Notified carrier</td></tr>
            <tr><td>Cypress Cargo</td><td className="mono">MC-882211</td><td>OOS spike + 2 complaints (Carrier411)</td><td><Chip kind="danger">FLAG</Chip></td><td className="mono dim">2d ago</td><td>Blocked from dispatch</td></tr>
          </tbody>
        </table>
      </Panel>
    </div>
  );
}

function CsaCard({ cat, pct, threshold, status }) {
  return (
    <div className="panel" style={{ padding: 14, borderLeft: `2px solid var(--${status === "warn" ? "warn" : status === "danger" ? "danger" : "ok"})` }}>
      <div className="kpi-label">{cat}</div>
      <div className="mono" style={{ fontSize: 22, marginTop: 4 }}>{pct} <span className="dim" style={{ fontSize: 12 }}>/ {threshold} threshold</span></div>
      <div style={{ marginTop: 10, height: 4, background: "var(--bg-3)", borderRadius: 2, position: "relative" }}>
        <div style={{ width: `${(pct / 100) * 100}%`, height: "100%", background: `var(--${status === "warn" ? "warn" : "ok"})`, borderRadius: 2 }} />
        <div style={{ position: "absolute", left: `${threshold}%`, top: -2, width: 1, height: 8, background: "var(--text-faint)" }} />
      </div>
    </div>
  );
}

function InsView() {
  return (
    <div style={{ padding: 16 }}>
      <AiBand
        confidence={98}
        text={<><b>6 COIs expiring within 30 days.</b> Renewal emails drafted to all carriers. 2 critical (expire {`<`}7d) — Keelway will call if no response by EOD.</>}
        actions={<>
          <button className="btn ghost sm">View drafts</button>
          <button className="btn primary sm">Send all</button>
        </>}
      />

      <Panel title="INSURANCE CERTIFICATES · EXPIRING SOON" style={{ marginTop: 16 }}>
        <table className="tbl">
          <thead><tr><th>Carrier</th><th>Coverage</th><th>Issuer</th><th>Expires</th><th>Days</th><th>Status</th><th>AI Action</th></tr></thead>
          <tbody>
            <tr style={{ background: "var(--danger-bg)" }}><td>Apex Lines</td><td>Auto $1M / Cargo $100k</td><td>Progressive</td><td className="mono">05/30</td><td><span className="down">5d</span></td><td><Chip kind="danger">CRITICAL</Chip></td><td>Email + call scheduled</td></tr>
            <tr style={{ background: "var(--danger-bg)" }}><td>Cypress Cargo</td><td>Auto $1M / Cargo $100k</td><td>National Indemnity</td><td className="mono">06/02</td><td><span className="down">8d</span></td><td><Chip kind="danger">CRITICAL</Chip></td><td>Loads paused</td></tr>
            <tr style={{ background: "var(--warn-bg)" }}><td>Heartland Hauling</td><td>Auto $1M / Cargo $100k</td><td>Great West</td><td className="mono">06/14</td><td><span className="warn">20d</span></td><td><Chip kind="warn">WATCH</Chip></td><td>Renewal email sent</td></tr>
            <tr><td>Pinecone Hauling</td><td>Auto $750k / Cargo $50k</td><td>Hallmark</td><td className="mono">06/22</td><td>28d</td><td><Chip kind="warn">WATCH</Chip></td><td>Reminder queued</td></tr>
            <tr><td>Eastern Star</td><td>Auto $1M / Cargo $100k</td><td>Northland</td><td className="mono">06/28</td><td>34d</td><td><Chip kind="ok">CURRENT</Chip></td><td>—</td></tr>
            <tr><td>Western Mountain</td><td>Auto $2M / Cargo $250k</td><td>Berkshire Hathaway</td><td className="mono">09/14</td><td>112d</td><td><Chip kind="ok">CURRENT</Chip></td><td>—</td></tr>
          </tbody>
        </table>
      </Panel>
    </div>
  );
}

function AuditView() {
  const events = [
    { t: "13:02:42", who: "Keelway AI",   what: "Filed detention claim $240",                 obj: "CLM-2418",   k: "ai" },
    { t: "13:02:18", who: "Keelway AI",   what: "Initiated check call",                       obj: "KW-48217",   k: "ai" },
    { t: "12:54:08", who: "Maya O.",      what: "Approved AI rate quote $3.58/mi",            obj: "RFQ-9921",   k: "user" },
    { t: "12:48:32", who: "Keelway AI",   what: "Blocked carrier MC-991884 · fraud signals",  obj: "FS-2401",    k: "block" },
    { t: "12:42:14", who: "D. Patel",     what: "Approved carrier Western Mtn for KW-48213",  obj: "KW-48213",   k: "user" },
    { t: "11:48:08", who: "Keelway AI",   what: "Auto-rejected double-broker attempt",        obj: "FS-2400",    k: "block" },
    { t: "11:14:22", who: "Costco EDI",   what: "RFP received · 218 lanes",                   obj: "RFP-2026Q3", k: "edi" },
    { t: "10:42:18", who: "Keelway AI",   what: "Drafted 12 customer reminders (collections)",obj: "AR batch",   k: "ai" },
    { t: "10:14:04", who: "Maya O.",      what: "Override AI rate ceiling on KW-48198",       obj: "KW-48198",   k: "override" },
    { t: "09:42:08", who: "Walmart EDI",  what: "204 tender accepted",                         obj: "KW-48217",   k: "edi" },
    { t: "09:18:14", who: "Keelway AI",   what: "Filed detention claim $240 (auto)",         obj: "KW-48210",   k: "ai" },
    { t: "08:54:42", who: "S. Lee",       what: "Logged in",                                  obj: "session",    k: "user" },
  ];
  return (
    <div style={{ padding: 16 }}>
      <Panel title="AUDIT LOG · LAST 24H · 412 EVENTS" actions={
        <div style={{ display: "flex", gap: 6 }}>
          <input className="cmdk" style={{ margin: 0, width: 240 }} placeholder="Filter…" />
          <button className="btn ghost sm">Export</button>
        </div>
      }>
        <table className="tbl">
          <thead><tr><th>Timestamp</th><th>Actor</th><th>Type</th><th>Action</th><th>Object</th></tr></thead>
          <tbody>
            {events.map((e, i) => (
              <tr key={i}>
                <td className="mono dim" style={{ fontSize: 11 }}>{e.t}</td>
                <td>{e.who}</td>
                <td><Chip kind={e.k === "ai" ? "accent" : e.k === "block" ? "danger" : e.k === "override" ? "warn" : e.k === "edi" ? "info" : ""}>{e.k.toUpperCase()}</Chip></td>
                <td>{e.what}</td>
                <td className="mono dim" style={{ fontSize: 11 }}>{e.obj}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Panel>
    </div>
  );
}

window.Compliance = Compliance;
