// =============================================================
// page-carriers-directory.jsx — Carrier directory (DAT-derived)
//
// Public-facing list of every carrier we've observed posting trucks
// on DAT One Freight, enriched with FMCSA authority + safety + fleet
// data. Filterable by authority status, safety rating, fleet size,
// state, and lane. Searchable by name or DOT#.
//
// Route: /#/carriers
// Reads from: dat_carriers
// =============================================================

const {
  useState: useStateCD,
  useEffect: useEffectCD,
  useMemo: useMemoCD,
} = React;

// Carrier-HQ map. Pin color = authority status (green=active, red=inactive,
// gray=unknown). Pin size = fleet (power_units). Click pin → highlights the
// carrier in the list below. Cluster handling stays simple — there are only
// ~150 carriers so we render every pin.
function CarrierHQMap({ carriers, isRedFlag }) {
  const containerRef = React.useRef(null);
  const mapRef = React.useRef(null);
  const layerRef = React.useRef(null);

  React.useEffect(() => {
    // Defensive wrapper: a malformed carrier row, an early-mount with
    // carriers=undefined, or a Leaflet init failure should never crash
    // the page. Worst case: map fails to render, list still works.
    try {
      if (!containerRef.current || !window.L) return;
      if (!Array.isArray(carriers)) return;
      if (!mapRef.current) {
        mapRef.current = window.L.map(containerRef.current, {
          center: [39.0, -96.0], zoom: 4, scrollWheelZoom: false,
          attributionControl: true,
        });
        window.L.tileLayer("https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png", {
          attribution: "© OpenStreetMap contributors © CARTO",
          subdomains: "abcd", maxZoom: 18,
        }).addTo(mapRef.current);
      }
      if (layerRef.current) {
        layerRef.current.remove();
      }
      const grp = window.L.layerGroup();
      let mapped = 0;
      for (const c of carriers) {
        try {
          if (!c || c.hq_lat == null || c.hq_lng == null) continue;
          const flagged = isRedFlag(c);
          const units = c.power_units || 0;
          const radius = Math.max(4, Math.min(14, Math.sqrt(units) + 4));
          const color =
            flagged ? "#c0392b" :
            c.authority_status === "active" ? "#27ae60" :
            c.authority_status === "inactive" ? "#e67e22" : "#7f8c8d";
          const marker = window.L.circleMarker([c.hq_lat, c.hq_lng], {
            radius, color, weight: 1.5, fillColor: color, fillOpacity: 0.55,
          });
          const html = `
        <div style="font-family:inherit;font-size:13px;line-height:1.4;min-width:180px">
          <div style="font-family:var(--font-serif);font-size:15px;font-weight:600">${c.canonical_name}</div>
          <div style="color:#666;font-family:var(--font-mono);font-size:11px;margin-top:4px">
            ${c.hq_city || ""}, ${c.hq_state || ""}
          </div>
          <div style="margin-top:8px;font-size:12px">
            ${c.dot_number ? `DOT ${c.dot_number}` : ""}
            ${c.mc_number ? ` · ${c.mc_number}` : ""}
          </div>
          <div style="margin-top:6px;font-family:var(--font-mono);font-size:11px;color:#555">
            ${units} trucks · ${c.authority_status || "unknown"}
          </div>
          ${flagged ? `<div style="margin-top:8px;padding:4px 8px;background:#c0392b;color:#fff;font-family:var(--font-mono);font-size:9px;letter-spacing:0.14em;font-weight:700">DOUBLE-BROKERING RISK</div>` : ""}
        </div>`;
      marker.bindPopup(html);
      grp.addLayer(marker);
      mapped++;
        } catch (rowErr) {
          console.warn("[CarrierHQMap] skipped carrier", c && c.canonical_name, rowErr);
        }
      }
      grp.addTo(mapRef.current);
      layerRef.current = grp;
    } catch (err) {
      console.error("[CarrierHQMap] effect failed", err);
    }
  }, [carriers]);

  return (
    <div style={{ width: "100%", height: 420, borderRadius: 8, overflow: "hidden", border: "1px solid var(--rule)" }}>
      <div ref={containerRef} style={{ width: "100%", height: "100%" }} />
    </div>
  );
}

function CarriersDirectoryPage({ onNav }) {
  const [carriers, setCarriers] = useStateCD([]);
  const [caMcp, setCaMcp]       = useStateCD({});      // dot_number → mcp row
  const [bond, setBond]         = useStateCD({});      // dot_number → bond row
  const [signals, setSignals]   = useStateCD({});      // carrier_id → {count, top}
  const [loading, setLoading]   = useStateCD(true);
  const [query, setQuery]       = useStateCD("");
  const [authFilter, setAuthFilter] = useStateCD("all");   // all|active|inactive|red-flag|ca-gap|bond-risk|distress
  const [stateFilter, setStateFilter] = useStateCD("all");
  const [sizeFilter, setSizeFilter] = useStateCD("all");   // all|owner|small|mid|large
  const [page, setPage] = useStateCD(0);
  const PAGE_SIZE = 50;

  useEffectCD(() => {
    let alive = true;
    if (!window.SI_DB || !window.SI_DB.raw) return;
    (async () => {
      try {
        const [carriersRows, mcpRows, bondRows, signalRows] = await Promise.all([
          window.SI_DB.raw.select(
            "dat_carriers",
            "select=id,canonical_name,dot_number,mc_number,mc_status,legal_name,dba_name,hq_city,hq_state,hq_lat,hq_lng,authority_status,safety_rating,power_units,drivers,observed_lanes,observation_count,fmcsa_enriched_at&order=power_units.desc.nullslast,canonical_name.asc&limit=2000"
          ),
          window.SI_DB.raw.select(
            "ca_motor_carrier_permits",
            "select=ca_id,carrier_name,dot_number,mc_number,authority_status,permit_type&dot_number=not.is.null&limit=20000"
          ).catch(() => []),
          window.SI_DB.raw.select(
            "broker_bond_status",
            "select=dot_number,mc_number,authority_status,authority_type,bond_type,bond_filed,surety_company,cancellation_in_process,bond_cancellation_date,observed_at&limit=5000"
          ).catch(() => []),
          window.SI_DB.raw.select(
            "carrier_signals_recent",
            "select=carrier_id,source,signal_type,signal_data,severity,observed_at&order=observed_at.desc&limit=5000"
          ).catch(() => []),
        ]);
        if (!alive) return;
        setCarriers(Array.isArray(carriersRows) ? carriersRows : []);
        const mcpMap = {};
        if (Array.isArray(mcpRows)) {
          for (const r of mcpRows) {
            if (r && r.dot_number) mcpMap[String(r.dot_number)] = r;
          }
        }
        setCaMcp(mcpMap);
        const bondMap = {};
        if (Array.isArray(bondRows)) {
          for (const r of bondRows) {
            if (r && r.dot_number) bondMap[String(r.dot_number)] = r;
          }
        }
        setBond(bondMap);
        // Aggregate signals → first-seen-per-carrier wins (since the view
        // is ordered observed_at DESC, the first hit IS the most recent).
        const sigMap = {};
        if (Array.isArray(signalRows)) {
          for (const s of signalRows) {
            if (!s || !s.carrier_id) continue;
            const cid = s.carrier_id;
            if (!sigMap[cid]) {
              sigMap[cid] = { count: 0, top: null, hasHigh: false };
            }
            sigMap[cid].count += 1;
            if (s.severity === "critical" || s.severity === "high") {
              sigMap[cid].hasHigh = true;
              if (!sigMap[cid].top) sigMap[cid].top = s;
            }
          }
        }
        setSignals(sigMap);
      } catch {}
      finally { if (alive) setLoading(false); }
    })();
    return () => { alive = false; };
  }, []);

  // CA MCP cross-ref classification, returned per carrier:
  //   'legitimate_dual'         → both CA + FMCSA active
  //   'ca_active_fmcsa_gap'     → CA permit but FMCSA gap (illegal interstate)
  //   'fmcsa_active_no_ca_mcp'  → FMCSA active but BLOCKED from CA work
  //   'unknown'                 → no FMCSA enrich yet, or no CA-relevant signal
  const caMcpClass = (c) => {
    const dot = c.dot_number ? String(c.dot_number) : null;
    if (!dot || !c.fmcsa_enriched_at) return "unknown";
    const mcp = caMcp[dot];
    const fmcsaActive = c.mc_status === "has_mc_active";
    const mcpActive = mcp && (mcp.authority_status === "Active");
    if (mcpActive && fmcsaActive)               return "legitimate_dual";
    if (mcpActive && !fmcsaActive)              return "ca_active_fmcsa_gap";
    if (!mcp && fmcsaActive)                    return "fmcsa_active_no_ca_mcp";
    return "unknown";
  };

  // FMCSA L&I bond status — broker pre-revocation early warning.
  //   'authority_lost'                → Inactive / Revoked / Out of Service
  //   'bond_cancellation_in_process'  → ~30 days from authority revocation
  //   'no_bond_on_file'               → broker authority but no BMC-84/85
  //   'normal'                        → bond looks fine
  //   'unknown'                       → not a broker, or not yet scraped
  const bondClass = (c) => {
    const dot = c.dot_number ? String(c.dot_number) : null;
    if (!dot) return "unknown";
    const b = bond[dot];
    if (!b) return "unknown";
    if (["Inactive", "Revoked", "Out of Service"].includes(b.authority_status)) return "authority_lost";
    if (b.cancellation_in_process)                               return "bond_cancellation_in_process";
    const isBroker = b.authority_type === "Broker" || b.authority_type === "Broker/Carrier";
    if (isBroker && b.bond_filed === false)                      return "no_bond_on_file";
    return "normal";
  };

  const states = useMemoCD(() => {
    const s = new Set(carriers.map(c => c.hq_state).filter(Boolean));
    return ["all", ...[...s].sort()];
  }, [carriers]);

  const isRedFlag = (c) => (
    c.authority_status === "inactive" ||
    c.power_units === 0 ||
    c.safety_rating === "c" || c.safety_rating === "u"
  );

  const sizeBand = (units) => {
    if (units == null) return "unknown";
    if (units === 0) return "zero";
    if (units <= 5) return "owner";
    if (units <= 25) return "small";
    if (units <= 100) return "mid";
    return "large";
  };

  const filtered = useMemoCD(() => {
    const q = query.trim().toLowerCase();
    return carriers.filter(c => {
      if (q) {
        const haystack = [c.canonical_name, c.legal_name, c.dba_name, c.dot_number, c.mc_number]
          .filter(Boolean).join(" ").toLowerCase();
        if (!haystack.includes(q)) return false;
      }
      if (authFilter === "active"   && c.authority_status !== "active") return false;
      if (authFilter === "inactive" && c.authority_status !== "inactive") return false;
      if (authFilter === "red-flag" && !isRedFlag(c)) return false;
      if (authFilter === "ca-gap"   && caMcpClass(c) !== "fmcsa_active_no_ca_mcp" && caMcpClass(c) !== "ca_active_fmcsa_gap") return false;
      if (authFilter === "bond-risk") {
        const b = bondClass(c);
        if (b !== "bond_cancellation_in_process" && b !== "no_bond_on_file" && b !== "authority_lost") return false;
      }
      if (authFilter === "distress") {
        const sig = signals[c.id];
        if (!sig || !sig.hasHigh) return false;
      }
      if (stateFilter !== "all" && c.hq_state !== stateFilter) return false;
      if (sizeFilter !== "all" && sizeBand(c.power_units) !== sizeFilter) return false;
      return true;
    });
  }, [carriers, query, authFilter, stateFilter, sizeFilter]);

  const visible = useMemoCD(() => filtered.slice(0, (page + 1) * PAGE_SIZE), [filtered, page]);
  const hasMore = filtered.length > visible.length;

  const stats = useMemoCD(() => {
    const a = carriers.filter(c => c.authority_status === "active").length;
    const i = carriers.filter(c => c.authority_status === "inactive").length;
    const rf = carriers.filter(isRedFlag).length;
    return { total: carriers.length, active: a, inactive: i, redFlag: rf };
  }, [carriers]);

  return (
    <div className="cd-page">
      <style>{`
        .cd-page { background: var(--paper, #fff); min-height: 100vh; }
        .cd-hero { max-width: 1180px; margin: 0 auto; padding: 64px 24px 32px; }
        .cd-eyebrow {
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.32em;
          text-transform: uppercase; color: var(--ink-soft); margin-bottom: 18px;
          display: inline-flex; align-items: center; gap: 10px;
        }
        .cd-eyebrow .dot { width: 8px; height: 8px; border-radius: 50%;
          background: oklch(0.55 0.18 250); animation: cd-pulse 1.6s infinite; }
        @keyframes cd-pulse { 0%,100%{opacity:1} 50%{opacity:0.4} }
        .cd-h1 {
          font-family: var(--font-serif); font-size: 56px; line-height: 1.04;
          letter-spacing: -0.025em; margin: 0; font-weight: 500; color: var(--ink); max-width: 920px;
        }
        @media (max-width: 700px) { .cd-h1 { font-size: 36px; } }
        .cd-sub { margin-top: 18px; font-size: 18px; line-height: 1.5; color: var(--ink-soft); max-width: 780px; }

        .cd-stats {
          margin-top: 40px; padding: 24px 0; border-top: 1px solid var(--rule);
          border-bottom: 1px solid var(--rule);
          display: grid; grid-template-columns: repeat(4, 1fr); gap: 0;
        }
        @media (max-width: 720px) { .cd-stats { grid-template-columns: repeat(2, 1fr); } }
        .cd-stat { padding: 0 24px; border-right: 1px solid var(--rule); }
        .cd-stat:first-child { padding-left: 0; }
        .cd-stat:last-child { border-right: 0; padding-right: 0; }
        @media (max-width: 720px) {
          .cd-stat:nth-child(2n) { border-right: 0; }
          .cd-stat:nth-child(2n+1) { padding-left: 0; }
        }
        .cd-stat-num {
          font-family: var(--font-serif); font-size: 32px; line-height: 1;
          letter-spacing: -0.02em; font-weight: 600; color: var(--ink);
        }
        .cd-stat-num.warn { color: oklch(0.45 0.20 25); }
        .cd-stat-l {
          margin-top: 6px; font-family: var(--font-mono); font-size: 10px;
          letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink-soft);
        }

        .cd-controls {
          max-width: 1180px; margin: 32px auto 0; padding: 0 24px;
          display: flex; flex-wrap: wrap; gap: 12px; align-items: center;
        }
        .cd-search {
          flex: 1; min-width: 240px;
          padding: 12px 14px; border: 1px solid var(--rule); border-radius: 6px;
          background: var(--paper); color: var(--ink); outline: none;
          font: inherit; font-size: 15px;
        }
        .cd-search:focus { border-color: var(--ink); }
        .cd-select {
          padding: 11px 12px; border: 1px solid var(--rule); border-radius: 6px;
          background: var(--paper); color: var(--ink); font: inherit; font-size: 14px; cursor: pointer;
        }
        .cd-pill {
          padding: 9px 14px; border: 1px solid var(--rule); border-radius: 999px;
          background: var(--paper); color: var(--ink-soft); cursor: pointer;
          font: inherit; font-size: 12px; letter-spacing: 0.04em;
        }
        .cd-pill.active { background: var(--ink); color: #fff; border-color: var(--ink); }
        .cd-pill.warn.active { background: oklch(0.45 0.20 25); border-color: oklch(0.45 0.20 25); }

        .cd-list { max-width: 1180px; margin: 24px auto 0; padding: 0 24px 96px; }
        .cd-empty {
          padding: 48px 24px; text-align: center; color: var(--ink-soft); font-size: 15px;
        }
        .cd-row {
          display: grid;
          grid-template-columns: 2fr 130px 100px 90px 110px 1fr;
          gap: 16px; align-items: center;
          padding: 14px 0; border-bottom: 1px solid var(--rule);
          font-size: 14px;
        }
        @media (max-width: 980px) {
          .cd-row { grid-template-columns: 2fr 100px 90px; }
          .cd-row .cd-row-fleet, .cd-row .cd-row-state, .cd-row .cd-row-lanes { display: none; }
        }
        .cd-row.flagged {
          background: oklch(0.99 0.02 25); border-left: 3px solid oklch(0.55 0.20 25);
          padding-left: 12px;
        }
        .cd-row-name {
          font-family: var(--font-serif); font-size: 17px; color: var(--ink);
          letter-spacing: -0.005em;
        }
        .cd-row-name .legal { font-size: 11px; color: var(--ink-soft); font-family: var(--font-mono); }
        .cd-row-dot {
          font-family: var(--font-mono); font-size: 12px; color: var(--ink-soft);
        }
        .cd-row-dot strong { color: var(--ink); display:block; font-size:11px; letter-spacing: 0.04em; }
        .cd-row-fleet {
          font-family: var(--font-mono); font-size: 12px; color: var(--ink-soft); text-align: right;
        }
        .cd-row-fleet strong { color: var(--ink); font-size: 14px; }
        .cd-row-state { font-family: var(--font-mono); font-size: 12px; color: var(--ink-soft); }
        .cd-row-lanes {
          font-family: var(--font-mono); font-size: 11px; color: var(--ink-soft); letter-spacing: 0.04em;
        }
        .cd-badge {
          font-family: var(--font-mono); font-size: 9px; letter-spacing: 0.16em;
          padding: 3px 8px; border-radius: 3px; font-weight: 700; text-transform: uppercase;
          text-align: center; display: inline-block;
        }
        .cd-badge-active   { background: oklch(0.95 0.06 145); color: oklch(0.40 0.16 145); }
        .cd-badge-inactive { background: oklch(0.95 0.10 25);  color: oklch(0.45 0.22 25); }
        .cd-badge-cond     { background: oklch(0.93 0.10 60);  color: oklch(0.40 0.18 60); }
        .cd-badge-flag     { background: oklch(0.45 0.22 25); color: #fff; }
        .cd-badge-unknown  { background: oklch(0.95 0.01 60);  color: var(--ink-soft); }

        .cd-loadmore {
          margin: 32px auto 0; display: block; padding: 14px 28px;
          font: inherit; font-size: 14px; cursor: pointer;
          border: 1px solid var(--ink); background: var(--paper); color: var(--ink);
          border-radius: 6px; font-weight: 600;
        }
        .cd-loadmore:hover { background: var(--ink); color: #fff; }

        .cd-paid {
          margin: 32px 0; padding: 24px;
          background: oklch(0.98 0.02 250); border: 1px solid oklch(0.85 0.06 250);
          border-radius: 8px;
        }
        .cd-paid-h {
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.22em;
          text-transform: uppercase; color: oklch(0.40 0.16 250); margin-bottom: 8px;
        }
        .cd-paid-t {
          font-family: var(--font-serif); font-size: 22px; letter-spacing: -0.01em; margin: 0 0 6px;
        }
        .cd-paid-s { color: var(--ink-soft); font-size: 14px; line-height: 1.5; margin: 0; }
      `}</style>

      <section className="cd-hero">
        <div className="cd-eyebrow"><span className="dot" /> Carrier verification · live federal cross-check</div>
        <h1 className="cd-h1">How do you know the carrier you're working with is actually legal?</h1>
        <p className="cd-sub">
          Lapsed MC authority. No MC at all. Broker-only operations posting
          trucks they don't own. When a load is re-tendered through an
          unauthorized chain and something goes sideways, your insurance and
          chain-of-custody can break the same hour. Every carrier listed here
          is cross-referenced live against the federal carrier registry —
          authority, safety, fleet, MC status, all verified. Free.
        </p>

        <div className="cd-stats">
          <div className="cd-stat">
            <div className="cd-stat-num">{loading ? "…" : stats.total}</div>
            <div className="cd-stat-l">Total carriers</div>
          </div>
          <div className="cd-stat">
            <div className="cd-stat-num">{loading ? "…" : stats.active}</div>
            <div className="cd-stat-l">Active authority</div>
          </div>
          <div className="cd-stat">
            <div className="cd-stat-num warn">{loading ? "…" : stats.inactive}</div>
            <div className="cd-stat-l">Inactive authority</div>
          </div>
          <div className="cd-stat">
            <div className="cd-stat-num warn">{loading ? "…" : stats.redFlag}</div>
            <div className="cd-stat-l">🚩 Double-brokering risk</div>
          </div>
        </div>
      </section>

      {/* Map of carrier HQs — visual proof of geographic concentration */}
      <section style={{ maxWidth: 1180, margin: "20px auto 0", padding: "0 24px" }}>
        <div style={{
          fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.32em",
          textTransform: "uppercase", color: "var(--ink-soft)",
          paddingBottom: 12, borderBottom: "1px solid var(--rule)", marginBottom: 14,
          display: "flex", justifyContent: "space-between", alignItems: "baseline", flexWrap: "wrap", gap: 10,
        }}>
          <span>Carrier HQ map · click any pin</span>
          <span style={{ fontSize: 10, letterSpacing: "0.16em", display: "flex", gap: 12, flexWrap: "wrap" }}>
            <span><span style={{display:"inline-block",width:8,height:8,borderRadius:"50%",background:"#27ae60",marginRight:4}}/>Active</span>
            <span><span style={{display:"inline-block",width:8,height:8,borderRadius:"50%",background:"#e67e22",marginRight:4}}/>Inactive</span>
            <span><span style={{display:"inline-block",width:8,height:8,borderRadius:"50%",background:"#c0392b",marginRight:4}}/>Double-brokering risk</span>
            <span style={{ color: "var(--ink-soft)" }}>· pin size = fleet</span>
          </span>
        </div>
        {!loading && carriers.length > 0 && (
          <CarrierHQMap carriers={carriers} isRedFlag={isRedFlag} />
        )}
        {!loading && carriers.length > 0 && carriers.filter(c => c.hq_lat != null).length === 0 && (
          <div style={{ padding: 24, textAlign: "center", fontSize: 13, color: "var(--ink-soft)", border: "1px solid var(--rule)", borderRadius: 6 }}>
            Geocoding pending — run <code>geocode-dat-carriers.py</code> to populate hq_lat/hq_lng.
          </div>
        )}
      </section>

      <div className="cd-controls">
        <input
          type="text"
          className="cd-search"
          placeholder="Search by name, DOT#, or MC#…"
          value={query}
          onChange={e => { setQuery(e.target.value); setPage(0); }}
          autoComplete="off"
        />
        <select className="cd-select" value={stateFilter} onChange={e => { setStateFilter(e.target.value); setPage(0); }}>
          {states.map(s => <option key={s} value={s}>{s === "all" ? "All states" : s}</option>)}
        </select>
        <select className="cd-select" value={sizeFilter} onChange={e => { setSizeFilter(e.target.value); setPage(0); }}>
          <option value="all">All fleet sizes</option>
          <option value="owner">Owner-op (1-5)</option>
          <option value="small">Small (6-25)</option>
          <option value="mid">Mid (26-100)</option>
          <option value="large">Large (100+)</option>
          <option value="zero">Zero trucks ⚠️</option>
        </select>
        <button className={`cd-pill ${authFilter === "all" ? "active" : ""}`} onClick={() => { setAuthFilter("all"); setPage(0); }}>All</button>
        <button className={`cd-pill ${authFilter === "active" ? "active" : ""}`} onClick={() => { setAuthFilter("active"); setPage(0); }}>Active only</button>
        <button className={`cd-pill warn ${authFilter === "red-flag" ? "active" : ""}`} onClick={() => { setAuthFilter("red-flag"); setPage(0); }}>🚩 Double-brokering risk</button>
        <button className={`cd-pill warn ${authFilter === "ca-gap" ? "active" : ""}`} onClick={() => { setAuthFilter("ca-gap"); setPage(0); }} title="Carriers with a CA / FMCSA mismatch — blocked from legal CA work or operating illegally interstate">🐻 CA permit gap</button>
        <button className={`cd-pill warn ${authFilter === "bond-risk" ? "active" : ""}`} onClick={() => { setAuthFilter("bond-risk"); setPage(0); }} title="Brokers with FMCSA L&I bond cancellation in process, no bond on file, or lost authority">🚨 Bond risk</button>
        <button className={`cd-pill warn ${authFilter === "distress" ? "active" : ""}`} onClick={() => { setAuthFilter("distress"); setPage(0); }} title="Carriers with one or more high/critical distress signals in the last 90 days (NLRB, WARN, bankruptcy, OSHA, FMCSA L&I)">⚠ Distress signal</button>
      </div>

      <div className="cd-list">
        {loading ? (
          <div className="cd-empty">Loading…</div>
        ) : filtered.length === 0 ? (
          <div className="cd-empty">No carriers match those filters.</div>
        ) : (
          <>
            {visible.map(c => {
              const flagged = isRedFlag(c);
              const authBadge =
                c.authority_status === "active"   ? "active"   :
                c.authority_status === "inactive" ? "inactive" : "unknown";
              const safetyBadge =
                c.safety_rating === "s" ? "active"  :
                c.safety_rating === "c" ? "cond"    :
                c.safety_rating === "u" ? "flag"    : null;
              const ca = caMcpClass(c);
              const caTitle =
                ca === "legitimate_dual"        ? "CA Motor Carrier Permit + FMCSA both active — legitimate"  :
                ca === "ca_active_fmcsa_gap"    ? "Holds CA MCP but FMCSA authority is inactive — illegal interstate operation"  :
                ca === "fmcsa_active_no_ca_mcp" ? "FMCSA authority active. No CA Motor Carrier Permit on file — neutral signal: most US carriers don't run California."  :
                null;
              const bk = bondClass(c);
              const bkTitle =
                bk === "authority_lost"               ? "FMCSA authority lost — Inactive, Revoked, or Out of Service"  :
                bk === "bond_cancellation_in_process" ? "FMCSA L&I shows bond Cancellation in Process — typically ~30 days from authority revocation"  :
                bk === "no_bond_on_file"              ? "Broker authority on file but NO BMC-84 surety bond / BMC-85 trust"  :
                null;
              return (
                <div key={c.id} className={`cd-row ${flagged ? "flagged" : ""}`}
                     style={{ cursor: "pointer" }}
                     onClick={() => { window.location.hash = `#/profile/${c.id}`; }}>
                  <div className="cd-row-name">
                    {flagged && <span className="cd-badge cd-badge-flag" style={{marginRight:8}} title="Possible double-brokering operation: lapsed MC, no MC, no trucks, or unsatisfactory safety">DOUBLE-BROKERING RISK</span>}
                    {bk === "bond_cancellation_in_process" && <span className="cd-badge cd-badge-flag" style={{marginRight:8}} title={bkTitle}>BOND CANCELLATION PENDING</span>}
                    {bk === "no_bond_on_file"              && <span className="cd-badge cd-badge-flag" style={{marginRight:8}} title={bkTitle}>NO BOND ON FILE</span>}
                    {bk === "authority_lost"               && <span className="cd-badge cd-badge-flag" style={{marginRight:8}} title={bkTitle}>AUTHORITY LOST</span>}
                    {/* No-CA-permit is NOT a flag worth surfacing in the directory list.
                        Most US carriers don't operate in California; absence of a CA MCP
                        just means they don't run CA freight, not that they're sketchy.
                        Kept on the dossier page as informational context, not as a badge. */}
                    {ca === "ca_active_fmcsa_gap"    && <span className="cd-badge cd-badge-flag" style={{marginRight:8}} title={caTitle}>CA / FMCSA MISMATCH</span>}
                    {ca === "legitimate_dual"        && <span className="cd-badge cd-badge-active" style={{marginRight:8}} title={caTitle}>CA ✓</span>}
                    {c.canonical_name}
                    {c.legal_name && c.legal_name.toLowerCase() !== c.canonical_name.toLowerCase() && (
                      <div className="legal">{c.legal_name}{c.dba_name ? ` · dba ${c.dba_name}` : ""}</div>
                    )}
                    {signals[c.id] && signals[c.id].hasHigh && signals[c.id].top && (
                      <div style={{ fontSize: 11, fontFamily: "var(--font-mono)", color: "oklch(0.45 0.20 25)", marginTop: 4 }}
                           title={`${signals[c.id].count} signal${signals[c.id].count === 1 ? '' : 's'} in last 90d · click to filter all distress carriers`}>
                        ⚠ {(signals[c.id].top.signal_data || {}).headline || signals[c.id].top.signal_type}
                        {signals[c.id].count > 1 && ` · +${signals[c.id].count - 1} more`}
                      </div>
                    )}
                  </div>
                  <div className="cd-row-dot">
                    {c.dot_number && <><strong>DOT</strong>{c.dot_number}</>}
                    {c.mc_number && <div style={{marginTop:2}}><strong>MC</strong>{c.mc_number.replace(/^MC-/i, "")}</div>}
                  </div>
                  <div>
                    <span className={`cd-badge cd-badge-${authBadge}`}>
                      {c.authority_status || "unknown"}
                    </span>
                    {safetyBadge && (
                      <div style={{marginTop:4}}>
                        <span className={`cd-badge cd-badge-${safetyBadge}`}>
                          safety: {c.safety_rating === "s" ? "satis." : c.safety_rating === "c" ? "cond." : "unsat."}
                        </span>
                      </div>
                    )}
                  </div>
                  <div className="cd-row-fleet">
                    <strong>{c.power_units != null ? c.power_units : "?"}</strong> trucks
                    {c.drivers != null && <div style={{fontSize:10}}>{c.drivers} drivers</div>}
                  </div>
                  <div className="cd-row-state">
                    {c.hq_city && c.hq_state ? `${c.hq_city}, ${c.hq_state}` : (c.hq_state || "—")}
                  </div>
                  <div className="cd-row-lanes">
                    {c.observed_lanes && c.observed_lanes.length > 0
                      ? c.observed_lanes.slice(0, 3).join(" · ") + (c.observed_lanes.length > 3 ? ` +${c.observed_lanes.length - 3}` : "")
                      : "—"}
                  </div>
                </div>
              );
            })}
            {hasMore && (
              <button className="cd-loadmore" onClick={() => setPage(page + 1)}>
                Load {Math.min(PAGE_SIZE, filtered.length - visible.length)} more · {filtered.length - visible.length} remaining
              </button>
            )}
            <div className="cd-paid">
              <div className="cd-paid-h">A private-market check for a market going back to the wild west</div>
              <h3 className="cd-paid-t">Federal enforcement is thinner every year. The check has to come from somewhere.</h3>
              <p className="cd-paid-s">
                Cargo theft, double brokering, and lapsed-authority fraud are at multi-decade highs while regulators stretch thin. Our broker-tier verification API ($99/mo) is a single REST call to check any carrier name, DOT#, or MC# against authority, safety, fleet, and lane-rate history before you tender a single load. Catch the broken chain before it touches your freight. Checkout ships with the rest of Tier-1.
              </p>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

window.CarriersDirectoryPage = CarriersDirectoryPage;

// =============================================================
// DatCarrierProfile — per-carrier detail page at /#/profile/<uuid>.
// The shape of the $499 risk-report deliverable: full FMCSA enrich,
// CA MCP cross-ref, FMCSA L&I bond status, observed lanes, and the
// timeline of carrier_signals (NLRB / WARN / bankruptcy / OSHA / bond).
// =============================================================
function DatCarrierProfile({ onNav, carrierId }) {
  const [carrier, setCarrier] = useStateCD(null);
  const [mcp, setMcp]         = useStateCD(null);
  const [bond, setBond]       = useStateCD(null);
  const [signals, setSignals] = useStateCD([]);
  const [loading, setLoading] = useStateCD(true);

  useEffectCD(() => {
    let alive = true;
    if (!window.SI_DB || !window.SI_DB.raw || !carrierId) {
      setLoading(false);
      return;
    }
    (async () => {
      try {
        const carrierRows = await window.SI_DB.raw.select(
          "dat_carriers",
          `select=*&id=eq.${encodeURIComponent(carrierId)}&limit=1`
        );
        const c = Array.isArray(carrierRows) && carrierRows[0];
        if (!alive) return;
        setCarrier(c || null);
        if (!c) { setLoading(false); return; }
        const dot = c.dot_number;
        const [mcpRows, bondRows, signalRows] = await Promise.all([
          dot ? window.SI_DB.raw.select(
            "ca_motor_carrier_permits",
            `select=*&dot_number=eq.${encodeURIComponent(dot)}&limit=1`
          ).catch(() => []) : Promise.resolve([]),
          dot ? window.SI_DB.raw.select(
            "broker_bond_status",
            `select=*&dot_number=eq.${encodeURIComponent(dot)}&limit=1`
          ).catch(() => []) : Promise.resolve([]),
          window.SI_DB.raw.select(
            "carrier_signals",
            `select=source,signal_type,signal_data,weight,source_url,observed_at&carrier_id=eq.${encodeURIComponent(carrierId)}&order=observed_at.desc&limit=100`
          ).catch(() => []),
        ]);
        if (!alive) return;
        setMcp(Array.isArray(mcpRows) && mcpRows[0] ? mcpRows[0] : null);
        setBond(Array.isArray(bondRows) && bondRows[0] ? bondRows[0] : null);
        setSignals(Array.isArray(signalRows) ? signalRows : []);
      } catch {}
      finally { if (alive) setLoading(false); }
    })();
    return () => { alive = false; };
  }, [carrierId]);

  if (loading) {
    return <div style={{ padding: 96, textAlign: "center", color: "var(--ink-soft)" }}>Loading carrier profile…</div>;
  }
  if (!carrier) {
    return (
      <div style={{ maxWidth: 720, margin: "0 auto", padding: 96, textAlign: "center" }}>
        <div style={{ fontFamily: "var(--font-serif)", fontSize: 24, marginBottom: 12 }}>Carrier not found</div>
        <a href="#/find-carrier" style={{ color: "var(--ink)", borderBottom: "1px solid var(--rule)" }}
           onClick={(e) => { e.preventDefault(); window.location.hash = "#/find-carrier"; }}>
          ← Back to verify-carrier directory
        </a>
      </div>
    );
  }

  const fmcsaActive = carrier.mc_status === "has_mc_active";
  const mcpActive = mcp && mcp.authority_status === "Active";

  // CA MCP classification (same logic as the directory)
  const caClass =
    !carrier.fmcsa_enriched_at         ? "unknown" :
    (mcpActive && fmcsaActive)         ? "legitimate_dual" :
    (mcpActive && !fmcsaActive)        ? "ca_active_fmcsa_gap" :
    (!mcp && fmcsaActive)              ? "fmcsa_active_no_ca_mcp" :
    "unknown";

  // Bond classification
  const bondRedFlag =
    bond && ["Inactive","Revoked","Out of Service"].includes(bond.authority_status) ? "authority_lost" :
    bond && bond.cancellation_in_process                                              ? "bond_cancellation_in_process" :
    bond && bond.bond_filed === false && (bond.authority_type === "Broker" || bond.authority_type === "Broker/Carrier") ? "no_bond_on_file" :
    bond ? "normal" : "unknown";

  const sevColor = (s) => ({
    critical: "oklch(0.50 0.22 25)",
    high:     "oklch(0.55 0.18 25)",
    moderate: "oklch(0.55 0.14 80)",
    low:      "var(--ink-soft)",
  }[s] || "var(--ink-soft)");
  const sev = (w) => w >= 8 ? "critical" : w >= 5 ? "high" : w >= 3 ? "moderate" : "low";

  const SOURCE_LABELS = {
    "nlrb":          "NLRB case",
    "warn":          "WARN notice",
    "courtlistener": "PACER docket",
    "osha":          "OSHA report",
    "fmcsa-li":      "FMCSA L&I",
  };

  return (
    <div style={{ background: "var(--paper, #fff)", minHeight: "100vh", paddingBottom: 96 }}>
      <style>{`
        .cp-back {
          display: inline-block; margin-top: 24px; margin-left: 24px;
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.16em;
          text-transform: uppercase; color: var(--ink-soft); text-decoration: none;
        }
        .cp-back:hover { color: var(--ink); }
        .cp-hero { max-width: 1180px; margin: 0 auto; padding: 24px 24px 32px; }
        .cp-eyebrow {
          font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.32em;
          text-transform: uppercase; color: var(--ink-soft); margin-bottom: 14px;
        }
        .cp-h1 {
          font-family: var(--font-serif); font-size: 44px; line-height: 1.05;
          letter-spacing: -0.02em; margin: 0 0 8px; font-weight: 600;
        }
        @media (max-width: 700px) { .cp-h1 { font-size: 30px; } }
        .cp-meta {
          margin-top: 14px; display: flex; flex-wrap: wrap; gap: 16px;
          font-family: var(--font-mono); font-size: 12px; color: var(--ink-soft);
        }
        .cp-badges { margin-top: 14px; display: flex; flex-wrap: wrap; gap: 8px; }
        .cp-badge {
          padding: 4px 10px; border-radius: 4px; font-family: var(--font-mono);
          font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; font-weight: 700;
        }
        .cp-badge-active { background: oklch(0.92 0.08 145); color: oklch(0.35 0.15 145); }
        .cp-badge-warn   { background: oklch(0.94 0.10 60);  color: oklch(0.40 0.18 60); }
        .cp-badge-flag   { background: oklch(0.93 0.10 25);  color: oklch(0.40 0.20 25); }
        .cp-badge-neutral{ background: oklch(0.96 0.01 240); color: var(--ink-soft); }
        .cp-section { max-width: 1180px; margin: 24px auto; padding: 0 24px; }
        .cp-section-h {
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.32em;
          text-transform: uppercase; color: var(--ink-soft);
          padding-bottom: 12px; border-bottom: 1px solid var(--rule); margin-bottom: 16px;
        }
        .cp-grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        @media (max-width: 760px) { .cp-grid-2 { grid-template-columns: 1fr; } }
        .cp-card {
          background: #fff; border: 1px solid var(--rule); border-radius: 6px;
          padding: 18px;
        }
        .cp-card-h {
          font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.18em;
          text-transform: uppercase; color: var(--ink-soft); margin-bottom: 10px;
        }
        .cp-kv { display: grid; grid-template-columns: 140px 1fr; gap: 6px 12px; font-size: 13px; }
        .cp-kv dt { color: var(--ink-soft); font-family: var(--font-mono); font-size: 11px; }
        .cp-kv dd { margin: 0; color: var(--ink); }
        .cp-signal-row {
          display: grid; grid-template-columns: 80px 1fr 110px;
          gap: 12px; padding: 10px 0; border-bottom: 1px solid var(--rule);
          align-items: baseline; font-size: 13px;
        }
        .cp-signal-row:last-child { border-bottom: none; }
        .cp-sev {
          font-family: var(--font-mono); font-size: 9px; letter-spacing: 0.16em;
          text-transform: uppercase; font-weight: 700; padding: 3px 8px; border-radius: 3px;
          color: #fff; text-align: center;
        }
      `}</style>

      <a href="#/find-carrier" className="cp-back"
         onClick={(e) => { e.preventDefault(); window.location.hash = "#/find-carrier"; }}>
        ← Verify carrier directory
      </a>

      <section className="cp-hero">
        <div className="cp-eyebrow">Carrier profile · live</div>
        <h1 className="cp-h1">{carrier.canonical_name}</h1>
        {carrier.legal_name && carrier.legal_name.toLowerCase() !== carrier.canonical_name.toLowerCase() && (
          <div style={{ fontSize: 14, color: "var(--ink-soft)", fontFamily: "var(--font-mono)" }}>
            Legal: {carrier.legal_name}{carrier.dba_name ? ` · dba ${carrier.dba_name}` : ""}
          </div>
        )}
        <div className="cp-meta">
          {carrier.dot_number && <span><strong style={{ color: "var(--ink)" }}>DOT</strong> {carrier.dot_number}</span>}
          {carrier.mc_number && <span><strong style={{ color: "var(--ink)" }}>MC</strong> {String(carrier.mc_number).replace(/^MC-/i, "")}</span>}
          {(carrier.hq_city || carrier.hq_state) && <span>{[carrier.hq_city, carrier.hq_state].filter(Boolean).join(", ")}</span>}
          {carrier.power_units != null && <span>{carrier.power_units} trucks · {carrier.drivers || "?"} drivers</span>}
        </div>
        <div className="cp-badges">
          {carrier.authority_status === "active" && <span className="cp-badge cp-badge-active">FMCSA active</span>}
          {carrier.authority_status === "inactive" && <span className="cp-badge cp-badge-flag">FMCSA inactive</span>}
          {carrier.safety_rating === "s" && <span className="cp-badge cp-badge-active">Safety: satis.</span>}
          {carrier.safety_rating === "c" && <span className="cp-badge cp-badge-warn">Safety: cond.</span>}
          {carrier.safety_rating === "u" && <span className="cp-badge cp-badge-flag">Safety: unsat.</span>}
          {caClass === "legitimate_dual"        && <span className="cp-badge cp-badge-active">CA MCP ✓</span>}
          {caClass === "ca_active_fmcsa_gap"    && <span className="cp-badge cp-badge-flag">CA / FMCSA mismatch</span>}
          {/* No-CA-permit badge intentionally suppressed — neutral signal, not a flag.
              Detail still rendered in the California section below for context. */}
          {bondRedFlag === "bond_cancellation_in_process" && <span className="cp-badge cp-badge-flag">Bond cancellation pending</span>}
          {bondRedFlag === "no_bond_on_file"              && <span className="cp-badge cp-badge-flag">No bond on file</span>}
          {bondRedFlag === "authority_lost"               && <span className="cp-badge cp-badge-flag">Authority lost</span>}
        </div>
      </section>

      <section className="cp-section">
        <div className="cp-grid-2">
          <div className="cp-card">
            <div className="cp-card-h">Fleet snapshot</div>
            <FleetSnapshot carrier={carrier} />
          </div>
          <div className="cp-card">
            <div className="cp-card-h">Operating footprint</div>
            <CarrierStateMap
              observedLanes={carrier.observed_lanes}
              hqState={carrier.hq_state}
              hasCaMcp={!!mcp}
              caMcpActive={mcp && mcp.authority_status === "Active"}
            />
          </div>
          <div className="cp-card">
            <div className="cp-card-h">FMCSA L&I bond status</div>
            {bond ? (
              <dl className="cp-kv">
                <dt>Authority status</dt><dd>{bond.authority_status || "—"}</dd>
                <dt>Authority type</dt><dd>{bond.authority_type || "—"}</dd>
                <dt>Bond type</dt><dd>{bond.bond_type || "—"}</dd>
                <dt>Bond filed</dt><dd>{bond.bond_filed ? "Yes" : "No"}</dd>
                <dt>Surety</dt><dd>{bond.surety_company || "—"}</dd>
                <dt>Cancellation</dt>
                <dd>{bond.cancellation_in_process
                  ? <strong style={{ color: "oklch(0.45 0.20 25)" }}>IN PROCESS</strong>
                  : "—"}</dd>
                <dt>Last scrape</dt><dd>{bond.observed_at ? new Date(bond.observed_at).toLocaleDateString() : "—"}</dd>
              </dl>
            ) : (
              <p style={{ color: "var(--ink-soft)", fontSize: 13, margin: 0 }}>
                Not yet scraped. Run <code>ingest-fmcsa-li-bonds.py</code> to populate.
              </p>
            )}
          </div>
          <div className="cp-card">
            <div className="cp-card-h">Observed lanes (DAT)</div>
            {Array.isArray(carrier.observed_lanes) && carrier.observed_lanes.length > 0 ? (
              <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                {carrier.observed_lanes.map((lane, i) => (
                  <span key={i} style={{ padding: "3px 8px", background: "var(--paper-2, #f7f4ee)", border: "1px solid var(--rule)", borderRadius: 3, fontFamily: "var(--font-mono)", fontSize: 11 }}>
                    {lane}
                  </span>
                ))}
              </div>
            ) : (
              <p style={{ color: "var(--ink-soft)", fontSize: 13, margin: 0 }}>No DAT lane observations yet.</p>
            )}
            <div style={{ marginTop: 12, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-soft)" }}>
              {carrier.observation_count || 1} observation{(carrier.observation_count || 1) === 1 ? "" : "s"} since first seen
              {carrier.first_seen && ` · ${new Date(carrier.first_seen).toLocaleDateString()}`}
            </div>
          </div>
        </div>
      </section>

      {signals.length > 0 && (
        <section className="cp-section">
          <div className="cp-section-h">
            Distress + risk signals · {signals.length} total
          </div>
          {signals.map((s, i) => {
            const sd = s.signal_data || {};
            const severity = sd.severity || sev(s.weight || 0);
            const dateStr = (sd.event_date || sd.filed_date || sd.notice_date || sd.effective_date
                             || (s.observed_at ? String(s.observed_at).slice(0, 10) : ""));
            return (
              <div key={i} className="cp-signal-row">
                <span className="cp-sev" style={{ background: sevColor(severity) }}>
                  {severity}
                </span>
                <div>
                  <strong>{sd.headline || s.signal_type}</strong>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-soft)", marginTop: 2 }}>
                    {SOURCE_LABELS[s.source] || s.source} · {dateStr}
                  </div>
                </div>
                <div style={{ textAlign: "right" }}>
                  {s.source_url && (
                    <a href={s.source_url} target="_blank" rel="noopener noreferrer"
                       style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink)" }}>
                      Source →
                    </a>
                  )}
                </div>
              </div>
            );
          })}
        </section>
      )}

      {/* Cross-link footer */}
      <section className="cp-section">
        <div className="cp-section-h">Connected surfaces</div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))", gap: 12 }}>
          <a href="#/find-carrier" onClick={(e) => { e.preventDefault(); window.location.hash = "#/find-carrier"; }}
             style={{ textDecoration: "none", color: "inherit", padding: 16, border: "1px solid var(--rule)", borderRadius: 6, background: "#fff", display: "block" }}>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-soft)", marginBottom: 6 }}>Verify carrier directory →</div>
            <div style={{ fontFamily: "var(--font-serif)", fontSize: 17, color: "var(--ink)", lineHeight: 1.3 }}>
              Browse the full roster, filter by red flags, find another carrier.
            </div>
          </a>
          <a href="#/risk-report" onClick={(e) => { e.preventDefault(); window.location.hash = "#/risk-report"; }}
             style={{ textDecoration: "none", padding: 16, border: "1px solid var(--ink)", borderRadius: 6, background: "var(--ink)", color: "var(--paper)", display: "block" }}>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "color-mix(in srgb, var(--paper) 70%, transparent)", marginBottom: 6 }}>Carrier Risk Report · $499 →</div>
            <div style={{ fontFamily: "var(--font-serif)", fontSize: 17, color: "var(--paper)", lineHeight: 1.3 }}>
              10-page deep-dive on this carrier — financial, regulatory, lane density, operational signal — delivered in 24 hours.
            </div>
          </a>
        </div>
      </section>
    </div>
  );
}

// =============================================================================
// FLEET SNAPSHOT — visual replacement for the old key-value FMCSA enrichment
// dl. Big numbers for the two facts that matter most (power units + drivers),
// a driver-to-truck ratio gauge that tells an operational story, and a row
// of stoplight indicators for authority / hazmat / safety rating.
// =============================================================================

function FleetSnapshot({ carrier }) {
  const c = carrier || {};
  const pu = c.power_units;
  const dr = c.drivers;
  const ratio = (pu && dr) ? (dr / pu) : null;
  // Driver-to-truck ratio interpretation (industry rules of thumb):
  //   <0.85 → likely owner-operators / unattended trucks (yellow)
  //   0.85–1.30 → standard solo-driver fleet (green)
  //   1.30–1.80 → significant team-driving operation (blue)
  //   >1.80 → dispatch density looks high; could indicate team / dedicated
  let ratioBand = null, ratioDesc = "";
  if (ratio != null) {
    if (ratio < 0.85)      { ratioBand = "low";  ratioDesc = "Idle-truck risk · drivers/truck"; }
    else if (ratio < 1.30) { ratioBand = "norm"; ratioDesc = "Solo-driver fleet · drivers/truck"; }
    else if (ratio < 1.80) { ratioBand = "team"; ratioDesc = "Team-driving operation · drivers/truck"; }
    else                   { ratioBand = "high"; ratioDesc = "Dense dispatch · drivers/truck"; }
  }
  const ratioColor = {
    low:  "#f5b942", norm: "#38b46e", team: "#5fa9ff", high: "#a07aff",
  }[ratioBand] || "var(--ink-soft)";

  // Stoplight indicators for the categorical signals.
  const auth = (c.authority_status || "").toLowerCase();
  const authState = auth === "active" ? "green" : auth ? "yellow" : "gray";
  const mcStatus  = (c.mc_status || "").toLowerCase();
  const mcState   = mcStatus.includes("active") ? "green" : mcStatus ? "yellow" : "gray";
  const safety    = (c.safety_rating || "").toLowerCase();
  const safetyState = safety === "satisfactory" ? "green"
                    : safety === "conditional" ? "yellow"
                    : safety === "unsatisfactory" ? "red"
                    : "gray";
  const hazState  = c.hazmat_indicator ? "green" : "gray";

  const dotColor = (s) => ({
    green: "#38b46e", yellow: "#f5b942", red: "#e85a5a", gray: "rgba(80,90,110,0.45)",
  }[s] || "rgba(80,90,110,0.45)");

  return (
    <div>
      {/* Two big-number tiles + ratio gauge */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginBottom: 12 }}>
        <div style={{ background: "rgba(56,180,110,0.06)", border: "1px solid rgba(56,180,110,0.20)",
                      borderRadius: 6, padding: "10px 12px" }}>
          <div style={{ fontSize: 10, letterSpacing: "0.10em", textTransform: "uppercase",
                        color: "var(--ink-soft)", fontWeight: 600 }}>Power units</div>
          <div style={{ fontSize: 28, fontWeight: 700, lineHeight: 1.1, marginTop: 2 }}>
            {pu != null ? pu.toLocaleString("en-US") : "—"}
          </div>
          <div style={{ fontSize: 11, color: "var(--ink-soft)", marginTop: 2 }}>tractors registered with FMCSA</div>
        </div>
        <div style={{ background: "rgba(95,169,255,0.06)", border: "1px solid rgba(95,169,255,0.20)",
                      borderRadius: 6, padding: "10px 12px" }}>
          <div style={{ fontSize: 10, letterSpacing: "0.10em", textTransform: "uppercase",
                        color: "var(--ink-soft)", fontWeight: 600 }}>Drivers</div>
          <div style={{ fontSize: 28, fontWeight: 700, lineHeight: 1.1, marginTop: 2 }}>
            {dr != null ? dr.toLocaleString("en-US") : "—"}
          </div>
          <div style={{ fontSize: 11, color: "var(--ink-soft)", marginTop: 2 }}>CDL holders on the carrier's roster</div>
        </div>
      </div>

      {ratio != null && (
        <div style={{ marginBottom: 12, padding: "8px 10px",
                      background: "rgba(15,23,42,0.04)", borderRadius: 6,
                      border: "1px solid rgba(15,23,42,0.08)" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline",
                        marginBottom: 4, fontSize: 11 }}>
            <span style={{ color: "var(--ink-soft)" }}>{ratioDesc}</span>
            <strong style={{ color: ratioColor, fontFamily: "var(--font-mono, ui-monospace, monospace)" }}>
              {ratio.toFixed(2)}
            </strong>
          </div>
          {/* Tiny gauge — 4 bands, dot at the carrier's position */}
          <div style={{ position: "relative", height: 6, borderRadius: 3, background: "rgba(80,90,110,0.18)" }}>
            <div style={{ position: "absolute", left: 0,         width: "20%", height: "100%",
                          background: "rgba(245,185,66,0.55)", borderRadius: "3px 0 0 3px" }} />
            <div style={{ position: "absolute", left: "20%",     width: "30%", height: "100%",
                          background: "rgba(56,180,110,0.55)" }} />
            <div style={{ position: "absolute", left: "50%",     width: "30%", height: "100%",
                          background: "rgba(95,169,255,0.55)" }} />
            <div style={{ position: "absolute", left: "80%",     width: "20%", height: "100%",
                          background: "rgba(160,122,255,0.55)", borderRadius: "0 3px 3px 0" }} />
            <div style={{ position: "absolute", top: -2, height: 10, width: 4,
                          left: `${Math.min(98, Math.max(0, (ratio / 2.5) * 100))}%`,
                          background: ratioColor, borderRadius: 2,
                          boxShadow: "0 1px 4px rgba(0,0,0,0.25)" }} />
          </div>
        </div>
      )}

      {/* Stoplight indicator strip */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(2, minmax(0,1fr))", gap: 6,
                    marginBottom: 8 }}>
        {[
          { label: "Operating authority",  state: authState,   value: c.authority_status || "—" },
          { label: "MC active",            state: mcState,     value: (c.mc_status || "—").replace(/_/g, " ") },
          { label: "Safety rating",        state: safetyState, value: c.safety_rating || "—" },
          { label: "Hazmat",               state: hazState,    value: c.hazmat_indicator ? "Authorized" : "—" },
        ].map((row) => (
          <div key={row.label} style={{ display: "flex", alignItems: "center", gap: 8,
                                        padding: "6px 8px", background: "rgba(15,23,42,0.03)",
                                        borderRadius: 5, fontSize: 11 }}>
            <span style={{ width: 9, height: 9, borderRadius: "50%", background: dotColor(row.state),
                           flexShrink: 0, boxShadow: `0 0 6px ${dotColor(row.state)}55` }} />
            <span style={{ color: "var(--ink-soft)", flex: 1, textTransform: "uppercase",
                           letterSpacing: "0.04em", fontWeight: 600 }}>{row.label}</span>
            <span style={{ fontWeight: 600, textAlign: "right" }}>{row.value}</span>
          </div>
        ))}
      </div>

      {c.fmcsa_enriched_at && (
        <div style={{ fontSize: 10, color: "var(--ink-soft)", textAlign: "right",
                      fontFamily: "var(--font-mono, ui-monospace, monospace)" }}>
          last FMCSA pull: {new Date(c.fmcsa_enriched_at).toLocaleDateString()}
        </div>
      )}
    </div>
  );
}

// =============================================================================
// CARRIER STATE MAP — replaces the old "California MCP cross-ref" box on the
// carrier profile. A continental-US hex map highlighting the states where
// this carrier has been observed running freight (from DAT observed_lanes
// + HQ state). California gets a special amber tint when there's an active
// CA Motor Carrier Permit on file. Clean, geographic, no wall of text.
// =============================================================================

// Hex layout — same logic as the dossier hex map. Each entry is
// [stateAbbr, col, row]. Even/odd-row offset gives the honeycomb stagger.
const STATEMAP_LAYOUT = [
  ["ME", 10, 0], ["VT", 9, 1], ["NH", 10, 1],
  ["WA", 1, 1], ["ID", 2, 2], ["MT", 3, 1], ["ND", 4, 1], ["MN", 5, 1],
  ["WI", 6, 1], ["MI", 7, 2], ["NY", 8, 2], ["MA", 9, 2], ["RI", 10, 2],
  ["OR", 1, 2], ["NV", 2, 3], ["WY", 3, 2], ["SD", 4, 2], ["IA", 5, 2],
  ["IL", 6, 3], ["IN", 7, 3], ["OH", 8, 3], ["PA", 9, 3], ["NJ", 10, 3],
  ["CT", 9, 4], ["CA", 1, 3], ["UT", 2, 4], ["CO", 3, 3], ["NE", 4, 3],
  ["MO", 5, 3], ["KY", 7, 4], ["WV", 8, 4], ["VA", 9, 5], ["MD", 10, 4],
  ["DE", 11, 4], ["AZ", 2, 5], ["NM", 3, 4], ["KS", 4, 4], ["AR", 5, 4],
  ["TN", 6, 4], ["NC", 8, 5], ["SC", 8, 6], ["DC", 11, 5],
  ["TX", 4, 5.5], ["OK", 4, 4.5], ["LA", 5, 5], ["MS", 6, 5], ["AL", 7, 5],
  ["GA", 8, 5.5], ["FL", 9, 6],
];

// City code → state lookup. DAT observed_lanes come back as compact codes
// like "LA-ATL" (Los Angeles → Atlanta) or "NY-CHI". We translate each
// origin/dest to a state so the corresponding hex lights up.
const STATEMAP_CITY_TO_STATE = {
  // West coast / SW
  LA: "CA", LAX: "CA", SF: "CA", SFO: "CA", SD: "CA", FRES: "CA", SAC: "CA",
  PHX: "AZ", TUS: "AZ", LAS: "NV", RNO: "NV", SLC: "UT",
  PDX: "OR", SEA: "WA", SPO: "WA",
  // Mountain
  DEN: "CO", BIL: "MT", BOI: "ID",
  // Texas / SW
  DAL: "TX", DFW: "TX", HOU: "TX", AUS: "TX", SAT: "TX", ELP: "TX",
  OKC: "OK", TUL: "OK", LIT: "AR", MSY: "LA", BTR: "LA", JAN: "MS",
  // Midwest
  CHI: "IL", ORD: "IL", STL: "MO", MCI: "MO", KCM: "MO", MEM: "TN",
  NSH: "TN", IND: "IN", DET: "MI", DTW: "MI", CLE: "OH", CMH: "OH", CIN: "OH",
  MKE: "WI", MSP: "MN", DSM: "IA", FAR: "ND", OMA: "NE",
  // Southeast
  ATL: "GA", MIA: "FL", JAX: "FL", TPA: "FL", ORL: "FL",
  CLT: "NC", RDU: "NC", GSO: "NC", BHM: "AL", HSV: "AL", CHA: "TN", KNX: "TN",
  CHS: "SC", GSP: "SC", LOU: "KY", LEX: "KY",
  // Northeast / Mid-Atl
  NY: "NY", NYC: "NY", BUF: "NY", ALB: "NY", PHL: "PA", PIT: "PA",
  BOS: "MA", PVD: "RI", HFD: "CT", BWI: "MD", DCA: "DC", IAD: "VA",
  RIC: "VA", ROA: "VA", CHO: "VA", NOR: "VA",
  PRT: "ME", BUR: "VT", MHT: "NH", NWK: "NJ",
  // Plains
  ICT: "KS", FAY: "AR", SGF: "MO", LIN: "NE", FSD: "SD",
};

function statemapLaneStates(lanes) {
  if (!Array.isArray(lanes)) return new Set();
  const out = new Set();
  for (const lane of lanes) {
    if (typeof lane !== "string") continue;
    const parts = lane.toUpperCase().split(/[-→/]/).map((s) => s.trim()).filter(Boolean);
    for (const code of parts) {
      // Already a 2-letter state code? Trust it.
      if (code.length === 2 && /^[A-Z]{2}$/.test(code)) {
        out.add(code);
      } else if (STATEMAP_CITY_TO_STATE[code]) {
        out.add(STATEMAP_CITY_TO_STATE[code]);
      }
    }
  }
  return out;
}

function CarrierStateMap({ observedLanes, hqState, hasCaMcp, caMcpActive }) {
  const laneStates = statemapLaneStates(observedLanes);
  if (hqState) laneStates.add(String(hqState).toUpperCase());

  const HEX_W = 38, HEX_H = 44, ROW_H = 34, COL_W = 38;
  const cols = Math.max(...STATEMAP_LAYOUT.map((s) => s[1])) + 1;
  const rows = Math.max(...STATEMAP_LAYOUT.map((s) => s[2])) + 1;
  const W = cols * COL_W + COL_W;
  const H = rows * ROW_H + HEX_H;

  function hexPath(cx, cy, w, h) {
    const dx = w / 2, dy = h / 2;
    return `M ${cx - dx} ${cy - dy/2} L ${cx} ${cy - dy} L ${cx + dx} ${cy - dy/2} L ${cx + dx} ${cy + dy/2} L ${cx} ${cy + dy} L ${cx - dx} ${cy + dy/2} Z`;
  }

  function fillFor(abbr) {
    const lit = laneStates.has(abbr);
    const isHQ = abbr === (hqState || "").toUpperCase();
    if (abbr === "CA" && hasCaMcp) {
      // CA permit-on-file gets a distinct amber tint regardless of lane
      // observation, so the editor can read "they have CA authority" at
      // a glance.
      return caMcpActive ? "#f5b942" : "rgba(245,185,66,0.35)";
    }
    if (isHQ) return "#0b6b3a";          // HQ state — deepest green
    if (lit) return "rgba(56,180,110,0.78)";
    return "rgba(80,90,110,0.18)";
  }
  function strokeFor(abbr) {
    const isHQ = abbr === (hqState || "").toUpperCase();
    if (isHQ) return "#1a8c4f";
    if (abbr === "CA" && hasCaMcp) return "#a17f06";
    if (laneStates.has(abbr)) return "rgba(56,180,110,1)";
    return "rgba(80,90,110,0.30)";
  }
  function textFill(abbr) {
    const lit = laneStates.has(abbr) || (abbr === "CA" && hasCaMcp) || abbr === (hqState || "").toUpperCase();
    return lit ? "#0a1224" : "rgba(15,23,42,0.40)";
  }

  const litCount = laneStates.size;

  return (
    <div>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="auto" style={{ display: "block" }}>
        {STATEMAP_LAYOUT.map(([abbr, col, row]) => {
          const cx = col * COL_W + COL_W / 2 + (Math.floor(row) % 2 === 0 ? 0 : COL_W / 2);
          const cy = row * ROW_H + HEX_H / 2;
          return (
            <g key={abbr}>
              <title>{abbr}{abbr === (hqState || "").toUpperCase() ? " · HQ" : ""}{abbr === "CA" && hasCaMcp ? " · CA MCP" : ""}{laneStates.has(abbr) ? " · observed lane" : ""}</title>
              <path d={hexPath(cx, cy, HEX_W, HEX_H)} fill={fillFor(abbr)} stroke={strokeFor(abbr)} strokeWidth="1" />
              <text x={cx} y={cy + 3.5} textAnchor="middle"
                    style={{ fontFamily: '"Helvetica Neue", Helvetica, Arial, sans-serif',
                             fontSize: 10, fontWeight: 700, fill: textFill(abbr),
                             pointerEvents: "none" }}>
                {abbr}
              </text>
            </g>
          );
        })}
      </svg>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 12, alignItems: "center",
                    marginTop: 8, fontSize: 11, color: "var(--ink-soft)" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
          <span style={{ width: 10, height: 10, borderRadius: 2, background: "#0b6b3a" }} /> HQ state
        </span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
          <span style={{ width: 10, height: 10, borderRadius: 2, background: "rgba(56,180,110,0.78)" }} />
          Observed lane state{litCount === 1 ? "" : "s"} ({Math.max(0, litCount - (hqState ? 1 : 0))})
        </span>
        {hasCaMcp && (
          <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
            <span style={{ width: 10, height: 10, borderRadius: 2,
                           background: caMcpActive ? "#f5b942" : "rgba(245,185,66,0.35)" }} />
            CA Motor Carrier Permit {caMcpActive ? "(active)" : "(on file)"}
          </span>
        )}
      </div>
      <p style={{ fontSize: 11, color: "var(--ink-soft)", lineHeight: 1.5,
                  marginTop: 8, marginBottom: 0 }}>
        Coverage = HQ state + states inferred from observed DAT lane pairs.
        {!hasCaMcp && " No CA Motor Carrier Permit on file — neutral signal; most US carriers don't run California freight."}
      </p>
    </div>
  );
}

window.DatCarrierProfile = DatCarrierProfile;
