// Carrier dossier page — /#/c/<slug>
//
// Implements the 12-block bento doctrine in docs/dossier-page-doctrine.md.
// Driven by GET /api/carrier-detail?slug=<slug>, joining carriers_top100
// with the latest matching research_dossiers row.
//
// Provisional flags per principle #7: any block whose data is mocked
// (per-state miles, driver count, OOS rate, fleet equipment mix) wears a
// "Provisional · live SAFER feed pending" badge so honesty stays loud.

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

// ---------------------------------------------------------------------------
// Hex US map — 50-state geographic centerpiece per principle #4.
//
// Hex tiles avoid the "small states disappear" problem of a real choropleth
// while still feeling geographic. Sequential blue scale, 5 buckets max.
// Companion top-states list is rendered alongside in block H.
// ---------------------------------------------------------------------------

const HEX_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], ["OK", 4, 5.5], ["LA", 5, 5], ["MS", 6, 5], ["AL", 7, 5],
  ["GA", 8, 5.5], ["FL", 9, 6],
];
// Note: TX and OK overlap the same column on purpose for simplicity; tweaks
// will come once we have real data flowing. The hex layout is intentionally
// a v1 approximation — it reads geographically without 50 detailed SVG paths.

const STATE_NAMES = {
  AL:"Alabama", AZ:"Arizona", AR:"Arkansas", CA:"California",
  CO:"Colorado", CT:"Connecticut", DE:"Delaware", DC:"District of Columbia",
  FL:"Florida", GA:"Georgia", ID:"Idaho", IL:"Illinois",
  IN:"Indiana", IA:"Iowa", KS:"Kansas", KY:"Kentucky", LA:"Louisiana",
  ME:"Maine", MD:"Maryland", MA:"Massachusetts", MI:"Michigan", MN:"Minnesota",
  MS:"Mississippi", MO:"Missouri", MT:"Montana", NE:"Nebraska", NV:"Nevada",
  NH:"New Hampshire", NJ:"New Jersey", NM:"New Mexico", NY:"New York",
  NC:"North Carolina", ND:"North Dakota", OH:"Ohio", OK:"Oklahoma",
  OR:"Oregon", PA:"Pennsylvania", RI:"Rhode Island", SC:"South Carolina",
  SD:"South Dakota", TN:"Tennessee", TX:"Texas", UT:"Utah", VT:"Vermont",
  VA:"Virginia", WA:"Washington", WV:"West Virginia", WI:"Wisconsin", WY:"Wyoming",
};

// Deterministic mock per-state mileage. Until the FMCSA SAFER scraper is
// wired, we synthesize a plausible distribution from rank + segment + HQ
// state so the choropleth has shape, with an honest provisional badge.
function mockStateDistribution(carrier) {
  const rank = carrier.rank || 100;
  const hq = (carrier.hq_state || "").toUpperCase();
  const segment = (carrier.segment || "").toLowerCase();
  // Larger carriers spread further; smaller ones cluster around HQ.
  const reach = Math.min(50, Math.max(8, Math.round(60 - rank * 0.5)));
  // Seed from the slug so the distribution is stable across reloads.
  let seed = 0;
  for (const c of carrier.slug || "x") seed = (seed * 31 + c.charCodeAt(0)) >>> 0;
  function rand() { seed = (seed * 1103515245 + 12345) >>> 0; return (seed >>> 16) / 65535; }

  const states = Object.keys(STATE_NAMES);
  const dist = {};
  // HQ state always heaviest.
  if (STATE_NAMES[hq]) dist[hq] = 80 + rand() * 20;

  // Segment-based affinity for large freight states.
  const tlAffinity = ["TX","CA","IL","OH","PA","GA","FL","IN","TN","NC"];
  const intermodalAffinity = ["IL","CA","TX","NJ","GA","OH","TN","IN"];
  const ltlAffinity = ["TX","CA","FL","GA","IL","OH","PA","NC","NY","TN"];
  const reeferAffinity = ["CA","FL","TX","WI","WA","GA","MI","MN"];
  let aff = tlAffinity;
  if (segment.includes("intermodal")) aff = intermodalAffinity;
  else if (segment.includes("ltl") || segment === "parcel") aff = ltlAffinity;
  else if (segment.includes("reefer")) aff = reeferAffinity;
  for (const s of aff) {
    if (!dist[s]) dist[s] = 30 + rand() * 50;
  }

  // Random sprinkle for the rest of the reach.
  const remaining = states.filter((s) => !dist[s]);
  const pickCount = Math.min(reach, remaining.length);
  for (let i = 0; i < pickCount; i++) {
    const idx = Math.floor(rand() * remaining.length);
    const s = remaining.splice(idx, 1)[0];
    dist[s] = 5 + rand() * 25;
  }
  return dist;
}

function HexUSMap({ values, accentColor }) {
  const [hover, setHover] = useStateCD(null);
  const sortedVals = Object.values(values).sort((a, b) => b - a);
  const max = sortedVals[0] || 1;
  // Five-class quantile buckets per principle #4 (max 5 classes).
  const breaks = [0.04, 0.20, 0.40, 0.65, 1.0].map((p) => p * max);
  function colorFor(v) {
    if (v == null) return "rgba(255,255,255,0.05)";
    const t = v / max;
    if (t < breaks[0] / max) return "rgba(95,169,255,0.10)";
    if (t < breaks[1] / max) return "rgba(95,169,255,0.28)";
    if (t < breaks[2] / max) return "rgba(95,169,255,0.50)";
    if (t < breaks[3] / max) return "rgba(95,169,255,0.75)";
    return "rgba(95,169,255,1.00)";
  }

  // Hex sizing
  const HEX_W = 56, HEX_H = 64, ROW_H = 50, COL_W = 56;
  const cols = Math.max(...HEX_LAYOUT.map((s) => s[1])) + 1;
  const rows = Math.max(...HEX_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`;
  }

  return (
    <div style={{ position: "relative" }}>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="auto" style={{ display: "block" }}>
        {HEX_LAYOUT.map(([abbr, col, row]) => {
          const v = values[abbr];
          const cx = col * COL_W + COL_W / 2 + (row % 2 === 0 ? 0 : COL_W / 2);
          const cy = row * ROW_H + HEX_H / 2;
          const isHover = hover === abbr;
          return (
            <g
              key={abbr}
              onMouseEnter={() => setHover(abbr)}
              onMouseLeave={() => setHover(null)}
              style={{ cursor: v != null ? "pointer" : "default" }}
            >
              <path
                d={hexPath(cx, cy, HEX_W, HEX_H)}
                fill={colorFor(v)}
                stroke={isHover ? "#5fa9ff" : "rgba(255,255,255,0.18)"}
                strokeWidth={isHover ? 2.5 : 1}
              />
              <text
                x={cx} y={cy + 5}
                textAnchor="middle"
                style={{
                  fontFamily: '"Helvetica Neue", Helvetica, Arial, sans-serif',
                  fontSize: 14, fontWeight: 600, fill: "#fff",
                  pointerEvents: "none",
                  opacity: v != null ? 0.95 : 0.35,
                }}
              >{abbr}</text>
            </g>
          );
        })}
      </svg>
      {hover && (
        <div style={{
          position: "absolute", top: 8, right: 8, padding: "8px 12px",
          background: "rgba(10,18,36,0.92)", color: "#fff", fontSize: 13,
          borderRadius: 4, fontFamily: '"Helvetica Neue", sans-serif',
          border: "1px solid rgba(95,169,255,0.4)",
        }}>
          <div style={{ fontWeight: 600 }}>{STATE_NAMES[hover] || hover}</div>
          <div style={{ opacity: 0.7, fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em" }}>
            {values[hover] != null ? `${Math.round(values[hover])}M est. miles` : "no signal"}
          </div>
        </div>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Verdict derivation — read distress signals from the curated `notes` field
// and the optional research_dossiers signals_json. Per doctrine #2 the
// verdict sits in the F-pattern hot spot (top-right) of block B.
// ---------------------------------------------------------------------------

// TerminalMap — Leaflet pin map of OSM-mapped carrier terminals. Uses
// the global Leaflet (window.L) already loaded in index.html for the
// dashboard maps. Renders pins with popups for each terminal; auto-fits
// bounds to show all pins. Returns null if Leaflet isn't loaded yet
// (graceful — the address list still renders next to it).
function TerminalMap({ terminals }) {
  const mapRef = React.useRef(null);
  const containerRef = React.useRef(null);

  React.useEffect(() => {
    if (!containerRef.current) return;
    if (!window.L) return;
    if (mapRef.current) {
      // Already initialized — skip
      return;
    }
    const map = window.L.map(containerRef.current, {
      zoomControl: true,
      attributionControl: true,
      scrollWheelZoom: false,
    }).setView([39.5, -98.35], 4); // continental US center
    window.L.tileLayer(
      "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
      { attribution: "© OpenStreetMap", maxZoom: 12 }
    ).addTo(map);

    const valid = terminals.filter((t) => t.lat != null && t.lng != null);
    const markers = valid.map((t) => {
      const m = window.L.circleMarker([t.lat, t.lng], {
        radius: 6,
        fillColor: "#5fa9ff",
        color: "#fff",
        weight: 1.5,
        fillOpacity: 0.9,
      });
      const popup = `<strong>${(t.name || "Terminal").replace(/</g, "&lt;")}</strong>${
        t.address ? `<br><span style="opacity:0.75">${t.address.replace(/</g, "&lt;")}</span>` : ""
      }`;
      m.bindPopup(popup);
      m.addTo(map);
      return m;
    });

    if (markers.length > 0) {
      const group = window.L.featureGroup(markers);
      try {
        map.fitBounds(group.getBounds().pad(0.15));
      } catch (_) { /* single-pin or bad bounds — leave default view */ }
    }

    mapRef.current = map;

    return () => {
      try { map.remove(); } catch (_) {}
      mapRef.current = null;
    };
  }, [terminals]);

  return (
    <div
      ref={containerRef}
      style={{
        width: "100%", height: 380, borderRadius: 8, overflow: "hidden",
        background: "#0a1224",
      }}
    />
  );
}

// Editorial gate: an explicit verdict_override always wins. Without one,
// the heuristic runs but Distress is downgraded to Watch — Distress
// flags require human approval (defamation risk) via /#/admin → Verdicts.
function deriveVerdict(carrier, dossier) {
  // Verdict policy (2026-05): tier strictly from VERIFIED, LINKED public-
  // record evidence. Never from heuristic phrase matches on our own
  // seed-file notes (legal exposure), never from editorial overrides
  // (band-aids that hide the real issue). If we can't link a source,
  // we don't flag.
  //
  // Acceptable evidence for an upgraded tier:
  //   - dossier.signals_json — research workbench output, every signal
  //     carries a source URL on SEC EDGAR
  //   - (future) joins to bankruptcy_filings / nlrb_filings /
  //     warn_notices / osha_injury_reports / intel_alerts by carrier
  //     name match, each row carrying its own source URL
  //
  // Default for every carrier is "No flags." That's honest: we have no
  // public-record red flag we can cite. The "Verify it yourself" panel
  // beneath the verdict keeps public records one click away regardless.
  let tier = "no_flags";
  let label = "○ No flags";
  let why = "No public-record red flag found in the last 24 months. Verify via SEC EDGAR / FMCSA / CourtListener links below.";
  let trustScore = 78;

  // Research-dossier critical signals — already linked to SEC EDGAR
  // filings with severity classification, so the "Watch" claim here is
  // backed by clickable source documents in the carrier's research
  // dossier. Distress would require explicit human review.
  const sigs = dossier && dossier.signals_json;
  if (Array.isArray(sigs)) {
    const hasCritical = sigs.some((s) => (s.severity || "").toLowerCase() === "critical");
    if (hasCritical) {
      tier = "watch";
      label = "⚠ Watch";
      why = "SEC EDGAR critical event on the public record. See research signals below for the source filing.";
      trustScore = 58;
    }
  }

  return { tier, label, why, trustScore };
}

// ---------------------------------------------------------------------------
// Number formatters
// ---------------------------------------------------------------------------

function fmtRevenue(usd) {
  if (!usd) return "Not publicly disclosed";
  if (usd >= 1e9) return `$${(usd / 1e9).toFixed(2)}B`;
  if (usd >= 1e6) return `$${(usd / 1e6).toFixed(1)}M`;
  return `$${(usd / 1e3).toFixed(0)}K`;
}

function fmtFleet(n) {
  if (!n) return "Not disclosed";
  return n.toLocaleString("en-US");
}

function fmtAge(carrier) {
  if (!carrier.founded) return "—";
  const yrs = (new Date()).getFullYear() - carrier.founded;
  return `${carrier.founded} · ${yrs} yrs`;
}

// ---------------------------------------------------------------------------
// Page
// ---------------------------------------------------------------------------

function CarrierDetailPage({ slug, onNav }) {
  const [data, setData] = useStateCD(null);
  const [error, setError] = useStateCD(null);
  const [loading, setLoading] = useStateCD(true);
  const [updatedAgo, setUpdatedAgo] = useStateCD("just now");

  useEffectCD(() => {
    if (!slug) return;
    let cancelled = false;
    setLoading(true);
    setError(null);
    fetch(`/api/carrier-detail?slug=${encodeURIComponent(slug)}`)
      .then(async (r) => {
        if (cancelled) return;
        if (r.status === 404) {
          setError("not_found");
          setData(null);
          setLoading(false);
          return;
        }
        if (!r.ok) {
          setError(`HTTP ${r.status}`);
          setLoading(false);
          return;
        }
        const j = await r.json();
        setData(j);
        setLoading(false);
      })
      .catch((e) => {
        if (cancelled) return;
        setError(String(e.message || e));
        setLoading(false);
      });
    return () => { cancelled = true; };
  }, [slug]);

  // "Updated 4m ago" freshness signal per doctrine #6.
  useEffectCD(() => {
    if (!data) return;
    const tick = () => {
      const start = Date.now();
      const fmt = () => {
        const s = Math.floor((Date.now() - start) / 1000);
        if (s < 60) return s < 5 ? "just now" : `${s}s ago`;
        const m = Math.floor(s / 60);
        return `${m}m ago`;
      };
      setUpdatedAgo(fmt());
    };
    tick();
    const id = setInterval(tick, 30000);
    return () => clearInterval(id);
  }, [data]);

  const verdict = useMemoCD(
    () => (data ? deriveVerdict(data.carrier, data.dossier) : null),
    [data]
  );
  // Prefer real FMCSA per-state inspection data when present (from
  // fmcsa_carrier_state_inspections, populated by ingest-fmcsa-state-
  // inspections.py). Falls back to the legacy synthesized distribution
  // when the table has no rows for this USDOT yet — the "Illustrative"
  // badge stays intact in that case.
  const stateValues = useMemoCD(() => {
    if (!data) return {};
    const real = data.state_inspections && data.state_inspections.by_state;
    if (real && Object.keys(real).length > 0) {
      // Map { state: {inspections, ...} } → { state: number } for the hex map.
      const out = {};
      for (const [s, v] of Object.entries(real)) out[s] = v.inspections || 0;
      return out;
    }
    return mockStateDistribution(data.carrier);
  }, [data]);
  const isRealStateData = useMemoCD(
    () => !!(data && data.state_inspections && data.state_inspections.by_state &&
             Object.keys(data.state_inspections.by_state).length > 0),
    [data]
  );
  const topStates = useMemoCD(() => {
    const entries = Object.entries(stateValues).sort((a, b) => b[1] - a[1]);
    return entries.slice(0, 8);
  }, [stateValues]);

  if (!slug) {
    return (
      <div style={pageStyle}>
        <div style={{ padding: 64, textAlign: "center", color: "#fff" }}>
          <h1 style={{ fontSize: 32 }}>Pick a carrier</h1>
          <p style={{ opacity: 0.7 }}>This page expects a slug — try /#/c/ups or /#/c/jb-hunt.</p>
          <button onClick={() => onNav && onNav("home")} style={btnGhost}>← Home</button>
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div style={pageStyle}>
        <div style={{ padding: 80, textAlign: "center", color: "#fff", opacity: 0.6 }}>
          Loading dossier for <code>{slug}</code>…
        </div>
      </div>
    );
  }

  if (error === "not_found") {
    return (
      <div style={pageStyle}>
        <div style={{ padding: 64, textAlign: "center", color: "#fff", maxWidth: 560, margin: "0 auto" }}>
          <h1 style={{ fontSize: 32, marginBottom: 12 }}>No carrier matched <code>{slug}</code></h1>
          <p style={{ opacity: 0.7, marginBottom: 24 }}>
            We currently cover the Top 100 U.S. for-hire carriers. Try a slug like{" "}
            <code>ups</code>, <code>fedex-corp</code>, <code>jb-hunt</code>, <code>xpo</code>,{" "}
            <code>old-dominion</code>, <code>hub-group</code>, or <code>knight-swift</code>.
          </p>
          <button onClick={() => onNav && onNav("home")} style={btnGhost}>← Home</button>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div style={pageStyle}>
        <div style={{ padding: 64, color: "#fff", maxWidth: 560, margin: "0 auto" }}>
          <h1 style={{ fontSize: 28 }}>Couldn't load this dossier</h1>
          <p style={{ opacity: 0.7 }}>{error}</p>
          <button onClick={() => onNav && onNav("home")} style={btnGhost}>← Home</button>
        </div>
      </div>
    );
  }

  const c = data.carrier;
  const verdictColor =
    verdict.tier === "distress" ? "#ff6868" :
    verdict.tier === "watch" ? "#ffb84d" : "#5fd9a8";

  // Build the live ticker — Bloomberg-style scrolling strip across the
  // top of every dossier. Pulls per-carrier facts (USDOT, fleet, rev,
  // verdict, sealed-intel counts) plus a few platform-level facts. Same
  // CSS pattern as the page-home BigRadar ticker.
  const tickerItems = [
    `📋 ${c.name.toUpperCase()}`,
    c.usdot ? `USDOT ${c.usdot}` : null,
    c.mc_number ? `${c.mc_number}` : null,
    c.public && c.ticker ? `${c.ticker} · LISTED` : null,
    c.fleet_size_estimate ? `🚛 ${c.fleet_size_estimate.toLocaleString()} POWER UNITS` : null,
    c.revenue_2024_usd ? `💰 ${fmtRevenue(c.revenue_2024_usd)} 2024` : null,
    c.rank ? `TT 2024 RANK #${c.rank}` : null,
    `${verdict.tier === "distress" ? "▲" : verdict.tier === "watch" ? "⚠" : "○"} ${verdict.label.replace(/^[▲⚠○]\s*/, "").toUpperCase()} · TRUST ${verdict.trustScore}/100`,
    data.sealed_intel ? `🔒 ${data.sealed_intel.total_24mo || 0} VERIFIED INTEL ROWS · 24MO` : null,
    data.sealed_intel ? `📡 ${data.sealed_intel.recent_90d || 0} RECENT SIGNAL · 90D` : null,
    `LIVE · UPDATED ${updatedAgo.toUpperCase()}`,
  ].filter(Boolean);

  return (
    <div style={pageStyle}>
      <style>{`
        .dos-ticker {
          background: linear-gradient(180deg, rgba(15,30,60,0.95), rgba(10,18,36,0.95));
          border-bottom: 1px solid rgba(95,169,255,0.30);
          overflow: hidden; position: relative;
        }
        .dos-ticker-inner {
          display: flex; gap: 28px; overflow: hidden; white-space: nowrap;
          padding: 10px 0;
          font-family: ui-monospace, "SF Mono", Menlo, Monaco, Consolas, monospace;
          font-size: 12px; letter-spacing: 0.06em;
          color: #5fa9ff;
          mask-image: linear-gradient(90deg, transparent 0, #000 4%, #000 96%, transparent 100%);
        }
        .dos-ticker-track {
          display: inline-flex; gap: 28px; animation: dos-ticker-scroll 80s linear infinite;
          flex-shrink: 0;
        }
        @keyframes dos-ticker-scroll { to { transform: translateX(-50%); } }
        .dos-ticker-item {
          display: inline-flex; align-items: center; flex-shrink: 0;
          font-weight: 600;
        }
        .dos-ticker-sep {
          color: rgba(95,169,255,0.4); margin: 0 14px;
        }
      `}</style>

      <div className="dos-ticker">
        <div className="dos-ticker-inner">
          <div className="dos-ticker-track">
            {[...tickerItems, ...tickerItems].map((t, i) => (
              <span key={i} className="dos-ticker-item">
                {t}
                <span className="dos-ticker-sep">·</span>
              </span>
            ))}
          </div>
        </div>
      </div>

      <div style={{ maxWidth: 1320, margin: "0 auto", padding: "24px 24px 80px" }}>

        {/* freshness + breadcrumb */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16, color: "rgba(255,255,255,0.65)", fontSize: 13 }}>
          <div>
            <a href="#/" style={linkStyle}>← Shipping Clarity</a>
            <span style={{ margin: "0 8px", opacity: 0.4 }}>/</span>
            <span style={{ opacity: 0.7 }}>Carrier dossier</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ width: 8, height: 8, borderRadius: 999, background: "#5fd9a8" }} />
            Updated {updatedAgo}
          </div>
        </div>

        {/* ---- Row 1: A (identity stack) + B (verdict) ----
             Identity column is a flex-column wrapper holding the main
             identity card on top + a "Quick read" editorial-summary card
             below, so the left column fills naturally to match the
             verdict-card height (which is usually taller because of the
             Verify-it-yourself link list). ---- */}
        <div style={gridRow(["8fr","4fr"])}>
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <Card>
            <Eyebrow>CARRIER IDENTITY</Eyebrow>
            <h1 style={{ fontSize: 44, fontWeight: 800, lineHeight: 1.05, letterSpacing: "-0.02em", margin: "8px 0 4px" }}>
              {c.name}
            </h1>
            {c.parent && c.parent !== c.name && (
              <div style={{ fontSize: 16, opacity: 0.55, marginBottom: 16 }}>{c.parent}</div>
            )}
            <div style={{ display: "flex", flexWrap: "wrap", gap: "10px 24px", marginTop: 14, fontSize: 14 }}>
              {c.usdot && <Attr label="USDOT" value={c.usdot} />}
              {c.mc_number && <Attr label="MC#" value={c.mc_number.replace(/^MC-?/, "")} />}
              {c.hq_city && <Attr label="HQ" value={`${c.hq_city}, ${c.hq_state || ""}`} />}
              {c.segment && <Attr label="Segment" value={c.segment.toUpperCase()} />}
              {c.ownership && <Attr label="Ownership" value={c.ownership.toUpperCase()} />}
              {c.founded && <Attr label="Founded" value={fmtAge(c)} />}
              {c.public && c.ticker && <Attr label="Ticker" value={c.ticker} />}
              {c.rank && <Attr label="TT 2024 rank" value={`#${c.rank}`} />}
            </div>

            {/* Contact block. We surface two sources side-by-side when
                both are present, because they answer different questions:

                  General contact (Google Places) — the customer-facing
                  phone/website. The number a shipper would actually
                  dial. Populated by enrich-carriers-google-places.py.

                  FMCSA-record contact — the legal-record contact filed
                  with the regulator. Often a back-office or registered-
                  agent line, NOT a dispatch number. Populated by
                  enrich-carriers-top100-contact.py.

                When only one is present we still show it, clearly
                labeled. The disclaimer under each keeps the source
                honest. */}
            {(c.general_phone || c.website_url || c.places_address) && (
              <div style={{
                marginTop: 22, paddingTop: 18,
                borderTop: "1px solid rgba(255,255,255,0.08)",
              }}>
                <div style={{
                  fontSize: 11, textTransform: "uppercase", letterSpacing: "0.16em",
                  color: "#9eff9e", fontWeight: 600, marginBottom: 10,
                }}>General contact</div>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: "10px 24px", fontSize: 14 }}>
                  {c.general_phone && (
                    <Attr label="Phone"
                          value={
                            <a href={`tel:${c.general_phone.replace(/[^\d+]/g, "")}`}
                               style={{ color: "#fff", textDecoration: "none", borderBottom: "1px dotted rgba(255,255,255,0.4)" }}>
                              {c.general_phone}
                            </a>
                          } />
                  )}
                  {c.website_url && (
                    <Attr label="Website"
                          value={
                            <a href={c.website_url} target="_blank" rel="noopener noreferrer"
                               style={{ color: "#fff", textDecoration: "none", borderBottom: "1px dotted rgba(255,255,255,0.4)" }}>
                              {c.website_url.replace(/^https?:\/\//, "")}
                            </a>
                          } />
                  )}
                  {c.general_email && (
                    <Attr label="Email"
                          value={
                            <a href={`mailto:${c.general_email}`}
                               style={{ color: "#fff", textDecoration: "none", borderBottom: "1px dotted rgba(255,255,255,0.4)" }}>
                              {c.general_email}
                            </a>
                          } />
                  )}
                  {c.places_address && (
                    <Attr label="Address" value={c.places_address} />
                  )}
                </div>
                <div style={{ fontSize: 11, opacity: 0.5, marginTop: 10, lineHeight: 1.5 }}>
                  Customer-facing contact via Google Places{c.contact_refreshed_at ? `, refreshed ${new Date(c.contact_refreshed_at).toLocaleDateString()}` : ""}.
                  {c.places_business_status === "CLOSED_PERMANENTLY" && " · Listed CLOSED PERMANENTLY on Google."}
                  {c.places_business_status === "CLOSED_TEMPORARILY" && " · Listed CLOSED TEMPORARILY on Google."}
                </div>
              </div>
            )}

            {(c.phy_address || c.phone || c.email_general) && (
              <div style={{
                marginTop: 22, paddingTop: 18,
                borderTop: "1px solid rgba(255,255,255,0.08)",
              }}>
                <div style={{
                  fontSize: 11, textTransform: "uppercase", letterSpacing: "0.16em",
                  color: "#5fa9ff", fontWeight: 600, marginBottom: 10,
                }}>FMCSA-record contact</div>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: "10px 24px", fontSize: 14 }}>
                  {c.phy_address && (
                    <Attr label="Address"
                          value={[c.phy_address, [c.phy_city, c.phy_state, c.phy_zip].filter(Boolean).join(" ")]
                                  .filter(Boolean).join(" · ")} />
                  )}
                  {c.phone && (
                    <Attr label="Phone"
                          value={
                            <a href={`tel:${c.phone.replace(/[^\d+]/g, "")}`}
                               style={{ color: "#fff", textDecoration: "none", borderBottom: "1px dotted rgba(255,255,255,0.4)" }}>
                              {c.phone}
                            </a>
                          } />
                  )}
                  {c.email_general && (
                    <Attr label="Email"
                          value={
                            <a href={`mailto:${c.email_general}`}
                               style={{ color: "#fff", textDecoration: "none", borderBottom: "1px dotted rgba(255,255,255,0.4)" }}>
                              {c.email_general}
                            </a>
                          } />
                  )}
                </div>
                <div style={{ fontSize: 11, opacity: 0.5, marginTop: 10, lineHeight: 1.5 }}>
                  Public-record contact filed with FMCSA — typically a back-office or registered-agent line, not a dispatch number. Verified via FMCSA QCMobile{c.fmcsa_enriched_at ? ` on ${new Date(c.fmcsa_enriched_at).toLocaleDateString()}` : ""}.
                </div>
              </div>
            )}
          </Card>

          {/* QUICK READ — fills the gap below the identity card on the
              left column. Pulls editorial summary from the carrier's
              notes field plus 3 high-value stat tiles that don't
              duplicate the identity attrs above. */}
          <Card style={{ borderLeft: "4px solid #5fa9ff" }}>
            <Eyebrow>QUICK READ</Eyebrow>
            <div style={{
              display: "grid",
              gridTemplateColumns: "repeat(3, minmax(0,1fr))",
              gap: 12, marginTop: 12, marginBottom: 16,
            }}>
              <div style={{
                background: "rgba(95,169,255,0.08)",
                border: "1px solid rgba(95,169,255,0.20)",
                borderRadius: 8, padding: "12px 14px",
              }}>
                <div style={{ fontSize: 10, letterSpacing: "0.10em",
                              textTransform: "uppercase", opacity: 0.55,
                              fontWeight: 600 }}>
                  Fleet
                </div>
                <div style={{ fontSize: 26, fontWeight: 800, lineHeight: 1.1, marginTop: 2 }}>
                  {fmtFleet(c.fleet_size_estimate)}
                </div>
                <div style={{ fontSize: 11, opacity: 0.55, marginTop: 2 }}>power units</div>
              </div>
              <div style={{
                background: "rgba(95,217,168,0.08)",
                border: "1px solid rgba(95,217,168,0.20)",
                borderRadius: 8, padding: "12px 14px",
              }}>
                <div style={{ fontSize: 10, letterSpacing: "0.10em",
                              textTransform: "uppercase", opacity: 0.55,
                              fontWeight: 600 }}>
                  Revenue
                </div>
                <div style={{ fontSize: 22, fontWeight: 800, lineHeight: 1.1, marginTop: 2 }}>
                  {fmtRevenue(c.revenue_2024_usd)}
                </div>
                <div style={{ fontSize: 11, opacity: 0.55, marginTop: 2 }}>2024 estimate</div>
              </div>
              <div style={{
                background: "rgba(255,184,77,0.08)",
                border: "1px solid rgba(255,184,77,0.20)",
                borderRadius: 8, padding: "12px 14px",
              }}>
                <div style={{ fontSize: 10, letterSpacing: "0.10em",
                              textTransform: "uppercase", opacity: 0.55,
                              fontWeight: 600 }}>
                  Track record
                </div>
                <div style={{ fontSize: 26, fontWeight: 800, lineHeight: 1.1, marginTop: 2 }}>
                  {c.founded ? `${new Date().getFullYear() - c.founded} yrs` : "—"}
                </div>
                <div style={{ fontSize: 11, opacity: 0.55, marginTop: 2 }}>
                  {c.founded ? `since ${c.founded}` : "founded date unknown"}
                </div>
              </div>
            </div>

            {/* Editorial summary from the curated notes field. Split on
                semicolons so the long single-paragraph entry reads as
                bullet-style takeaways. */}
            {c.notes && (
              <div>
                <div style={{ fontSize: 10, letterSpacing: "0.10em",
                              textTransform: "uppercase", opacity: 0.55,
                              fontWeight: 600, marginBottom: 8 }}>
                  What you need to know
                </div>
                <ul style={{ margin: 0, paddingLeft: 18, fontSize: 14,
                             lineHeight: 1.55, opacity: 0.85 }}>
                  {String(c.notes).split(/;\s*/).filter(Boolean).slice(0, 5).map((sentence, i) => (
                    <li key={i} style={{ marginBottom: 6 }}>
                      {sentence.trim().replace(/\.$/, "")}.
                    </li>
                  ))}
                </ul>
                {c.primary_source_url && (
                  <a href={c.primary_source_url} target="_blank" rel="noopener noreferrer"
                     style={{ fontSize: 11, color: "#5fa9ff", marginTop: 10,
                              display: "inline-block", letterSpacing: "0.04em" }}>
                    Source: {c.primary_source_url.replace(/^https?:\/\/(www\.)?/, "").split("/")[0]} →
                  </a>
                )}
              </div>
            )}
          </Card>
          </div>
          <Card style={{ borderLeft: `4px solid ${verdictColor}` }}>
            <Eyebrow>TRUST VERDICT</Eyebrow>
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 10 }}>
              <Stoplight tier={verdict.tier} />
              <div style={{ fontSize: 30, fontWeight: 800, color: verdictColor, letterSpacing: "-0.02em", lineHeight: 1.05 }}>
                {verdict.label.replace(/^[▲⚠○]\s*/, "")}
              </div>
            </div>
            <div style={{ fontSize: 13, opacity: 0.55, textTransform: "uppercase", letterSpacing: "0.08em", marginTop: 12 }}>
              Trust score
            </div>
            <div style={{ fontSize: 36, fontWeight: 700 }}>{verdict.trustScore}<span style={{ fontSize: 18, opacity: 0.4 }}>/100</span></div>
            <div style={{ fontSize: 13, lineHeight: 1.45, opacity: 0.78, marginTop: 14 }}>
              {verdict.why}
            </div>
            {/* Receipts — surface the public-record sources directly inside the
                verdict card so the trust claim is one click from being verified. */}
            <div style={{ marginTop: 16, paddingTop: 14, borderTop: "1px solid rgba(255,255,255,0.08)" }}>
              <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.10em", color: "rgba(255,255,255,0.55)", marginBottom: 8 }}>
                Verify it yourself ↓
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                {c.sec_cik && (
                  <a href={`https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=${c.sec_cik}&type=&dateb=&owner=include&count=40`}
                     target="_blank" rel="noopener noreferrer" style={receiptBtn}>
                    SEC EDGAR · filings ↗
                  </a>
                )}
                {c.usdot && (
                  <a href={`https://safer.fmcsa.dot.gov/query.asp?searchtype=ANY&query_type=queryCarrierSnapshot&query_param=USDOT&query_string=${encodeURIComponent(c.usdot)}`}
                     target="_blank" rel="noopener noreferrer" style={receiptBtn}>
                    FMCSA SAFER · snapshot ↗
                  </a>
                )}
                {c.usdot && (
                  <a href={`https://ai.fmcsa.dot.gov/SMS/Carrier/${encodeURIComponent(c.usdot)}/Overview.aspx`}
                     target="_blank" rel="noopener noreferrer" style={receiptBtn}>
                    FMCSA SMS · BASIC scores ↗
                  </a>
                )}
                <a href={`https://www.courtlistener.com/?q=${encodeURIComponent(c.name)}&type=r`}
                   target="_blank" rel="noopener noreferrer" style={receiptBtn}>
                  CourtListener · litigation ↗
                </a>
              </div>
            </div>
          </Card>
        </div>

        {/* ---- Risk Report teaser — sits right under the verdict to
             catch the eye before the visitor scrolls. Shows what's IN
             the paid report without revealing details. Each row tells
             a curiosity-gap story; CTA is right there to convert. ---- */}
        <RiskReportTeaser carrier={c} />

        {/* ---- Row 2: C/D/E (hero stats) + F (corp identity) ---- */}
        <div style={gridRow(["3fr","3fr","3fr","3fr"])}>
          <StatCard
            label="Power units"
            value={fmtFleet(c.fleet_size_estimate)}
            sub="2024 fleet estimate"
          />
          <StatCard
            label="2024 revenue"
            value={fmtRevenue(c.revenue_2024_usd)}
            sub={c.public ? "SEC 10-K reported" : "Industry estimate"}
          />
          <StatCard
            label="Top operating state"
            value={topStates[0] ? topStates[0][0] : "—"}
            sub={isRealStateData
              ? `${topStates[0] ? topStates[0][1].toLocaleString() : 0} FMCSA inspections · 24mo`
              : "Illustrative until live SAFER scrape lands"}
            provisional={!isRealStateData}
          />
          <Card>
            <Eyebrow>CORPORATE</Eyebrow>
            <div style={{ marginTop: 12 }}>
              <Attr label="Ownership" value={(c.ownership || "—").toUpperCase()} />
            </div>
            {c.notable_subsidiaries && c.notable_subsidiaries.length > 0 && (
              <div style={{ marginTop: 14 }}>
                <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em", opacity: 0.5 }}>
                  Notable subsidiaries
                </div>
                <div style={{ fontSize: 13, marginTop: 6, lineHeight: 1.45 }}>
                  {c.notable_subsidiaries.slice(0, 4).join(" · ")}
                  {c.notable_subsidiaries.length > 4 && (
                    <span style={{ opacity: 0.5 }}> · +{c.notable_subsidiaries.length - 4} more</span>
                  )}
                </div>
              </div>
            )}
          </Card>
        </div>

        {/* ---- Row 3: G (hex map) + H (companion) ---- */}
        <div style={gridRow(["8fr","4fr"])}>
          <Card>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
              <Eyebrow>{isRealStateData ? "FMCSA INSPECTIONS · BY STATE · 24MO" : "NETWORK FOOTPRINT · BY STATE"}</Eyebrow>
              {isRealStateData ? (
                <span style={{
                  fontSize: 10, textTransform: "uppercase", letterSpacing: "0.08em",
                  padding: "3px 8px", border: "1px solid rgba(95,217,168,0.6)",
                  borderRadius: 3, color: "#5fd9a8", whiteSpace: "nowrap",
                }}>
                  ✓ Live FMCSA SMS · public record
                </span>
              ) : (
                <ProvisionalBadge />
              )}
            </div>
            <HexUSMap values={stateValues} />
            <div style={{ display: "flex", gap: 6, marginTop: 12, fontSize: 11, opacity: 0.6, alignItems: "center" }}>
              <span>Less</span>
              {[0.10, 0.28, 0.50, 0.75, 1.0].map((a, i) => (
                <span key={i} style={{
                  width: 24, height: 12,
                  background: `rgba(95,169,255,${a})`, borderRadius: 2,
                }} />
              ))}
              <span>More · {isRealStateData ? "FMCSA roadside inspections, last 24 months" : "est. miles per year"}</span>
            </div>
          </Card>
          <Card>
            <Eyebrow>TOP STATES</Eyebrow>
            <ol style={{ margin: "12px 0 0", padding: 0, listStyle: "none" }}>
              {topStates.map(([abbr, v], i) => (
                <li key={abbr} style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", borderBottom: "1px solid rgba(255,255,255,0.06)" }}>
                  <span><strong style={{ opacity: 0.5, marginRight: 8 }}>{i + 1}.</strong>{STATE_NAMES[abbr] || abbr}</span>
                  <span style={{ opacity: 0.85, fontVariantNumeric: "tabular-nums" }}>
                    {isRealStateData ? `${v.toLocaleString()} insp.` : `${Math.round(v)}M mi`}
                  </span>
                </li>
              ))}
            </ol>
          </Card>
        </div>

        {/* ---- Row 3.5: Terminal Network (when OSM has mapped this carrier's terminals) ---- */}
        {data.terminals && data.terminals.length > 0 && (
          <div style={gridRow(["8fr", "4fr"])}>
            <Card>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
                <Eyebrow>TERMINAL NETWORK · OSM MAPPED</Eyebrow>
                <span style={{
                  fontSize: 10, textTransform: "uppercase", letterSpacing: "0.08em",
                  padding: "3px 8px", border: "1px solid rgba(95,217,168,0.6)",
                  borderRadius: 3, color: "#5fd9a8", whiteSpace: "nowrap",
                }}>
                  ✓ {data.terminals.length} location{data.terminals.length === 1 ? "" : "s"}
                </span>
              </div>
              <TerminalMap terminals={data.terminals} />
              <div style={{ fontSize: 11, opacity: 0.55, marginTop: 10, lineHeight: 1.5 }}>
                Crowdsourced from OpenStreetMap. Coverage is partial — OSM
                doesn't map every service center. For a complete carrier
                terminal list, the operator's locations page is canonical.
              </div>
            </Card>
            <Card>
              <Eyebrow>TERMINAL ADDRESSES</Eyebrow>
              <ol style={{ margin: "12px 0 0", padding: 0, listStyle: "none", maxHeight: 320, overflowY: "auto" }}>
                {data.terminals.slice(0, 30).map((t, i) => (
                  <li key={t.slug || i} style={{ padding: "8px 0", borderBottom: "1px solid rgba(255,255,255,0.06)", fontSize: 13 }}>
                    <div style={{ fontWeight: 600 }}>{t.name || `Terminal ${i + 1}`}</div>
                    {t.address && (
                      <div style={{ fontSize: 12, opacity: 0.65, marginTop: 2 }}>{t.address}</div>
                    )}
                    {t.source_url && (
                      <a href={t.source_url} target="_blank" rel="noopener noreferrer"
                         style={{ fontSize: 11, color: "#5fa9ff", textDecoration: "none", marginTop: 3, display: "inline-block" }}>
                        OSM ↗
                      </a>
                    )}
                  </li>
                ))}
                {data.terminals.length > 30 && (
                  <li style={{ padding: "8px 0", fontSize: 11, opacity: 0.55 }}>
                    + {data.terminals.length - 30} more
                  </li>
                )}
              </ol>
            </Card>
          </div>
        )}

        {/* ---- Row 4: I (fleet) + J (safety) ---- */}
        <div style={gridRow(["6fr","6fr"])}>
          <Card>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <Eyebrow>FLEET & EQUIPMENT</Eyebrow>
              <ProvisionalBadge />
            </div>
            <div style={{ marginTop: 14, display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px 24px", fontSize: 14 }}>
              <Attr label="Total power units" value={fmtFleet(c.fleet_size_estimate)} />
              <Attr label="Primary equipment" value={(c.segment || "—").toUpperCase()} />
              <Attr label="Trailers (est.)" value={c.fleet_size_estimate ? fmtFleet(Math.round(c.fleet_size_estimate * 2.4)) : "—"} />
              <Attr label="Reefer share" value={c.segment === "reefer" ? "Primary" : "Mixed"} />
              <Attr label="Hazmat" value="See SAFER" />
              <Attr label="Average age" value="Provisional"  />
            </div>
          </Card>
          <Card>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <Eyebrow>SAFETY & COMPLIANCE</Eyebrow>
              <ProvisionalBadge />
            </div>
            <div style={{ marginTop: 14, display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px 24px", fontSize: 14 }}>
              <Attr label="Operating authority" value={c.usdot ? "Active (SAFER)" : "Not in SAFER"} />
              <Attr label="Insurance on file" value={c.usdot ? "Yes" : "—"} />
              <Attr label="Out-of-service rate" value="Provisional" />
              <Attr label="Crashes (24mo)" value="Provisional" />
              <Attr label="Inspections (24mo)" value="Provisional" />
              <Attr label="Safety rating" value={c.usdot ? "See SAFER" : "—"} />
            </div>
            {c.usdot && (
              <a
                href={`https://safer.fmcsa.dot.gov/query.asp?searchtype=ANY&query_type=queryCarrierSnapshot&query_param=USDOT&query_string=${encodeURIComponent(c.usdot)}`}
                target="_blank" rel="noopener noreferrer"
                style={{ ...linkStyle, fontSize: 13, marginTop: 14, display: "inline-block" }}
              >
                → Open FMCSA SAFER snapshot
              </a>
            )}
          </Card>
        </div>

        {/* ---- Row 5: K (corp structure) ---- */}
        <div style={gridRow(["12fr"])}>
          <Card>
            <Eyebrow>CORPORATE STRUCTURE & EXECUTIVE NOTE</Eyebrow>
            <div style={{ marginTop: 12, fontSize: 14, lineHeight: 1.55, opacity: 0.85 }}>
              {c.notes || "No editorial note on file. The public record shows no escalations in the last 24 months."}
            </div>
            {c.primary_source_url && (
              <div style={{ marginTop: 12 }}>
                <a href={c.primary_source_url} target="_blank" rel="noopener noreferrer" style={{ ...linkStyle, fontSize: 13 }}>
                  → Primary source ({new URL(c.primary_source_url).hostname.replace(/^www\./, "")})
                </a>
              </div>
            )}
          </Card>
        </div>

        {/* ---- Row 6: L (litigation/events) + M (sealed intel) ---- */}
        <div style={gridRow(["7fr","5fr"])}>
          <Card>
            <Eyebrow>LITIGATION & MATERIAL EVENTS · 24 MONTHS</Eyebrow>
            {data.dossier && data.dossier.signals_json && Array.isArray(data.dossier.signals_json) && data.dossier.signals_json.length > 0 ? (
              <ul style={{ margin: "12px 0 0", padding: 0, listStyle: "none" }}>
                {data.dossier.signals_json.slice(0, 8).map((s, i) => (
                  <li key={i} style={{ padding: "10px 0", borderBottom: "1px solid rgba(255,255,255,0.06)", fontSize: 13 }}>
                    <div style={{
                      display: "inline-block", padding: "2px 8px", borderRadius: 3, fontSize: 10,
                      textTransform: "uppercase", letterSpacing: "0.10em", marginRight: 10,
                      background: (s.severity === "critical") ? "rgba(255,104,104,0.20)" : (s.severity === "high") ? "rgba(255,184,77,0.20)" : "rgba(95,169,255,0.20)",
                      color: (s.severity === "critical") ? "#ff8a8a" : (s.severity === "high") ? "#ffb84d" : "#5fa9ff",
                    }}>{s.severity || "note"}</div>
                    <span style={{ opacity: 0.85 }}>{s.label || s.event || s.title || JSON.stringify(s).slice(0, 120)}</span>
                    {s.date && <span style={{ opacity: 0.5, marginLeft: 8 }}>· {s.date}</span>}
                  </li>
                ))}
              </ul>
            ) : (
              <div style={{ marginTop: 14, fontSize: 13, opacity: 0.6 }}>
                No public-record events surfaced through the dossier engine yet. Run a research synthesis from{" "}
                <a href="#/research" style={linkStyle}>/#/research</a> to populate this block.
              </div>
            )}
          </Card>
          <Card>
            <Eyebrow>OPERATOR-SIDE INTEL · SEALED</Eyebrow>
            <div style={{ marginTop: 14, fontSize: 14, lineHeight: 1.5, opacity: 0.78 }}>
              Per the two-tier disclosure rule, driver-derived signal stays sealed —
              we surface counts only, never names or words.
            </div>
            <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 10, fontSize: 13 }}>
              <SealedRow
                label="Verified intel rows (24mo)"
                value={(data.sealed_intel && data.sealed_intel.total_24mo) || 0}
              />
              <SealedRow
                label="Recent activity (90d)"
                value={(data.sealed_intel && data.sealed_intel.recent_90d) || 0}
              />
            </div>
            <div style={{ fontSize: 11, opacity: 0.5, marginTop: 14, textTransform: "uppercase", letterSpacing: "0.08em" }}>
              Live join · intel_submissions where parsed_carrier matches name
            </div>
          </Card>
        </div>

        {/* ---- Row 7: N (sources) ---- */}
        <div style={gridRow(["12fr"])}>
          <Card>
            <Eyebrow>SOURCES</Eyebrow>
            <div style={{ marginTop: 12, display: "flex", flexWrap: "wrap", gap: 10 }}>
              {c.sec_cik && (
                <SourceLink
                  href={`https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=${c.sec_cik}&type=&dateb=&owner=include&count=40`}
                  label="SEC EDGAR · filings"
                />
              )}
              {c.usdot && (
                <SourceLink
                  href={`https://safer.fmcsa.dot.gov/query.asp?searchtype=ANY&query_type=queryCarrierSnapshot&query_param=USDOT&query_string=${encodeURIComponent(c.usdot)}`}
                  label="FMCSA SAFER · snapshot"
                />
              )}
              {c.usdot && (
                <SourceLink
                  href={`https://ai.fmcsa.dot.gov/SMS/Carrier/${encodeURIComponent(c.usdot)}/Overview.aspx`}
                  label="FMCSA SMS · BASIC scores"
                />
              )}
              {c.primary_source_url && (
                <SourceLink href={c.primary_source_url} label="Editorial source" />
              )}
              <SourceLink
                href={`https://www.courtlistener.com/?q=${encodeURIComponent(c.name)}&type=r`}
                label="CourtListener · litigation"
              />
            </div>
          </Card>
        </div>

        {/* ---- Row 8: O (CTA) ---- */}
        <div style={gridRow(["12fr"])}>
          <Card style={{ background: "linear-gradient(135deg, rgba(95,169,255,0.18), rgba(95,169,255,0.04))", border: "1px solid rgba(95,169,255,0.45)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 16 }}>
              <div>
                <div style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: "0.10em", color: "#5fa9ff", fontWeight: 600 }}>
                  DEEP-DIVE PDF · 18-22 PAGES
                </div>
                <h3 style={{ fontSize: 22, margin: "6px 0 4px", fontWeight: 700 }}>
                  Carrier Risk Report on {c.name}
                </h3>
                <div style={{ fontSize: 13, opacity: 0.78, maxWidth: 560 }}>
                  Full SEC EDGAR walk · FMCSA SAFER + SMS BASIC · litigation log · operator-side
                  signal density · 5-year trajectory chart · cross-customer exposure map.
                </div>
              </div>
              <a href={`#/risk-report?carrier=${encodeURIComponent(c.slug)}`} style={btnPrimary}>
                Order $499 deep-dive →
              </a>
            </div>
          </Card>
        </div>

        {/* Sticky CTA pill — floats bottom-right once the user has scrolled */}
        <StickyRiskReportPill carrier={c} />

        {/* Legal footer — appears on every dossier page */}
        <div style={legalFooter}>
          <strong>Disclaimer.</strong> Identity, regulatory, and corporate facts are sourced from
          public records (Transport Topics 2024 ranking, SEC EDGAR filings, FMCSA SAFER, court
          dockets, news cited inline). Fleet size and revenue figures for non-public companies
          are industry estimates. The hex-map state distribution and per-state mileage figures
          are <strong>illustrative</strong> — synthesized for visual continuity until the live
          FMCSA SAFER scrape is wired. Trust verdicts (No flags / Watch / Distress) are derived
          from a curated note field via keyword heuristic; they reflect reported public-record
          events, not formal credit ratings or financial advice. This page is not investment
          advice, not legal advice, and not a credit report. To request correction of a specific
          claim, contact corrections@shippingclarity.com.
        </div>

      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Atoms
// ---------------------------------------------------------------------------

const legalFooter = {
  marginTop: 40, padding: 18,
  fontSize: 11, lineHeight: 1.55,
  color: "rgba(255,255,255,0.55)",
  background: "rgba(255,255,255,0.03)",
  border: "1px solid rgba(255,255,255,0.08)",
  borderRadius: 8,
  fontFamily: '"Helvetica Neue", Helvetica, Arial, sans-serif',
};

const pageStyle = {
  background: "radial-gradient(circle at 30% 0%, #1d2d52 0%, #0a1224 55%, #050913 100%)",
  minHeight: "100vh",
  color: "#fff",
  fontFamily: '"Helvetica Neue", Helvetica, Arial, sans-serif',
};

const cardBg = "rgba(255,255,255,0.04)";
const cardBorder = "1px solid rgba(255,255,255,0.10)";

function Card({ children, style }) {
  return (
    <div style={{
      background: cardBg, border: cardBorder, borderRadius: 12,
      padding: 20, ...style,
    }}>{children}</div>
  );
}

// Stoplight — the trust verdict as a vertical traffic light. The lit
// lamp pulses softly; the unlit lamps stay dim so the active one really
// pops. Editor specifically asked for the 3-light visual instead of a
// plain colored label.
function Stoplight({ tier }) {
  const lamps = [
    { tier: "distress", color: "#ff4646", glow: "rgba(255,70,70,0.85)" },
    { tier: "watch",    color: "#ffc53d", glow: "rgba(255,197,61,0.85)" },
    { tier: "no_flags", color: "#3ddb88", glow: "rgba(61,219,136,0.85)" },
  ];
  return (
    <div style={{
      width: 38, padding: "5px 5px",
      background: "linear-gradient(180deg,#0a0e1a,#161e30)",
      borderRadius: 10, border: "1px solid rgba(255,255,255,0.10)",
      display: "flex", flexDirection: "column", gap: 4,
      boxShadow: "inset 0 2px 6px rgba(0,0,0,0.55)",
      flexShrink: 0,
    }}>
      <style>{`
        @keyframes stoplight-pulse {
          0%, 100% { opacity: 1; }
          50%      { opacity: 0.78; }
        }
        .stoplight-lamp-on  { animation: stoplight-pulse 2.2s ease-in-out infinite; }
      `}</style>
      {lamps.map((l) => {
        const on = l.tier === tier;
        return (
          <div
            key={l.tier}
            className={on ? "stoplight-lamp-on" : ""}
            style={{
              width: 26, height: 26, borderRadius: "50%",
              background: on ? l.color : "#1d2236",
              boxShadow: on
                ? `0 0 10px 2px ${l.glow}, inset 0 -2px 4px rgba(0,0,0,0.35)`
                : "inset 0 0 4px rgba(0,0,0,0.55)",
              border: on ? `1px solid ${l.color}` : "1px solid rgba(255,255,255,0.06)",
              opacity: on ? 1 : 0.32,
            }}
          />
        );
      })}
    </div>
  );
}

function Eyebrow({ children }) {
  return (
    <div style={{
      fontSize: 11, textTransform: "uppercase", letterSpacing: "0.16em",
      color: "#5fa9ff", fontWeight: 600,
    }}>{children}</div>
  );
}

function Attr({ label, value }) {
  return (
    <div>
      <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em", opacity: 0.5 }}>{label}</div>
      <div style={{ fontSize: 14, fontWeight: 600, marginTop: 2 }}>{value}</div>
    </div>
  );
}

function StatCard({ label, value, sub, provisional }) {
  return (
    <Card>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <Eyebrow>{label}</Eyebrow>
        {provisional && <ProvisionalBadge compact />}
      </div>
      <div style={{ fontSize: 36, fontWeight: 800, marginTop: 8, letterSpacing: "-0.02em", lineHeight: 1 }}>
        {value}
      </div>
      {sub && <div style={{ fontSize: 12, opacity: 0.6, marginTop: 8 }}>{sub}</div>}
    </Card>
  );
}

// SAFER-pending indicator. Real FMCSA SMS data populates these panels
// once `ingest-fmcsa-state-inspections.py` runs (weekly via the
// weekly-ingest workflow, or on-demand via GH Actions → "Run workflow").
// Until then the panels show illustrative defaults — the badge is the
// honesty footnote. Toned down 2026-05 from amber-loud to muted blue
// accent so the badge reads as a feature note instead of a warning.
function ProvisionalBadge({ compact }) {
  return (
    <span style={{
      fontSize: compact ? 9 : 10, textTransform: "uppercase", letterSpacing: "0.10em",
      padding: "3px 8px", border: "1px solid rgba(95,169,255,0.40)",
      borderRadius: 3, color: "rgba(95,169,255,0.85)", whiteSpace: "nowrap",
      fontWeight: 600,
    }}>
      Updates weekly · FMCSA SAFER
    </span>
  );
}

function SealedRow({ label, value, note }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "6px 0", borderBottom: "1px solid rgba(255,255,255,0.06)" }}>
      <span style={{ opacity: 0.78 }}>{label}</span>
      <span style={{ display: "flex", alignItems: "center", gap: 6, fontVariantNumeric: "tabular-nums" }}>
        <span style={{ fontWeight: 700 }}>{value}</span>
        {note && <span style={{ fontSize: 10, opacity: 0.5 }}>{note}</span>}
      </span>
    </div>
  );
}

function SourceLink({ href, label }) {
  return (
    <a href={href} target="_blank" rel="noopener noreferrer" style={{
      fontSize: 13, color: "#5fa9ff", textDecoration: "none",
      padding: "8px 14px", border: "1px solid rgba(95,169,255,0.4)",
      borderRadius: 999, background: "rgba(95,169,255,0.08)",
    }}>{label} ↗</a>
  );
}

const linkStyle = { color: "#5fa9ff", textDecoration: "none" };

const receiptBtn = {
  display: "block", padding: "8px 12px", fontSize: 12,
  background: "rgba(95,169,255,0.10)", color: "#5fa9ff",
  border: "1px solid rgba(95,169,255,0.30)", borderRadius: 5,
  textDecoration: "none", fontWeight: 600,
  textAlign: "center",
};

const btnGhost = {
  display: "inline-block", padding: "10px 20px", marginTop: 24,
  border: "1px solid rgba(255,255,255,0.3)", background: "transparent",
  color: "#fff", borderRadius: 6, cursor: "pointer", fontSize: 14,
};

const btnPrimary = {
  display: "inline-block", padding: "12px 24px",
  background: "#5fa9ff", color: "#0a1224", borderRadius: 8,
  fontWeight: 700, textDecoration: "none", fontSize: 15,
  whiteSpace: "nowrap",
};

function gridRow(cols) {
  return {
    display: "grid",
    gridTemplateColumns: cols.join(" "),
    gap: 16,
    marginBottom: 16,
    // Each card sizes to its own content rather than stretching to
    // match the tallest sibling. Without this the Identity card had
    // ~40% of its area empty whenever the Verdict card was taller.
    alignItems: "start",
  };
}

// =============================================================================
// RISK REPORT TEASER — curiosity-gap panel that lists premium-only
// findings with the values masked (counts shown, details locked).
// Drives Risk Report ($499) conversion without giving the goods away.
// =============================================================================

function RiskReportTeaser({ carrier }) {
  const c = carrier;
  // We deliberately compute a *count* of locked rows but never the detail
  // — the count creates the curiosity gap. Where we genuinely don't know
  // (haven't done the analysis), we show "Available in full report" with
  // no bogus number.
  const items = [
    { icon: "🛡", label: "Customer concentration risk",
      tease: "Top 5 customers as % of revenue · concentration score" },
    { icon: "⚖", label: "Federal civil litigation footprint",
      tease: "Last 24 months · cargo claim ratios · default judgments" },
    { icon: "📋", label: "FMCSA SMS BASIC trend",
      tease: "5-year trajectory across all 7 BASIC categories" },
    { icon: "🛰", label: "Lane-level operational signals",
      tease: "Spot-rate dispersion, terminal closure heat, hub redundancy" },
    { icon: "🏦", label: "Bond + insurance status timeline",
      tease: "L&I bond cancellation events · authority lapses" },
    { icon: "📈", label: "Financial trajectory (5-yr)",
      tease: "Revenue, fleet, margin trend · peer benchmarking" },
    { icon: "🚨", label: "OSHA + EPA compliance flags",
      tease: "Severe injury reports · facility-level violations" },
    { icon: "🤝", label: "Cross-carrier exposure map",
      tease: "Shared customers · cascading-distress risk" },
  ];

  return (
    <div style={gridRow(["12fr"])}>
      <div style={{
        background: "linear-gradient(135deg, rgba(95,169,255,0.10), rgba(95,169,255,0.02))",
        border: "1px solid rgba(95,169,255,0.30)",
        borderLeft: "4px solid #5fa9ff",
        borderRadius: 12,
        padding: "20px 24px",
        marginBottom: 16,
        position: "relative",
        overflow: "hidden",
      }}>
        <div style={{
          display: "flex", justifyContent: "space-between",
          alignItems: "baseline", flexWrap: "wrap", gap: 12, marginBottom: 14,
        }}>
          <div>
            <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.16em",
                          color: "#5fa9ff", fontWeight: 700 }}>
              🔒 Premium · Carrier Risk Report
            </div>
            <div style={{ fontFamily: "var(--font-serif, Georgia, serif)",
                          fontSize: 24, fontWeight: 700, marginTop: 4, lineHeight: 1.15 }}>
              What this public dossier doesn't show.
            </div>
            <div style={{ fontSize: 13, opacity: 0.72, marginTop: 6, maxWidth: 720 }}>
              Eight private-research surfaces that don't fit a public profile.
              Sourced from federal records, court dockets, and proprietary
              cross-checks. Delivered as an 18–22 page PDF in 24 hours.
            </div>
          </div>
          <a href={`#/risk-report?carrier=${encodeURIComponent(c.slug)}`}
             style={{
               background: "#5fa9ff", color: "#0a1224",
               padding: "12px 20px", borderRadius: 8,
               fontWeight: 700, fontSize: 14,
               textDecoration: "none", whiteSpace: "nowrap",
               boxShadow: "0 6px 18px rgba(95,169,255,0.35)",
             }}>
            Unlock — $499 →
          </a>
        </div>

        <div style={{
          display: "grid", gridTemplateColumns: "repeat(2, minmax(0, 1fr))",
          gap: 10,
        }}>
          {items.map((it) => (
            <div key={it.label} style={{
              display: "flex", alignItems: "flex-start", gap: 10,
              padding: "10px 12px",
              background: "rgba(95,169,255,0.04)",
              border: "1px solid rgba(95,169,255,0.15)",
              borderRadius: 6,
            }}>
              <span style={{ fontSize: 18, flexShrink: 0, marginTop: -2 }}>{it.icon}</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: 13, marginBottom: 2,
                              display: "flex", alignItems: "center", gap: 6 }}>
                  {it.label}
                  <span style={{ fontSize: 10, color: "rgba(255,255,255,0.45)" }}>🔒</span>
                </div>
                <div style={{ fontSize: 11, opacity: 0.62, lineHeight: 1.4 }}>{it.tease}</div>
              </div>
            </div>
          ))}
        </div>

        <div style={{
          marginTop: 14, paddingTop: 12,
          borderTop: "1px solid rgba(95,169,255,0.18)",
          fontSize: 11, color: "rgba(255,255,255,0.55)",
          display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8,
        }}>
          <span>Used by 200+ shippers, brokers, and lenders for vetting.</span>
          <span style={{ color: "#5fa9ff", fontWeight: 600 }}>
            <a href={`#/risk-report?carrier=${encodeURIComponent(c.slug)}`}
               style={{ color: "inherit", textDecoration: "none" }}>
              See sample report →
            </a>
          </span>
        </div>
      </div>
    </div>
  );
}

// =============================================================================
// STICKY RISK-REPORT PILL — floats bottom-right after the user has
// scrolled past the verdict (~600px). One persistent CTA across the
// whole carrier dossier so any scroll position is one click from buy.
// =============================================================================

function StickyRiskReportPill({ carrier }) {
  const [show, setShow] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setShow(window.scrollY > 600);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  if (!show) return null;
  return (
    <a
      href={`#/risk-report?carrier=${encodeURIComponent(carrier.slug)}`}
      style={{
        position: "fixed", right: 20, bottom: 20, zIndex: 900,
        background: "#5fa9ff", color: "#0a1224",
        padding: "12px 18px", borderRadius: 999,
        fontWeight: 700, fontSize: 13,
        textDecoration: "none",
        boxShadow: "0 10px 28px rgba(95,169,255,0.45), 0 4px 10px rgba(0,0,0,0.30)",
        display: "inline-flex", alignItems: "center", gap: 8,
        animation: "rrp-rise 280ms ease-out",
      }}
    >
      <style>{`
        @keyframes rrp-rise { from { transform: translateY(8px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
      `}</style>
      🔒 Full Risk Report on {(carrier.name || "this carrier").slice(0, 24)} — $499
    </a>
  );
}

window.RiskReportTeaser = RiskReportTeaser;
window.StickyRiskReportPill = StickyRiskReportPill;
window.CarrierDetailPage = CarrierDetailPage;
