// Carrier profile + Members/Advertise + Insights pages

const { useState: useStateC, useEffect: useEffectC } = React;

// =============================================================
// CARRIER INTEL FEED — verified, public intel for one carrier
// Pulls directly from intel_submissions (RLS limits anon to
// status=verified + visibility=public + published_at IS NOT NULL).
// =============================================================
function CarrierIntelFeed({ carrierId, carrierName }) {
  const [rows, setRows] = useStateC([]);
  const [loading, setLoading] = useStateC(true);
  const [filter, setFilter] = useStateC({ severity: null, type: null });

  useEffectC(() => {
    let alive = true;
    async function load() {
      if (!window.SI_DB || !window.SI_DB.raw) { setLoading(false); return; }
      try {
        const data = await window.SI_DB.raw.select(
          "intel_submissions",
          `select=id,parsed_carrier,parsed_intel_type,severity,raw_text,created_at,posted_at,parsed_city,visibility,status,source_url`
          + `&parsed_carrier=eq.${encodeURIComponent(carrierId)}`
          + `&status=eq.verified`
          + `&visibility=eq.public`
          + `&order=created_at.desc&limit=200`
        );
        if (!alive) return;
        setRows(Array.isArray(data) ? data : []);
      } catch (e) {
        console.warn("[carrier-intel] load failed", e);
      } finally {
        if (alive) setLoading(false);
      }
    }
    load();
    return () => { alive = false; };
  }, [carrierId]);

  const cities = (window.SI_DATA && window.SI_DATA.ALL_CITIES) || [];
  const cityName = (id) => {
    if (!id) return "—";
    const c = cities.find(x => x.id === id);
    return c ? `${c.name}, ${c.state}` : id.split("-").map(w => w[0].toUpperCase() + w.slice(1)).join(" ");
  };

  const now = Date.now();
  const day = 24 * 3600 * 1000;
  const sev = (r) => r.severity || "low";
  const recent24h = rows.filter(r => now - new Date(r.created_at).getTime() < day).length;
  const recent7d  = rows.filter(r => now - new Date(r.created_at).getTime() < 7 * day).length;
  const recent30d = rows.filter(r => now - new Date(r.created_at).getTime() < 30 * day).length;
  const highSev   = rows.filter(r => sev(r) === "high" || sev(r) === "critical").length;

  // type / city breakdown
  const byType = {};
  const byCity = {};
  rows.forEach(r => {
    const t = r.parsed_intel_type || "other";
    byType[t] = (byType[t] || 0) + 1;
    if (r.parsed_city) byCity[r.parsed_city] = (byCity[r.parsed_city] || 0) + 1;
  });
  const topTypes = Object.entries(byType).sort((a, b) => b[1] - a[1]).slice(0, 6);
  const topCities = Object.entries(byCity).sort((a, b) => b[1] - a[1]).slice(0, 6);

  const filtered = rows
    .filter(r => !filter.severity || sev(r) === filter.severity)
    .filter(r => !filter.type || (r.parsed_intel_type || "other") === filter.type)
    .slice(0, 100);

  function fmtDate(s) {
    if (!s) return "";
    const d = new Date(s);
    const days = Math.round((now - d.getTime()) / day);
    if (days === 0) return "today";
    if (days === 1) return "yesterday";
    if (days < 7)   return `${days}d ago`;
    return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
  }

  const sevColor = {
    critical: "#b91c1c",
    high:     "#dc2626",
    moderate: "#d97706",
    low:      "#6b7280",
  };

  return (
    <div className="ci-section">
      <div className="section-eyebrow">Field intel</div>
      <h2 className="section-title">What's surfacing about {carrierName} right now.</h2>
      <p className="ci-sub">
        Every verified, publicly published intel report tied to {carrierName} —
        sourced from driver communities, public posts, and verified shipper submissions.
        Sealed reports are aggregated separately and never appear here verbatim.
      </p>

      <div className="ci-summary-row">
        <div className="ci-stat"><div className="ci-stat-num">{recent24h}</div><div className="ci-stat-l">Last 24h</div></div>
        <div className="ci-stat"><div className="ci-stat-num">{recent7d}</div><div className="ci-stat-l">Last 7 days</div></div>
        <div className="ci-stat"><div className="ci-stat-num">{recent30d}</div><div className="ci-stat-l">Last 30 days</div></div>
        <div className="ci-stat"><div className="ci-stat-num" style={{ color: highSev ? "#dc2626" : "inherit" }}>{highSev}</div><div className="ci-stat-l">High / critical</div></div>
        <div className="ci-stat"><div className="ci-stat-num">{rows.length}</div><div className="ci-stat-l">Total verified</div></div>
      </div>

      {(topTypes.length > 0 || topCities.length > 0) && (
        <div className="ci-breakdown">
          {topTypes.length > 0 && (
            <div className="ci-bd-col">
              <div className="ci-bd-h">Top intel types</div>
              <div className="ci-chip-row">
                {topTypes.map(([t, n]) => (
                  <button
                    key={t}
                    className={`ci-chip ${filter.type === t ? "ci-chip-on" : ""}`}
                    onClick={() => setFilter({ ...filter, type: filter.type === t ? null : t })}
                  >
                    {t.replace(/_/g, " ")} <strong>{n}</strong>
                  </button>
                ))}
              </div>
            </div>
          )}
          {topCities.length > 0 && (
            <div className="ci-bd-col">
              <div className="ci-bd-h">Top metros</div>
              <div className="ci-chip-row">
                {topCities.map(([c, n]) => (
                  <span key={c} className="ci-chip ci-chip-static">
                    {cityName(c)} <strong>{n}</strong>
                  </span>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      {(filter.severity || filter.type) && (
        <div className="ci-filter-bar">
          <span>Filtered:</span>
          {filter.severity && <span className="ci-filter-pill">severity: {filter.severity}</span>}
          {filter.type && <span className="ci-filter-pill">type: {filter.type.replace(/_/g, " ")}</span>}
          <button className="ci-clear" onClick={() => setFilter({ severity: null, type: null })}>Clear</button>
        </div>
      )}

      <div className="ci-feed">
        {loading && <div className="ci-empty">Loading intel…</div>}
        {!loading && rows.length === 0 && (
          <div className="ci-empty">
            No verified public intel for {carrierName} yet. As driver and shipper reports come in
            and get verified by an editor, they'll show here.
          </div>
        )}
        {!loading && rows.length > 0 && filtered.length === 0 && (
          <div className="ci-empty">No intel matches the current filter.</div>
        )}
        {filtered.map((r) => (
          <article key={r.id} className="ci-row">
            <div className="ci-row-l" style={{ background: sevColor[sev(r)] || sevColor.low }} />
            <div className="ci-row-body">
              <div className="ci-row-head">
                <button
                  className={`ci-sev-tag ci-sev-${sev(r)}`}
                  onClick={() => setFilter({ ...filter, severity: filter.severity === sev(r) ? null : sev(r) })}
                  title="Filter by severity"
                >
                  {sev(r)}
                </button>
                <span className="ci-row-meta">
                  {(r.parsed_intel_type || "other").replace(/_/g, " ")}
                  {" · "}{cityName(r.parsed_city)}
                  {" · "}{fmtDate(r.posted_at || r.created_at)}
                </span>
              </div>
              <div className="ci-row-text">{r.raw_text || "—"}</div>
              {r.source_url && (
                <a className="ci-row-source" href={r.source_url} target="_blank" rel="noopener noreferrer">
                  source ↗
                </a>
              )}
            </div>
          </article>
        ))}
      </div>
    </div>
  );
}

// =============================================================
// FMCSA PUBLIC RECORD — pulls fmcsa_* attributes from
// entity_attributes for this carrier and renders fleet size,
// inspection volume + OOS rates, crashes, and operating status.
// Brand spine: this is PUBLIC record. We don't editorialize it,
// we surface it with citation. Source link to safer.fmcsa.dot.gov.
// =============================================================
function FmcsaPublicRecord({ carrierId, carrierName }) {
  const [attrs, setAttrs] = useStateC(null);
  const [loading, setLoading] = useStateC(true);

  useEffectC(() => {
    let alive = true;
    (async () => {
      try {
        const ents = await window.SI_DB.raw.select(
          "entities",
          `select=id&type=eq.carrier&slug=eq.${encodeURIComponent(carrierId)}`
        );
        if (!alive || !ents || !ents.length) { setLoading(false); return; }
        const rows = await window.SI_DB.raw.select(
          "entity_attributes",
          `select=key,value,source_url&entity_id=eq.${ents[0].id}&key=like.fmcsa_*`
        );
        if (!alive) return;
        const map = {};
        let src = null;
        (rows || []).forEach(r => {
          map[r.key.replace(/^fmcsa_/, "")] = r.value;
          if (!src && r.source_url) src = r.source_url;
        });
        setAttrs({ ...map, _source: src });
      } finally {
        if (alive) setLoading(false);
      }
    })();
    return () => { alive = false; };
  }, [carrierId]);

  if (loading) return null;
  if (!attrs || !attrs.usdot_number) return null;

  const num = (v) => {
    if (v == null || v === "") return null;
    const n = parseInt(String(v).replace(/[^0-9-]/g, ""), 10);
    return Number.isFinite(n) ? n : null;
  };
  const pct = (oos, total) => {
    const o = num(oos), t = num(total);
    if (!t || o == null) return null;
    return ((o / t) * 100);
  };

  const trucks = num(attrs.power_units);
  const drivers = num(attrs.drivers_count);
  const inspV = num(attrs.inspections_count_vehicle);
  const inspD = num(attrs.inspections_count_driver);
  const oosV = num(attrs.inspections_oos_vehicle);
  const oosD = num(attrs.inspections_oos_driver);
  const oosVPct = pct(attrs.inspections_oos_vehicle, attrs.inspections_count_vehicle);
  const oosDPct = pct(attrs.inspections_oos_driver, attrs.inspections_count_driver);
  const crashFatal = num(attrs.crashes_fatal);
  const crashInjury = num(attrs.crashes_injury);
  const crashTotal = num(attrs.crashes_total);

  const fmt = (n) => n == null ? "—" : n.toLocaleString();
  const status = attrs.operating_status || "—";
  const rating = attrs.safety_rating || null;

  // Vehicle OOS national average is ~20%; driver OOS national average ~5.5%
  const NAT_VEH = 20.0;
  const NAT_DRV = 5.5;
  function compare(p, nat) {
    if (p == null) return { label: "—", tone: "n" };
    const delta = p - nat;
    if (Math.abs(delta) < 0.5) return { label: "≈ national avg", tone: "n" };
    if (delta > 0) return { label: `${delta.toFixed(1)} pts above national`, tone: "bad" };
    return { label: `${Math.abs(delta).toFixed(1)} pts below national`, tone: "good" };
  }
  const vehCmp = compare(oosVPct, NAT_VEH);
  const drvCmp = compare(oosDPct, NAT_DRV);

  return (
    <div className="carrier-section">
      <style>{`
        .fmcsa-h { display:flex; align-items:baseline; justify-content:space-between;
          padding-bottom:14px; border-bottom:1px solid var(--rule); margin-bottom:18px; }
        .fmcsa-h h2 { font-family: var(--font-serif); font-size: 26px; letter-spacing: -0.02em;
          margin: 0; }
        .fmcsa-h .src { font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.1em;
          text-transform: uppercase; color: var(--ink-soft); }
        .fmcsa-h .src a { color: var(--ink-soft); text-decoration: none; border-bottom: 1px dotted var(--ink-soft); }
        .fmcsa-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px;
          margin-bottom: 18px; }
        @media (max-width: 760px) { .fmcsa-grid { grid-template-columns: repeat(2, 1fr); } }
        .fmcsa-card { background: #fff; border: 1px solid var(--rule); border-radius: 8px;
          padding: 16px 18px; }
        .fmcsa-card .lbl { font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.14em;
          text-transform: uppercase; color: var(--ink-soft); }
        .fmcsa-card .num { font-family: var(--font-serif); font-size: 28px; letter-spacing: -0.02em;
          margin: 6px 0 4px; }
        .fmcsa-card .sub { font-size: 11px; color: var(--ink-soft); line-height: 1.4; }
        .fmcsa-cmp { font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.05em;
          padding: 2px 6px; border-radius: 3px; display: inline-block; margin-top: 6px; }
        .fmcsa-cmp.good { background: oklch(0.94 0.05 145); color: oklch(0.36 0.12 145); }
        .fmcsa-cmp.bad  { background: oklch(0.94 0.05 25);  color: oklch(0.40 0.18 25); }
        .fmcsa-cmp.n    { background: oklch(0.95 0 0);       color: var(--ink-soft); }
        .fmcsa-row { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 14px;
          padding: 14px 0; border-top: 1px solid var(--rule); }
        @media (max-width: 760px) { .fmcsa-row { grid-template-columns: 1fr; } }
        .fmcsa-row .lbl { font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.14em;
          text-transform: uppercase; color: var(--ink-soft); }
        .fmcsa-row .v { font-family: var(--font-serif); font-size: 17px; margin-top: 2px; }
        .fmcsa-foot { margin-top: 14px; font-size: 11px; color: var(--ink-soft);
          line-height: 1.5; }
      `}</style>
      <div className="fmcsa-h">
        <div>
          <div className="section-eyebrow">Public record · FMCSA</div>
          <h2>What the federal data says about {carrierName}.</h2>
        </div>
        <span className="src">
          USDOT {fmt(num(attrs.usdot_number))} ·{" "}
          {attrs._source ? (
            <a href={attrs._source} target="_blank" rel="noopener noreferrer">SAFER snapshot ↗</a>
          ) : "SAFER snapshot"}
        </span>
      </div>

      <div className="fmcsa-grid">
        <div className="fmcsa-card">
          <div className="lbl">Power units</div>
          <div className="num">{fmt(trucks)}</div>
          <div className="sub">trucks + tractors registered</div>
        </div>
        <div className="fmcsa-card">
          <div className="lbl">Drivers</div>
          <div className="num">{fmt(drivers)}</div>
          <div className="sub">on the roster (MCS-150)</div>
        </div>
        <div className="fmcsa-card">
          <div className="lbl">Vehicle OOS rate</div>
          <div className="num">{oosVPct == null ? "—" : oosVPct.toFixed(1) + "%"}</div>
          <div className="sub">{fmt(oosV)} of {fmt(inspV)} inspections (24-mo)</div>
          <span className={`fmcsa-cmp ${vehCmp.tone}`}>{vehCmp.label}</span>
        </div>
        <div className="fmcsa-card">
          <div className="lbl">Driver OOS rate</div>
          <div className="num">{oosDPct == null ? "—" : oosDPct.toFixed(1) + "%"}</div>
          <div className="sub">{fmt(oosD)} of {fmt(inspD)} inspections (24-mo)</div>
          <span className={`fmcsa-cmp ${drvCmp.tone}`}>{drvCmp.label}</span>
        </div>
      </div>

      <div className="fmcsa-row">
        <div>
          <div className="lbl">Operating status</div>
          <div className="v">{status}</div>
        </div>
        <div>
          <div className="lbl">Safety rating</div>
          <div className="v">{rating || "Not rated"}</div>
        </div>
        <div>
          <div className="lbl">Crashes (24-mo)</div>
          <div className="v">{fmt(crashTotal)} total · {fmt(crashFatal)} fatal · {fmt(crashInjury)} injury</div>
        </div>
      </div>

      <p className="fmcsa-foot">
        Source: U.S. DOT Federal Motor Carrier Safety Administration. Public record.
        Inspection out-of-service rates are 24-month rolling. National averages from
        FMCSA: vehicle OOS ~20%, driver OOS ~5.5%. The number on the door isn't the
        story — what gets pulled at the inspection station is.
      </p>
    </div>
  );
}

function CarrierPage({ onNav, onReport, carrierId = "ups" }) {
  const { LA_REPORT, METRICS } = window.SI_DATA;
  // find carrier across all categories
  let carrier = null, catId = null;
  for (const cat of Object.keys(LA_REPORT.carriers)) {
    const found = LA_REPORT.carriers[cat].find(c => c.id === carrierId);
    if (found) { carrier = found; catId = cat; break; }
  }
  if (!carrier) { carrier = LA_REPORT.carriers.small[0]; catId = "small"; }

  // Mock multi-city grades for this carrier
  const cityGrades = [
    { city: "Los Angeles", score: carrier.score },
    { city: "New York", score: Math.max(40, carrier.score - 4) },
    { city: "Chicago", score: Math.min(99, carrier.score + 3) },
    { city: "Dallas", score: carrier.score - 2 },
    { city: "Atlanta", score: carrier.score + 1 },
    { city: "Phoenix", score: carrier.score - 6 },
    { city: "Seattle", score: carrier.score - 1 },
    { city: "Miami", score: carrier.score - 8 },
  ];

  return (
    <div className="page-carrier">
      <section className="carrier-hero">
        <div className="carrier-hero-inner">
          <div className="report-breadcrumb">
            <a href="#" onClick={(e) => { e.preventDefault(); onNav("home"); }}>Home</a>
            <span>/</span>
            <a href="#" onClick={(e) => { e.preventDefault(); onNav("carriers"); }}>Carriers</a>
            <span>/</span>
            <span className="current">{carrier.name}</span>
          </div>

          <div className="carrier-hero-grid">
            <div className="carrier-hero-left">
              <div className="carrier-id-row">
                <span className="carrier-logo-big" style={{ background: window.carrierColor(carrier.id) }}>
                  {carrier.name[0]}
                </span>
                <div>
                  <div className="report-eyebrow">{catId === "small" ? "Small Package" : catId === "ltl" ? "LTL Freight" : catId === "ftl" ? "Truckload (FTL)" : catId === "courier" ? "Last-Mile Courier" : "International"} Carrier</div>
                  <h1 className="carrier-name-big">{carrier.name}</h1>
                  <div className="carrier-meta">
                    <span>{carrier.shipments} LA shipments · Q1 2026</span>
                    <span className="dot-sep">·</span>
                    <span>{carrier.complaints} complaints filed</span>
                  </div>
                </div>
              </div>
              <p className="carrier-verdict-big">"{carrier.verdict}"</p>
              <div className="carrier-action-row">
                <button className="btn-primary" onClick={() => onReport()}>See LA report</button>
                <button className="btn-ghost">Compare with another →</button>
              </div>
            </div>
            <div className="carrier-hero-right">
              <CircleScore score={carrier.score} size={200} />
              <div className="carrier-overall-meta">
                <span>National avg: {carrier.score - 2}</span>
                <span><TrendArrow trend={carrier.trend} /> QoQ</span>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="carrier-body">
        <div className="carrier-body-inner">
          <div className="carrier-section">
            <div className="section-eyebrow">Metric breakdown</div>
            <h2 className="section-title">Where {carrier.name} excels — and where it doesn't.</h2>
            <div className="carrier-metrics-grid">
              {METRICS.map((m, i) => (
                <MetricBar key={m.id} label={m.label} score={carrier.scores[m.id]} delay={i * 60} />
              ))}
            </div>
          </div>

          <div className="carrier-section">
            <div className="section-eyebrow">Across the country</div>
            <h2 className="section-title">{carrier.name} grades by metro.</h2>
            <div className="city-grades-grid">
              {cityGrades.map(g => (
                <div key={g.city} className="city-grade-cell">
                  <div className="city-grade-name">{g.city}</div>
                  <div className="city-grade-score">{g.score}</div>
                  <LetterBadge score={g.score} size="sm" />
                </div>
              ))}
            </div>
          </div>

          <div className="carrier-section sw-section">
            <div className="sw-grid-big">
              <div>
                <div className="sw-h sw-h-good">What works</div>
                <ul className="sw-list-big">
                  {carrier.strengths.map((s, i) => <li key={i}>{s}</li>)}
                </ul>
              </div>
              <div>
                <div className="sw-h sw-h-bad">What doesn't</div>
                <ul className="sw-list-big">
                  {carrier.weaknesses.map((s, i) => <li key={i}>{s}</li>)}
                </ul>
              </div>
            </div>
          </div>

          <FmcsaPublicRecord carrierId={carrier.id} carrierName={carrier.name} />

          <div className="carrier-section">
            <CarrierIntelFeed carrierId={carrier.id} carrierName={carrier.name} />
          </div>

          <div className="carrier-section">
            <DriverReport carrierId={carrier.id} carrierName={carrier.name} />
          </div>

          {/* Claim banner */}
          <div className="claim-banner">
            <div>
              <div className="claim-eyebrow">Are you {carrier.name}?</div>
              <h3 className="claim-h">Claim your profile.</h3>
              <p className="claim-p">Respond to grades, share updates, and reach shippers actively comparing carriers.</p>
            </div>
            <button className="btn-primary-lg" onClick={() => onNav("members")}>Claim profile →</button>
          </div>

          {/* Cross-links — connect the carrier page to the rest of the
              data graph: rate intel, verification, the shipper directory
              for top customers, and the metro pages where this carrier
              actually operates. */}
          <div className="carrier-section">
            <div className="section-eyebrow">Connected surfaces</div>
            <h2 className="section-title" style={{ marginBottom: 18 }}>
              From {carrier.name} · into the rest of the graph
            </h2>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))", gap: 12 }}>
              <a href="#/rates" onClick={(e) => { e.preventDefault(); window.location.hash = "#/rates"; }}
                 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 }}>Lane rates →</div>
                <div style={{ fontFamily: "var(--font-serif)", fontSize: 17, color: "var(--ink)", lineHeight: 1.3 }}>
                  Where {carrier.name} could be running headhaul-vs-backhaul to maximize $/mi.
                </div>
              </a>
              <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 any carrier →</div>
                <div style={{ fontFamily: "var(--font-serif)", fontSize: 17, color: "var(--ink)", lineHeight: 1.3 }}>
                  Authority, safety, fleet, MC status — federal cross-check on the carriers you book.
                </div>
              </a>
              <a href="#/shippers" onClick={(e) => { e.preventDefault(); window.location.hash = "#/shippers"; }}
                 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 }}>Shipper directory →</div>
                <div style={{ fontFamily: "var(--font-serif)", fontSize: 17, color: "var(--ink)", lineHeight: 1.3 }}>
                  29,762 shippers indexed — find the customer pipeline that fits {carrier.name}'s lane density.
                </div>
              </a>
              <a href="#/risk-report" onClick={(e) => { e.preventDefault(); window.location.hash = "#/risk-report"; }}
                 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 }}>Carrier Risk Report →</div>
                <div style={{ fontFamily: "var(--font-serif)", fontSize: 17, color: "var(--ink)", lineHeight: 1.3 }}>
                  Order a 10-page deep-dive on any carrier — public-records synthesis in 24 hours. $499.
                </div>
              </a>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

// =============================================================
// MEMBERS / ADVERTISE PAGE
// =============================================================
// =============================================================
// MEMBERS / PRICING — three audiences, one page.
// Carriers, Shippers, Brokers. Hash sub-route lets the home page
// link straight to the audience: /#/members?for=shippers.
//
// Carrier "Verified" $1,200/mo is the only published number — set
// by Kris. Shippers + Brokers tiers are intentionally
// "Contact for pricing" until per-segment numbers are decided.
// =============================================================
function MembersPage({ onNav }) {
  // Read ?for=... from the URL hash on first render.
  const initialAudience = (() => {
    try {
      const m = window.location.hash.match(/[?&]for=([a-z]+)/i);
      const v = m && m[1].toLowerCase();
      if (v === "shippers" || v === "brokers" || v === "carriers") return v;
    } catch (e) {}
    return "shippers";
  })();
  const [audience, setAudience] = useStateC(initialAudience);
  const [tierSel, setTierSel] = useStateC(null);

  // Real day-1 platform numbers — sourced from build_state.
  // No visitor counts, no fabricated "decision-maker" stats.
  const platformStats = [
    { num: "1,162", label: "Verified intel signals · live" },
    { num: "33,455", label: "Receiver docks mapped" },
    { num: "22", label: "Metros · 41 carriers tracked" },
  ];

  const audiences = [
    { id: "shippers",  label: "Shippers" },
    { id: "carriers",  label: "Carriers" },
    { id: "brokers",   label: "Brokers" },
  ];

  // -- per-audience content -------------------------------------------------
  const content = {
    shippers: {
      eyebrow: "For shippers",
      title: <>Read any carrier for <em>$500</em>. Before the freight moves.</>,
      sub: "On-demand per-carrier deep-dives. Public-records synthesis — SEC filings, court dockets, FMCSA, operational signals — assembled into a 10-page actionable read. Priced for shippers who need it, not for procurement committees.",
      tiers: [
        {
          id: "free",
          name: "Pulse Free",
          price: "Free",
          sub: "One metro · daily digest",
          features: [
            "Daily Pulse email · 1 metro of your choice",
            "Public alert ribbon access",
            "Receiver-location lookup (33K docks)",
            "Truck-stop atlas + active weather",
          ],
          cta: "Subscribe to a Pulse →",
          ctaTarget: "home-pulse",
        },
        {
          id: "deepdive",
          name: "Deep-Dive Report",
          price: "$500",
          period: "/ report",
          sub: "Any carrier, any time you have a real decision",
          featured: true,
          features: [
            "Altman Z'' history · 3-year trend from EDGAR XBRL",
            "SEC filing scan · 8-K · 10-K · NT 10-K · 4.02 · 3.01",
            "CourtListener creditor + defendant pattern",
            "FMCSA SAFER inspection + crash trail",
            "Public BBB complaint trend",
            "Driver-network chatter · aggregated · names sealed",
            "10-page PDF · delivered inside 24 hours",
          ],
          cta: "Request a deep-dive →",
          ctaTarget: "mailto:hello@shippingclarity.com?subject=Deep-dive report request",
        },
        {
          id: "pro",
          name: "Pulse Pro",
          price: "$499",
          period: "/ month",
          sub: "All metros · full alert feed · annual prepay",
          features: [
            "All 22 metros · daily Pulse + breaking alerts",
            "Cross-source synthesizer feed · Hub Group-style reads",
            "Per-carrier financial dirt · 21-carrier EDGAR watchlist",
            "Refinery utilization + crack spreads + crude state map",
            "Email + Slack alert delivery",
            "Annual unlimited deep-dive add-on · $10,000/yr",
          ],
          cta: "Start Pulse Pro →",
          ctaTarget: "mailto:hello@shippingclarity.com?subject=Pulse Pro",
        },
      ],
    },
    carriers: {
      eyebrow: "For carriers, couriers & freight companies",
      title: <>Claim your profile. <em>Respond on the record.</em></>,
      sub: "Shippers Connect publishes verified intel signals about how carriers actually run. Claim your listing, respond to driver-sourced grades publicly, and put your service record in front of the shippers reading us.",
      tiers: [
        {
          id: "free",
          name: "Listed",
          price: "Free",
          sub: "Basic profile",
          features: [
            "Public carrier profile",
            "Quarterly grade visibility",
            "Basic metric data",
            "Read-only complaint summary",
          ],
          cta: "Claim listing →",
          ctaTarget: "mailto:hello@shippingclarity.com?subject=Claim listing",
        },
        {
          id: "pro",
          name: "Verified",
          price: "$1,200",
          period: "/ month",
          sub: "Recommended for active carriers",
          featured: true,
          features: [
            "Verified badge on profile",
            "Respond to grades publicly",
            "Detailed metric breakdowns",
            "Lead inbox from shippers",
            "Quarterly performance briefing",
            "API access to your data",
          ],
          cta: "Get Verified →",
          ctaTarget: "mailto:hello@shippingclarity.com?subject=Get Verified",
        },
        {
          id: "ad",
          name: "Spotlight",
          price: "Custom",
          sub: "Premium ad placement",
          features: [
            "Everything in Verified",
            "Sponsored placement on city reports",
            "Featured in search results",
            "Newsletter sponsorship slots",
            "Co-branded research reports",
            "Dedicated account manager",
          ],
          cta: "Contact sales →",
          ctaTarget: "mailto:hello@shippingclarity.com?subject=Spotlight",
        },
      ],
    },
    brokers: {
      eyebrow: "For freight brokers",
      title: <>Qualify carriers <em>in real time</em>, not on a spreadsheet.</>,
      sub: "Tendering a load and not sure which carrier to put on it? Live operator-network signal + regulatory filings + per-state density. The same data shippers see — bundled for tender-side decisioning.",
      tiers: [
        {
          id: "free",
          name: "Lookup",
          price: "Free",
          sub: "Per-carrier intel page",
          features: [
            "Public carrier profile + intel feed",
            "Verified driver-sourced signals",
            "Carrier-state-density map",
            "Anon-readable alert ribbon",
          ],
          cta: "Browse carriers →",
          ctaTarget: "carriers",
        },
        {
          id: "pro",
          name: "Live Qualify",
          price: "$999",
          period: "/ month",
          sub: "Internal use · unlimited qualifications",
          featured: true,
          features: [
            "API: per-carrier risk read on demand",
            "Watchlist: alert when any carrier you book hits a red flag",
            "EDGAR financial-dirt feed (4.02 / NT 10-K / 3.01)",
            "Per-city carrier scorecard access",
            "Slack + webhook delivery",
            "Deep-dive report add-on · $400 / report (broker rate)",
          ],
          cta: "Start Live Qualify →",
          ctaTarget: "mailto:hello@shippingclarity.com?subject=Live Qualify",
        },
        {
          id: "ent",
          name: "White-Label",
          price: "$4,999",
          period: "/ month",
          sub: "Resell carrier scorecards to your shippers",
          features: [
            "Everything in Live Qualify",
            "Co-branded carrier scorecards for your shippers",
            "Bulk carrier qualification · your full bench",
            "Custom corridor + lane analytics",
            "Dedicated rep + onboarding",
          ],
          cta: "Contact sales →",
          ctaTarget: "mailto:hello@shippingclarity.com?subject=Broker White-Label",
        },
      ],
    },
  };

  const a = content[audience];

  function handleTierCta(tier) {
    if (!tier.ctaTarget) return;
    if (tier.ctaTarget.startsWith("mailto:")) {
      window.location.href = tier.ctaTarget;
      return;
    }
    if (tier.ctaTarget === "home-pulse") {
      onNav("home");
      // Defer scroll until after route renders.
      setTimeout(() => {
        document.getElementById("dash-pulse-signup")?.scrollIntoView({ behavior: "smooth", block: "start" });
      }, 60);
      return;
    }
    onNav(tier.ctaTarget);
  }

  return (
    <div className="page-members">
      <style>{`
        .audience-tabs {
          display: inline-flex; gap: 4px; padding: 4px;
          background: var(--paper-2, #f4f4f0); border-radius: 999px;
          margin-bottom: 28px; border: 1px solid var(--rule-soft, #e5e5e0);
        }
        .audience-tab {
          padding: 8px 18px; border-radius: 999px; border: none; background: transparent;
          font-family: var(--font-mono); font-size: 12px; letter-spacing: 0.1em;
          text-transform: uppercase; color: var(--ink-soft); cursor: pointer;
          transition: all 0.15s;
        }
        .audience-tab.active { background: var(--ink); color: var(--paper); }
        .audience-tab:hover:not(.active) { color: var(--ink); }
        .members-honest-note {
          margin-top: 24px; font-size: 13px; color: var(--ink-soft);
          font-style: italic; max-width: 720px;
        }
      `}</style>
      <section className="members-hero">
        <div className="members-hero-inner">
          <div className="audience-tabs" role="tablist">
            {audiences.map(x => (
              <button key={x.id}
                role="tab"
                aria-selected={audience === x.id}
                className={`audience-tab ${audience === x.id ? "active" : ""}`}
                onClick={() => { setAudience(x.id); setTierSel(null); }}>
                {x.label}
              </button>
            ))}
          </div>
          <div className="hero-eyebrow"><span className="eyebrow-dot" />{a.eyebrow}</div>
          <h1 className="hero-title">{a.title}</h1>
          <p className="hero-sub">{a.sub}</p>
          <div className="members-stat-row">
            {platformStats.map((s, i) => (
              <div key={i} className="members-stat">
                <div className="ms-num">{s.num}</div>
                <div className="ms-label">{s.label}</div>
              </div>
            ))}
          </div>
          <p className="members-honest-note">
            Day-1 numbers, not visitor stats. We publish what we actually track —
            not what we wish we did.
          </p>
        </div>
      </section>

      <section className="pricing-section">
        <div className="pricing-inner">
          <div className="section-eyebrow">Plans</div>
          <h2 className="section-title">
            {audience === "shippers" && "Three ways to read the network."}
            {audience === "carriers" && "Three ways to be on Shippers Connect."}
            {audience === "brokers"  && "Three ways to qualify."}
          </h2>
          <div className="pricing-grid">
            {a.tiers.map(t => (
              <div key={t.id} className={`pricing-card ${t.featured ? "featured" : ""} ${tierSel === t.id ? "selected" : ""}`}
                onClick={() => setTierSel(t.id)}>
                {t.featured && <div className="pricing-badge">Most popular</div>}
                <div className="pricing-name">{t.name}</div>
                <div className="pricing-price">
                  {t.price}
                  {t.period && <span className="pricing-period">{t.period}</span>}
                </div>
                <div className="pricing-sub">{t.sub}</div>
                <ul className="pricing-features">
                  {t.features.map((f, i) => (
                    <li key={i}><span className="check">✓</span>{f}</li>
                  ))}
                </ul>
                <button
                  className={t.featured ? "btn-primary-lg full-w" : "btn-ghost-lg full-w"}
                  onClick={(e) => { e.stopPropagation(); handleTierCta(t); }}>
                  {t.cta}
                </button>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="signup-section">
        <div className="signup-inner">
          <div className="signup-left">
            <div className="section-eyebrow">Get started</div>
            <h2 className="section-title">
              {audience === "shippers" && "Start with a free Pulse."}
              {audience === "carriers" && "List your company in minutes."}
              {audience === "brokers"  && "Talk to us about live qualification."}
            </h2>
            <p className="signup-p">
              {audience === "shippers" && "Pick a metro, get the daily digest in your inbox tomorrow morning. No card. Cancel from any email."}
              {audience === "carriers" && "Tell us about your operation. We'll verify your DOT, MC, or USPS Mailer ID and have your profile live within 48 hours."}
              {audience === "brokers"  && "Brokers tendering today need real-time carrier-risk reads. Tell us your bench size and we'll send a sample qualification report inside 24 hours."}
            </p>
            <ul className="signup-bullets">
              {audience === "shippers" && <>
                <li><span className="check">✓</span>Free forever — single metro</li>
                <li><span className="check">✓</span>Driver-sourced signals, names always sealed</li>
                <li><span className="check">✓</span>Unsubscribe from any email</li>
              </>}
              {audience === "carriers" && <>
                <li><span className="check">✓</span>No long-term commitment</li>
                <li><span className="check">✓</span>Editorial integrity — sponsored never affects grades</li>
                <li><span className="check">✓</span>Cancel anytime</li>
              </>}
              {audience === "brokers" && <>
                <li><span className="check">✓</span>Sample report inside 24 hours</li>
                <li><span className="check">✓</span>Pricing scaled to bench size — no flat enterprise gate</li>
                <li><span className="check">✓</span>Same signal you'd otherwise pay a premium service for, weeks late</li>
              </>}
            </ul>
          </div>
          <div className="signup-form">
            {audience === "carriers" ? (
              <>
                <div className="form-h">Quick start</div>
                <div className="form-field">
                  <label>Company name</label>
                  <input type="text" placeholder="e.g. Acme Logistics" />
                </div>
                <div className="form-field">
                  <label>Category</label>
                  <select>
                    <option>Small Package</option>
                    <option>LTL Freight</option>
                    <option>Truckload (FTL)</option>
                    <option>Last-Mile Courier</option>
                    <option>International</option>
                  </select>
                </div>
                <div className="form-field">
                  <label>DOT or MC Number</label>
                  <input type="text" placeholder="DOT-1234567" />
                </div>
                <div className="form-field">
                  <label>Work email</label>
                  <input type="email" placeholder="you@company.com" />
                </div>
                <a href="mailto:hello@shippingclarity.com?subject=Carrier listing"
                   className="btn-primary-lg full-w"
                   style={{ display: "inline-block", textAlign: "center", textDecoration: "none" }}>
                  Start verification →
                </a>
                <p className="form-fine">By continuing you agree to our editorial policy. Sponsored placements are always disclosed.</p>
              </>
            ) : audience === "shippers" ? (
              <>
                <div className="form-h">Pick your metro</div>
                <div className="form-field">
                  <label>Work email</label>
                  <input type="email" placeholder="you@company.com" />
                </div>
                <div className="form-field">
                  <label>Metro</label>
                  <select>
                    <option>Los Angeles</option>
                    <option>New York / NJ</option>
                    <option>Chicago</option>
                    <option>Dallas / Fort Worth</option>
                    <option>Atlanta</option>
                    <option>Memphis</option>
                    <option>Houston</option>
                    <option>Seattle</option>
                    <option>Miami</option>
                    <option>Phoenix</option>
                    <option>Denver</option>
                    <option>Indianapolis</option>
                  </select>
                </div>
                <button
                  className="btn-primary-lg full-w"
                  onClick={() => {
                    onNav("home");
                    setTimeout(() => {
                      document.getElementById("dash-pulse-signup")?.scrollIntoView({ behavior: "smooth", block: "start" });
                    }, 60);
                  }}>
                  Subscribe to the Pulse →
                </button>
                <p className="form-fine">Free. We'll send tomorrow's morning digest. No card required.</p>
              </>
            ) : (
              <>
                <div className="form-h">Sample report request</div>
                <div className="form-field">
                  <label>Brokerage name</label>
                  <input type="text" placeholder="e.g. Acme Brokerage" />
                </div>
                <div className="form-field">
                  <label>Bench size (rough)</label>
                  <select>
                    <option>Under 25 carriers</option>
                    <option>25–100 carriers</option>
                    <option>100–500 carriers</option>
                    <option>500+ carriers</option>
                  </select>
                </div>
                <div className="form-field">
                  <label>Work email</label>
                  <input type="email" placeholder="you@company.com" />
                </div>
                <a href="mailto:hello@shippingclarity.com?subject=Broker sample report"
                   className="btn-primary-lg full-w"
                   style={{ display: "inline-block", textAlign: "center", textDecoration: "none" }}>
                  Request sample report →
                </a>
                <p className="form-fine">We'll reply within 24 hours with a sample qualification on a carrier of your choice.</p>
              </>
            )}
          </div>
        </div>
      </section>
    </div>
  );
}

// =============================================================
// INSIGHTS PAGE — moved to page-insights.jsx (richer version)
// =============================================================
function _InsightsPageLegacy({ onNav }) {
  const articles = [
    { tag: "Q1 2026 Report", title: "UPS reclaims #1 in LA small-package — by a hair", excerpt: "After two quarters of FedEx leading on transit time, UPS is back on top thanks to a 2-point gain in tracking accuracy.", date: "Apr 22", read: "4 min" },
    { tag: "Trend", title: "Why USPS scores are dropping in major metros", excerpt: "Service times are up, tracking gaps are widening, and complaints are at a 3-year high. We dig into why.", date: "Apr 18", read: "6 min" },
    { tag: "Buyer's Guide", title: "How to pick an LTL carrier when price isn't everything", excerpt: "Damage rates, pickup reliability, and claims handling matter more than most shippers realize.", date: "Apr 12", read: "8 min" },
    { tag: "Spotlight", title: "Saia's quiet rise: what they're getting right", excerpt: "Three quarters of consistent gains across every metric we track. Here's the playbook.", date: "Apr 08", read: "5 min" },
    { tag: "Methodology", title: "How we calculate the Clarity Score, explained", excerpt: "Eight weighted metrics, 14M+ shipments, and zero pay-to-play. The math behind every grade.", date: "Apr 02", read: "7 min" },
    { tag: "Q1 2026 Report", title: "The fastest-improving courier in every metro", excerpt: "Same-day is heating up. These are the carriers gaining ground in your city.", date: "Mar 28", read: "5 min" },
  ];
  return (
    <div className="page-insights">
      <section className="insights-hero">
        <div className="insights-hero-inner">
          <div className="hero-eyebrow"><span className="eyebrow-dot" />Editorial</div>
          <h1 className="hero-title">Insights from the loading dock.</h1>
          <p className="hero-sub">Quarterly trends, buyer's guides, and the stories behind the grades. Written by people who actually ship things.</p>
        </div>
      </section>
      <section className="articles-section">
        <div className="articles-inner">
          <article className="article-feature">
            <div className="insight-tag">{articles[0].tag}</div>
            <h2 className="article-feature-title">{articles[0].title}</h2>
            <p className="article-feature-excerpt">{articles[0].excerpt}</p>
            <div className="insight-meta"><span>{articles[0].date}</span><span className="dot-sep">·</span><span>{articles[0].read} read</span></div>
          </article>
          <div className="articles-grid">
            {articles.slice(1).map((a, i) => (
              <article key={i} className="article-card">
                <div className="insight-tag">{a.tag}</div>
                <h3 className="article-h">{a.title}</h3>
                <p className="article-p">{a.excerpt}</p>
                <div className="insight-meta"><span>{a.date}</span><span className="dot-sep">·</span><span>{a.read} read</span></div>
              </article>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}

// =============================================================
// CARRIERS DIRECTORY PAGE — list
// =============================================================
// =============================================================
// CARRIER RADAR — companion to the homepage Big Radar, but focused
// on the WHO and WHERE of the freight network. Public-source data
// only: FMCSA fleet sizes (entity_attributes), curated 10-K-derived
// dominant lanes (carrier_strength_lanes), small-package hubs (the
// SMALL_PKG_HUBS const from page-auth.jsx — duplicated here so this
// module is self-contained), LTL/TL terminals (entities type
// facility_xdock), and live cargo aircraft (cargo_aircraft from
// OpenSky). NO driver pipeline. NO scraped news. Two-tier disclosure.
// =============================================================

const CR_HUBS = [
  { id: "ups-sdf",  name: "UPS Worldport",            carrier: "ups",   carrierLabel: "UPS",   primary: true,  city: "Louisville, KY",  lat: 38.1740, lng: -85.7390 },
  { id: "ups-ord",  name: "UPS CACH",                 carrier: "ups",   carrierLabel: "UPS",                  city: "Hodgkins, IL",    lat: 41.7686, lng: -87.8467 },
  { id: "ups-mhv",  name: "UPS Mid-Hudson",           carrier: "ups",   carrierLabel: "UPS",                  city: "Newburgh, NY",    lat: 41.5113, lng: -74.1051 },
  { id: "ups-atl",  name: "UPS Pleasantdale Hub",     carrier: "ups",   carrierLabel: "UPS",                  city: "Atlanta, GA",     lat: 33.8400, lng: -84.4830 },
  { id: "ups-mes",  name: "UPS Mesquite Sort",        carrier: "ups",   carrierLabel: "UPS",                  city: "Mesquite, TX",    lat: 32.7480, lng: -96.6240 },
  { id: "ups-phx",  name: "UPS Phoenix Hub",          carrier: "ups",   carrierLabel: "UPS",                  city: "Phoenix, AZ",     lat: 33.4360, lng: -112.0080 },
  { id: "ups-clt",  name: "UPS Charlotte Hub",        carrier: "ups",   carrierLabel: "UPS",                  city: "Charlotte, NC",   lat: 35.2150, lng: -80.9430 },
  { id: "ups-phl",  name: "UPS Philadelphia Hub",     carrier: "ups",   carrierLabel: "UPS",                  city: "Philadelphia, PA",lat: 39.8770, lng: -75.2380 },
  { id: "ups-mia",  name: "UPS Miami Gateway",        carrier: "ups",   carrierLabel: "UPS",                  city: "Miami, FL",       lat: 25.7919, lng: -80.2870 },
  { id: "fdx-mem",  name: "FedEx World Hub",          carrier: "fedex", carrierLabel: "FedEx", primary: true,  city: "Memphis, TN",     lat: 35.0467, lng: -89.9787 },
  { id: "fdx-ind",  name: "FedEx Indianapolis Hub",   carrier: "fedex", carrierLabel: "FedEx",                city: "Indianapolis, IN",lat: 39.7173, lng: -86.2944 },
  { id: "fdx-oak",  name: "FedEx Oakland Hub",        carrier: "fedex", carrierLabel: "FedEx",                city: "Oakland, CA",     lat: 37.7212, lng: -122.2207 },
  { id: "fdx-ewr",  name: "FedEx Newark Hub",         carrier: "fedex", carrierLabel: "FedEx",                city: "Newark, NJ",      lat: 40.6925, lng: -74.1687 },
  { id: "fdx-afw",  name: "FedEx Alliance",           carrier: "fedex", carrierLabel: "FedEx",                city: "Fort Worth, TX",  lat: 32.9870, lng: -97.3187 },
  { id: "fdxg-olv", name: "FedEx Ground Olive Branch",carrier: "fedex", carrierLabel: "FedEx",                city: "Olive Branch, MS",lat: 34.9675, lng: -89.8295 },
  { id: "fdx-grb",  name: "FedEx Ground Greensboro",  carrier: "fedex", carrierLabel: "FedEx",                city: "Greensboro, NC",  lat: 36.1090, lng: -79.9370 },
  { id: "fdx-stl",  name: "FedEx Express STL",        carrier: "fedex", carrierLabel: "FedEx",                city: "St. Louis, MO",   lat: 38.7480, lng: -90.3600 },
  { id: "fdx-msp",  name: "FedEx Express MSP",        carrier: "fedex", carrierLabel: "FedEx",                city: "Minneapolis, MN",lat: 44.8870, lng: -93.2230 },
  { id: "fdx-mia",  name: "FedEx Miami Gateway",      carrier: "fedex", carrierLabel: "FedEx",                city: "Miami, FL",       lat: 25.7790, lng: -80.2950 },
  { id: "amzn-cvg", name: "Amazon Air Prime Air HQ",  carrier: "amazon",carrierLabel: "Amazon",primary: true,  city: "Cincinnati, KY",  lat: 39.0533, lng: -84.6611 },
  { id: "amzn-sdf", name: "Amazon Air SDF",           carrier: "amazon",carrierLabel: "Amazon",               city: "Louisville, KY",  lat: 38.1742, lng: -85.7390 },
  { id: "amzn-ind", name: "Amazon Air IND",           carrier: "amazon",carrierLabel: "Amazon",               city: "Indianapolis, IN",lat: 39.7173, lng: -86.2944 },
  { id: "amzn-rfd", name: "Amazon Air RFD",           carrier: "amazon",carrierLabel: "Amazon",               city: "Rockford, IL",    lat: 42.1947, lng: -89.0972 },
  { id: "amzn-lex", name: "Amazon Air LEX",           carrier: "amazon",carrierLabel: "Amazon",               city: "Lexington, KY",   lat: 38.0365, lng: -84.6059 },
  { id: "amzn-mia", name: "Amazon Air MIA",           carrier: "amazon",carrierLabel: "Amazon",               city: "Miami, FL",       lat: 25.7959, lng: -80.2870 },
  { id: "dhl-cvg",  name: "DHL Americas Hub",         carrier: "dhl",   carrierLabel: "DHL",   primary: true,  city: "Cincinnati, KY",  lat: 39.0533, lng: -84.6611 },
  { id: "dhl-jfk",  name: "DHL JFK Gateway",          carrier: "dhl",   carrierLabel: "DHL",                  city: "Queens, NY",      lat: 40.6500, lng: -73.7820 },
  { id: "dhl-lax",  name: "DHL LAX Gateway",          carrier: "dhl",   carrierLabel: "DHL",                  city: "Los Angeles, CA", lat: 33.9426, lng: -118.4081 },
  { id: "dhl-mia",  name: "DHL Miami Gateway",        carrier: "dhl",   carrierLabel: "DHL",                  city: "Miami, FL",       lat: 25.7960, lng: -80.2700 },
  { id: "ontrac-anh", name: "OnTrac Anaheim",         carrier: "ontrac",carrierLabel: "OnTrac",primary: true,  city: "Anaheim, CA",     lat: 33.8350, lng: -117.9140 },
  { id: "ontrac-sac", name: "OnTrac Sacramento",      carrier: "ontrac",carrierLabel: "OnTrac",               city: "Sacramento, CA",  lat: 38.5300, lng: -121.4360 },
  { id: "ontrac-phx", name: "OnTrac Phoenix",         carrier: "ontrac",carrierLabel: "OnTrac",               city: "Phoenix, AZ",     lat: 33.4250, lng: -112.0710 },
  { id: "ontrac-sea", name: "OnTrac Seattle",         carrier: "ontrac",carrierLabel: "OnTrac",               city: "Auburn, WA",      lat: 47.2980, lng: -122.2270 },
  { id: "ontrac-den", name: "OnTrac Denver",          carrier: "ontrac",carrierLabel: "OnTrac",               city: "Aurora, CO",      lat: 39.7530, lng: -104.7950 },
  { id: "ontrac-edi", name: "OnTrac Edison NJ",       carrier: "ontrac",carrierLabel: "OnTrac",               city: "Edison, NJ",      lat: 40.5260, lng: -74.4070 },
  { id: "ontrac-atl", name: "OnTrac Atlanta",         carrier: "ontrac",carrierLabel: "OnTrac",               city: "Atlanta, GA",     lat: 33.6580, lng: -84.4220 },
  { id: "ontrac-orl", name: "OnTrac Orlando",         carrier: "ontrac",carrierLabel: "OnTrac",               city: "Orlando, FL",     lat: 28.4910, lng: -81.4170 },
  { id: "usps-mem", name: "USPS Memphis NDC",         carrier: "usps",  carrierLabel: "USPS",  primary: true,  city: "Memphis, TN",     lat: 35.1142, lng: -89.9908 },
  { id: "usps-jfk", name: "USPS NY Distribution",     carrier: "usps",  carrierLabel: "USPS",                 city: "New York, NY",    lat: 40.6520, lng: -73.7920 },
  { id: "usps-ord", name: "USPS Chicago NDC",         carrier: "usps",  carrierLabel: "USPS",                 city: "Chicago, IL",     lat: 41.9750, lng: -87.9080 },
  { id: "usps-atl", name: "USPS Atlanta NDC",         carrier: "usps",  carrierLabel: "USPS",                 city: "Atlanta, GA",     lat: 33.6500, lng: -84.4060 },
  { id: "usps-dal", name: "USPS Dallas NDC",          carrier: "usps",  carrierLabel: "USPS",                 city: "Coppell, TX",     lat: 32.9700, lng: -96.9510 },
  { id: "usps-lax", name: "USPS Los Angeles NDC",     carrier: "usps",  carrierLabel: "USPS",                 city: "Bell, CA",        lat: 33.9700, lng: -118.1860 },
];

// Carrier brand colors — same set as the air cargo overlay so the planes
// and the hubs are visually consistent.
const CR_COLOR = {
  ups:    "#9F8F4A",   // toned UPS gold for dark map
  fedex:  "#FF6600",   // FedEx orange (instead of purple — pops on dark)
  amazon: "#FF9900",
  dhl:    "#FFCC00",
  usps:   "#5BA9DE",
  ontrac: "#FF4F00",
  atlas:  "#5BA9DE",   // Atlas Air
  polar:  "#5BA9DE",   // Polar Air Cargo
  abx:    "#E25555",
  kalitta:"#FFD466",
  "kalitta-charters":"#FFD466",
  "western-global":"#7BD66B",
  amerijet:"#FF6F61",
  ati:    "#A78BFA",
  national:"#F472B6",
  "21-air":"#34D399",
  cargojet:"#FBBF24",
  aerologic:"#FFD400",
  cargolux:"#22D3EE",
  "lufthansa-cargo":"#F97316",
  martinair:"#60A5FA",
  "atlas-charters":"#5BA9DE",
  "asl-belgium":"#A3E635",
  "old-dominion":"#A3E635",
  saia:    "#60A5FA",
  xpo:     "#FBBF24",
  estes:   "#34D399",
  "abf-freight":"#F472B6",
  "knight-swift":"#FF8A4A",
  schneider:"#FFD466",
  "jb-hunt":"#FF6F61",
  werner:  "#A78BFA",
  "yellow-corp":"#FFD400",
  "hub-group":"#34D399",
  "forward-air":"#A3E635",
  gxo:     "#5BA9DE",
  "pitt-ohio":"#FBBF24",
  rxo:     "#A78BFA",
  "ch-robinson":"#34D399",
  "covenant-logistics":"#F472B6",
  "marten-transport":"#60A5FA",
  "pam-transportation":"#FF6F61",
  "heartland-express":"#FFD466",
  "dhl-express":"#FFCC00",
  default: "#cbd5e1",
};

const CR_PLANE_PATH = "M12 2 L13.5 11 L22 13 L22 14 L13.5 14.5 L13 21 L14 22 L11 22 L10 21 L10.5 14.5 L2 14 L2 13 L10.5 11 Z";

function CarrierRadar({ user, onNav }) {
  const mapRef = React.useRef(null);
  const containerRef = React.useRef(null);
  const layersRef = React.useRef({});
  const lcRef = React.useRef(null);
  const [aircraft, setAircraft] = useStateC([]);
  const [terminals, setTerminals] = useStateC([]);
  const [strengthLanes, setStrengthLanes] = useStateC([]);
  const [fleets, setFleets] = useStateC({});  // carrier_slug → fmcsa power_units
  const [activeCarrier, setActiveCarrier] = useStateC(null);  // null = all
  const [loading, setLoading] = useStateC(true);

  const isAuthed = !!user && !!user.email;

  React.useEffect(() => {
    let alive = true;
    if (!window.SI_DB || !window.SI_DB.raw) return;
    (async () => {
      const [planes, terms, lanes, attrs] = await Promise.all([
        window.SI_DB.raw.select("cargo_aircraft",
          "select=icao24,callsign,carrier,lat,lng,altitude_m,velocity_kt,heading_deg,on_ground" +
          "&on_ground=eq.false&order=retrieved_at.desc&limit=400"
        ).catch(() => []),
        window.SI_DB.raw.select("entities",
          "select=id,slug,name,parent_id,lat,lng,address,primary_city_id&type=eq.facility_xdock"
        ).catch(() => []),
        window.SI_DB.raw.select("carrier_strength_lanes",
          "select=carrier_slug,region_label,states,strength_tier,description,source_type,source_year"
        ).catch(() => []),
        window.SI_DB.raw.select("entity_attributes",
          "select=entity_id,key,value&key=in.(fmcsa_power_units,fmcsa_drivers_count)"
        ).catch(() => []),
      ]);
      if (!alive) return;
      setAircraft(Array.isArray(planes) ? planes : []);
      setStrengthLanes(Array.isArray(lanes) ? lanes : []);

      // Resolve terminal parent slugs by joining via entities (parent_id is uuid).
      // Easiest: pull all carrier entities, build id→slug map, attach.
      const carriers = await window.SI_DB.raw.select("entities",
        "select=id,slug,name&type=eq.carrier"
      ).catch(() => []);
      const idToSlug = {};
      (carriers || []).forEach(c => { idToSlug[c.id] = c.slug; });
      const termsWithSlug = (terms || []).map(t => ({
        ...t, carrier_slug: idToSlug[t.parent_id] || null,
      })).filter(t => t.lat != null && t.lng != null);
      setTerminals(termsWithSlug);

      // Build carrier → power_units map
      const byEntity = {};
      (attrs || []).forEach(a => {
        if (!byEntity[a.entity_id]) byEntity[a.entity_id] = {};
        byEntity[a.entity_id][a.key] = a.value;
      });
      const flt = {};
      (carriers || []).forEach(c => {
        const ea = byEntity[c.id];
        if (ea && ea.fmcsa_power_units) {
          const n = parseInt(String(ea.fmcsa_power_units).replace(/[^0-9-]/g, ""), 10);
          if (Number.isFinite(n)) flt[c.slug] = n;
        }
      });
      setFleets(flt);

      setLoading(false);
    })();
    return () => { alive = false; };
  }, []);

  // Carrier filter chips. We only show chips for carriers that actually
  // have data on the map (a hub OR a terminal OR a plane).
  const presentCarriers = React.useMemo(() => {
    const set = new Set();
    CR_HUBS.forEach(h => set.add(h.carrier));
    aircraft.forEach(a => a.carrier && set.add(a.carrier));
    terminals.forEach(t => t.carrier_slug && set.add(t.carrier_slug));
    return Array.from(set).sort();
  }, [aircraft, terminals]);

  const matchesActive = (slug) => !activeCarrier || activeCarrier === slug;

  // Hub-and-spoke polylines: from each non-primary hub to its carrier's
  // primary hub. Defines the "network shape" without needing literal
  // routing data.
  const spokes = React.useMemo(() => {
    const primaryByCarrier = {};
    CR_HUBS.forEach(h => { if (h.primary) primaryByCarrier[h.carrier] = h; });
    const out = [];
    CR_HUBS.forEach(h => {
      const primary = primaryByCarrier[h.carrier];
      if (!primary || h === primary) return;
      out.push({ carrier: h.carrier, from: primary, to: h });
    });
    return out;
  }, []);

  // Mount-only: build the map.
  React.useEffect(() => {
    if (!containerRef.current || !window.L || mapRef.current) return;
    const map = window.L.map(containerRef.current, {
      zoomControl: false, scrollWheelZoom: false, attributionControl: true,
      fadeAnimation: false, zoomAnimation: false, markerZoomAnimation: false,
      worldCopyJump: false, minZoom: 3, maxZoom: 9,
      maxBounds: [[10, -175], [72, -50]],
      maxBoundsViscosity: 1.0,
    }).setView([39.5, -98.5], 4);
    window.L.tileLayer(
      "https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png",
      {
        attribution: "© OpenStreetMap · © CARTO", subdomains: "abcd", maxZoom: 9,
        noWrap: true, bounds: [[-90, -180], [90, 180]],
      }
    ).addTo(map);
    window.L.control.zoom({ position: "bottomright" }).addTo(map);
    mapRef.current = map;
    setTimeout(() => map.invalidateSize(), 80);
    return () => { map.remove(); mapRef.current = null; };
  }, []);

  // Layer build.
  React.useEffect(() => {
    const map = mapRef.current;
    if (!map || !window.L) return;

    // Capture old layers before clearing so we can also remove them from
    // the layer control (otherwise entries duplicate on every refresh).
    const oldLayers = Object.values(layersRef.current);
    oldLayers.forEach(lg => {
      if (lg && map.hasLayer(lg)) map.removeLayer(lg);
    });
    layersRef.current = {};

    function dotIcon(color, size, label, primary) {
      const html = `
        <span class="cr-hub-dot${primary ? ' cr-hub-primary' : ''}" style="
          width:${size}px;height:${size}px;background:${color};
        ">${primary ? `<span class="cr-hub-ring" style="border-color:${color}"></span>` : ""}</span>
        ${label ? `<span class="cr-hub-label">${label}</span>` : ""}`;
      return window.L.divIcon({
        className: "cr-hub-icon", html,
        iconSize: [size + 6, size + 6],
        iconAnchor: [(size + 6) / 2, (size + 6) / 2],
      });
    }
    function planeIcon(a) {
      const heading = a.heading_deg ?? 0;
      const color = CR_COLOR[a.carrier] || CR_COLOR.default;
      const html = `
        <svg viewBox="0 0 24 24" width="13" height="13"
             style="transform:rotate(${heading - 45}deg);transform-origin:50% 50%;
                    filter:drop-shadow(0 0 2px rgba(0,0,0,0.6))">
          <path d="${CR_PLANE_PATH}" fill="${color}" stroke="rgba(0,0,0,0.5)" stroke-width="0.5"/>
        </svg>`;
      return window.L.divIcon({
        className: "cr-plane", html,
        iconSize: [16, 16], iconAnchor: [8, 8],
      });
    }

    // Hub spokes — drawn first so markers sit on top.
    const spokeLayer = window.L.layerGroup(spokes
      .filter(s => matchesActive(s.carrier))
      .map(s => {
        const color = CR_COLOR[s.carrier] || CR_COLOR.default;
        return window.L.polyline(
          [[s.from.lat, s.from.lng], [s.to.lat, s.to.lng]],
          { color, weight: activeCarrier ? 1.8 : 1.0,
            opacity: activeCarrier ? 0.55 : 0.18,
            interactive: false }
        );
      }));

    // Hubs
    const hubLayer = window.L.layerGroup(CR_HUBS
      .filter(h => matchesActive(h.carrier))
      .map(h => {
        const color = CR_COLOR[h.carrier] || CR_COLOR.default;
        const size = h.primary ? 18 : 9;
        const m = window.L.marker([h.lat, h.lng], {
          icon: dotIcon(color, size, "", h.primary),
          riseOnHover: true,
        });
        const fleet = fleets[h.carrier];
        const popup = isAuthed ? `
          <div class="cr-pop">
            <div class="cr-pop-eye" style="color:${color}">📦 ${h.carrierLabel} ${h.primary ? "· primary hub" : "· hub"}</div>
            <div class="cr-pop-num">${h.name}</div>
            <div class="cr-pop-meta">
              ${h.city}
              ${fleet ? ` · network fleet: ${fleet.toLocaleString()} trucks (FMCSA)` : ""}
            </div>
          </div>` : `
          <div class="cr-pop">
            <div class="cr-pop-eye" style="color:${color}">📦 ${h.carrierLabel} hub</div>
            <div class="cr-pop-meta cr-pop-cta">Sign in for hub name · throughput · network detail →</div>
          </div>`;
        m.bindPopup(popup);
        return m;
      }));

    // Terminals (LTL/TL cross-docks)
    const terminalLayer = window.L.layerGroup(terminals
      .filter(t => matchesActive(t.carrier_slug))
      .map(t => {
        const color = CR_COLOR[t.carrier_slug] || CR_COLOR.default;
        const m = window.L.marker([t.lat, t.lng], {
          icon: dotIcon(color, 7, ""),
          riseOnHover: true,
        });
        const popup = isAuthed ? `
          <div class="cr-pop">
            <div class="cr-pop-eye" style="color:${color}">🚚 ${(t.carrier_slug || "").replace(/-/g," ").toUpperCase()} terminal</div>
            <div class="cr-pop-num">${t.name}</div>
            <div class="cr-pop-meta">${t.address || ""}</div>
          </div>` : `
          <div class="cr-pop">
            <div class="cr-pop-eye" style="color:${color}">🚚 LTL terminal</div>
            <div class="cr-pop-meta cr-pop-cta">Sign in for carrier · address →</div>
          </div>`;
        m.bindPopup(popup);
        return m;
      }));

    // Aircraft
    const planeLayer = window.L.layerGroup(aircraft
      .filter(a => a.lat != null && a.lng != null && !a.on_ground && matchesActive(a.carrier))
      .map(a => {
        const color = CR_COLOR[a.carrier] || CR_COLOR.default;
        const m = window.L.marker([a.lat, a.lng], { icon: planeIcon(a), riseOnHover: true });
        const cName = (a.carrier || "").replace(/-/g, " ").toUpperCase();
        const popup = isAuthed ? `
          <div class="cr-pop">
            <div class="cr-pop-eye" style="color:${color}">✈ ${a.callsign || a.icao24} · ${cName}</div>
            <div class="cr-pop-num">${a.velocity_kt ?? "?"} kt</div>
            <div class="cr-pop-meta">
              ${a.altitude_m != null ? `${Math.round(a.altitude_m * 3.281).toLocaleString()} ft` : "—"}
              · heading ${Math.round(a.heading_deg ?? 0)}°
            </div>
          </div>` : `
          <div class="cr-pop">
            <div class="cr-pop-eye" style="color:${color}">✈ ${cName} flight</div>
            <div class="cr-pop-meta cr-pop-cta">Sign in for callsign · altitude · routing →</div>
          </div>`;
        m.bindPopup(popup);
        return m;
      }));

    spokeLayer.addTo(map);
    hubLayer.addTo(map);
    terminalLayer.addTo(map);
    planeLayer.addTo(map);
    layersRef.current = { spokes: spokeLayer, hubs: hubLayer, terminals: terminalLayer, planes: planeLayer };

    if (!lcRef.current) {
      lcRef.current = window.L.control.layers(null, {}, {
        collapsed: false, position: "bottomleft",
      }).addTo(map);
    } else {
      oldLayers.forEach(lg => lcRef.current.removeLayer(lg));
    }
    const visiblePlanes = aircraft.filter(a => !a.on_ground && matchesActive(a.carrier)).length;
    const visibleHubs = CR_HUBS.filter(h => matchesActive(h.carrier)).length;
    const visibleTerminals = terminals.filter(t => matchesActive(t.carrier_slug)).length;
    lcRef.current.addOverlay(spokeLayer,    `🌐 Hub-and-spoke (${spokes.filter(s => matchesActive(s.carrier)).length})`);
    lcRef.current.addOverlay(hubLayer,      `📦 Small-pkg hubs (${visibleHubs})`);
    lcRef.current.addOverlay(terminalLayer, `🚚 LTL terminals (${visibleTerminals})`);
    lcRef.current.addOverlay(planeLayer,    `✈ Aircraft live (${visiblePlanes})`);
  }, [aircraft, terminals, spokes, fleets, activeCarrier, isAuthed]);

  // Carrier filter chip data — only carriers with hubs/aircraft/terminals.
  const chips = React.useMemo(() => {
    return presentCarriers.map(slug => {
      const label = (CR_HUBS.find(h => h.carrier === slug)?.carrierLabel)
        || slug.replace(/-/g, " ").replace(/\b\w/g, c => c.toUpperCase());
      const planeCount = aircraft.filter(a => a.carrier === slug && !a.on_ground).length;
      const hubCount   = CR_HUBS.filter(h => h.carrier === slug).length;
      const fleet      = fleets[slug] || null;
      return { slug, label, planeCount, hubCount, fleet, color: CR_COLOR[slug] || CR_COLOR.default };
    }).sort((a, b) => (b.planeCount + b.hubCount * 3) - (a.planeCount + a.hubCount * 3));
  }, [presentCarriers, aircraft, fleets]);

  const totalPlanes = aircraft.filter(a => !a.on_ground).length;

  return (
    <section className="cr-radar">
      <style>{`
        .cr-radar { position: relative; background: #0a0e15; overflow: hidden;
          border-bottom: 1px solid #1f2937; }
        .cr-radar-map { width: 100%; height: 72vh; min-height: 540px; max-height: 760px;
          background: #0a0e15; }
        @media (max-width: 760px) { .cr-radar-map { height: 64vh; min-height: 420px; } }
        /* Subtle radial glow at center to suggest a "scope" */
        .cr-radar-map::after {
          content: ""; position: absolute; inset: 0; pointer-events: none;
          background: radial-gradient(ellipse at center, transparent 50%, rgba(10,14,21,0.55) 100%);
          z-index: 401;
        }
        .cr-hub-icon { background: transparent !important; border: 0 !important; }
        .cr-hub-dot {
          display: inline-block; border-radius: 50%;
          border: 1.5px solid rgba(255,255,255,0.6); position: relative;
          box-shadow: 0 0 6px rgba(0,0,0,0.6);
        }
        .cr-hub-primary .cr-hub-ring {
          content: ""; position: absolute; inset: -8px; border-radius: 50%;
          border: 2px solid; opacity: 0.55;
          animation: cr-hub-pulse 2.4s ease-out infinite;
        }
        @keyframes cr-hub-pulse {
          0% { transform: scale(1); opacity: 0.55; }
          80%, 100% { transform: scale(2.6); opacity: 0; }
        }
        .cr-plane { background: transparent !important; border: 0 !important; }

        /* Floating chrome */
        .cr-title {
          position: absolute; top: 18px; left: 22px; z-index: 500;
          color: #fff; pointer-events: none; max-width: 600px;
        }
        .cr-title-eye {
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.18em;
          text-transform: uppercase; color: #5BA9DE;
          display: inline-flex; align-items: center; gap: 8px;
          padding: 6px 10px; background: rgba(0,0,0,0.5); border-radius: 4px;
          backdrop-filter: blur(6px);
        }
        .cr-title-eye .dot {
          display: inline-block; width: 8px; height: 8px; border-radius: 50%;
          background: #5BA9DE;
          animation: cr-livedot 1.6s ease-in-out infinite;
        }
        @keyframes cr-livedot {
          0%, 100% { box-shadow: 0 0 0 0 rgba(91,169,222,0.6); }
          70% { box-shadow: 0 0 0 8px rgba(91,169,222,0); }
        }
        .cr-title-h {
          font-family: var(--font-serif); font-size: clamp(28px, 4vw, 44px);
          line-height: 1.05; letter-spacing: -0.025em;
          margin: 12px 0 6px;
          text-shadow: 0 2px 16px rgba(0,0,0,0.6);
        }
        .cr-title-h em { font-style: italic; color: #5BA9DE; }
        .cr-title-sub {
          font-size: 14px; color: #cbd5e1; line-height: 1.45;
          text-shadow: 0 1px 8px rgba(0,0,0,0.6);
        }

        /* Filter chips — single-line horizontal scroller along the bottom.
           Sits right of the layer control (bottom-left) and left of the
           zoom control (bottom-right). Mask both edges so the scroll
           feels intentional, not chopped. */
        .cr-chips {
          position: absolute; bottom: 18px; left: 50%; transform: translateX(-50%);
          z-index: 500; display: flex; flex-wrap: nowrap; gap: 6px;
          padding: 8px 12px; background: rgba(10,14,21,0.85);
          border: 1px solid rgba(255,255,255,0.08); border-radius: 8px;
          backdrop-filter: blur(10px); max-width: min(720px, 64vw);
          overflow-x: auto; overflow-y: hidden;
          scrollbar-width: thin; scrollbar-color: rgba(255,255,255,0.18) transparent;
          mask-image: linear-gradient(90deg, transparent 0, #000 4%, #000 96%, transparent 100%);
        }
        .cr-chips::-webkit-scrollbar { height: 4px; }
        .cr-chips::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.18); border-radius: 2px; }
        @media (max-width: 760px) {
          .cr-chips { max-width: 88vw; bottom: 12px; }
        }
        .cr-chip {
          display: inline-flex; align-items: center; gap: 6px;
          background: transparent; border: 1px solid rgba(255,255,255,0.12);
          padding: 5px 10px; border-radius: 999px; cursor: pointer;
          font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.06em;
          text-transform: uppercase; color: #cbd5e1;
          transition: all 0.15s; flex-shrink: 0;
        }
        .cr-chip:hover { background: rgba(255,255,255,0.06); }
        .cr-chip[data-active="true"] {
          background: var(--chip-c, #fff); color: #0a0e15;
          border-color: var(--chip-c, #fff);
        }
        .cr-chip-dot { display: inline-block; width: 7px; height: 7px;
          border-radius: 50%; background: var(--chip-c, #fff); }
        .cr-chip-meta { font-size: 9px; opacity: 0.75; margin-left: 2px; }

        .cr-cta-overlay {
          position: absolute; top: 18px; right: 22px; z-index: 500;
          background: rgba(10,14,21,0.85); backdrop-filter: blur(10px);
          border: 1px solid rgba(91,169,222,0.35); border-radius: 8px;
          padding: 14px 18px; max-width: 320px; color: #f1f5f9;
          box-shadow: 0 12px 36px rgba(0,0,0,0.4);
        }
        .cr-cta-eye { font-family: var(--font-mono); font-size: 10px;
          letter-spacing: 0.18em; text-transform: uppercase;
          color: #5BA9DE; margin-bottom: 6px; }
        .cr-cta-h { font-family: var(--font-serif); font-size: 17px;
          letter-spacing: -0.015em; margin: 0 0 6px; }
        .cr-cta-sub { font-size: 12px; color: #94a3b8; line-height: 1.45;
          margin-bottom: 10px; }
        .cr-cta-btn {
          display: inline-flex; align-items: center; gap: 6px;
          background: #5BA9DE; color: #0a0e15; border: 0;
          padding: 8px 14px; border-radius: 5px; font-family: inherit;
          font-weight: 600; font-size: 13px; cursor: pointer;
        }

        /* Layer control + popup styles same as homepage radar */
        .leaflet-control-layers {
          background: rgba(10,14,21,0.85) !important;
          backdrop-filter: blur(10px);
          border: 1px solid rgba(255,255,255,0.08) !important;
          border-radius: 6px !important;
          padding: 10px 12px !important;
          color: #cbd5e1 !important;
          font-family: var(--font-mono); font-size: 11px;
        }
        .leaflet-control-layers label { color: #cbd5e1 !important; }
        .leaflet-popup-content-wrapper {
          background: rgba(10,14,21,0.95) !important; color: #f1f5f9;
          border: 1px solid rgba(255,255,255,0.08); border-radius: 8px;
        }
        .leaflet-popup-tip { background: rgba(10,14,21,0.95) !important; }
        .leaflet-popup-close-button { color: #94a3b8 !important; }
        .leaflet-control-zoom a {
          background: rgba(10,14,21,0.85) !important; color: #cbd5e1 !important;
          border: 1px solid rgba(255,255,255,0.08) !important;
        }
        .cr-pop { font-family: var(--font-sans, system-ui); min-width: 200px; padding: 4px 2px; }
        .cr-pop-eye { font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.14em;
          text-transform: uppercase; margin-bottom: 4px; }
        .cr-pop-num { font-family: var(--font-serif); font-size: 18px;
          letter-spacing: -0.01em; color: #f1f5f9; }
        .cr-pop-meta { font-size: 11px; color: #94a3b8; margin-top: 4px; line-height: 1.45; }
        .cr-pop-cta { color: #5BA9DE; font-weight: 500; }
      `}</style>

      <div ref={containerRef} className="cr-radar-map" />

      <div className="cr-title">
        <span className="cr-title-eye">
          <span className="dot" />
          {loading
            ? "Loading network…"
            : `${activeCarrier ? activeCarrier.toUpperCase() : "All carriers"} · ${totalPlanes} aircraft live`}
        </span>
        <h1 className="cr-title-h">
          Where the <em>freight runs.</em>
        </h1>
        <p className="cr-title-sub">
          Every named hub. Every cross-dock terminal. Every cargo aircraft we can see in the air right now.
          {" "}{Object.keys(fleets).length > 0 && `Combined fleet: ${Object.values(fleets).reduce((s,n)=>s+n,0).toLocaleString()} power units (FMCSA).`}
        </p>
      </div>

      {!isAuthed && (
        <div className="cr-cta-overlay">
          <div className="cr-cta-eye"><span style={{display:"inline-block",width:6,height:6,borderRadius:"50%",background:"#5BA9DE",marginRight:6,verticalAlign:"middle"}}/>Anonymous view</div>
          <h3 className="cr-cta-h">The full network is one click away.</h3>
          <p className="cr-cta-sub">
            Click any pin to see "sign in for details." Free magic-link · no password.
          </p>
          <button className="cr-cta-btn" onClick={() => onNav("signin")}>Sign in →</button>
        </div>
      )}

      <div className="cr-chips">
        <button className="cr-chip" data-active={activeCarrier === null}
                onClick={() => setActiveCarrier(null)}>
          ALL · {chips.length}
        </button>
        {chips.map(c => (
          <button key={c.slug} className="cr-chip"
                  data-active={activeCarrier === c.slug}
                  style={{ "--chip-c": c.color }}
                  onClick={() => setActiveCarrier(activeCarrier === c.slug ? null : c.slug)}>
            <span className="cr-chip-dot" />
            {c.label}
            <span className="cr-chip-meta">
              {c.hubCount > 0 ? `${c.hubCount}h ` : ""}
              {c.planeCount > 0 ? `${c.planeCount}✈` : ""}
            </span>
          </button>
        ))}
      </div>
    </section>
  );
}

function CarriersPage({ onNav, onCarrier }) {
  const { LA_REPORT, SHIPPING_CATEGORIES } = window.SI_DATA;
  const allCarriers = Object.entries(LA_REPORT.carriers).flatMap(([cat, list]) =>
    list.map(c => ({ ...c, cat }))
  ).sort((a, b) => b.score - a.score);
  const [user, setUser] = useStateC(null);
  useEffectC(() => {
    let alive = true;
    if (window.SI_DB && window.SI_DB.auth && window.SI_DB.auth.getCurrentUser) {
      window.SI_DB.auth.getCurrentUser().then(u => { if (alive) setUser(u); }).catch(() => {});
    }
    return () => { alive = false; };
  }, []);
  return (
    <div className="page-carriers">
      {/* CARRIER RADAR — focal element of /#/carriers. Public-source data
          only: hubs + terminals + cargo aircraft + 10-K-derived corridors.
          No driver pipeline, no scraped data. */}
      <CarrierRadar user={user} onNav={onNav} />
      <section className="carriers-list-section">
        <div className="carriers-list-inner">
          <div className="carriers-list-head">
            <div>{allCarriers.length} carriers · sorted by Clarity Score</div>
          </div>
          <div className="carriers-list">
            {allCarriers.map((c, i) => {
              const catLabel = SHIPPING_CATEGORIES.find(s => s.id === c.cat)?.short;
              return (
                <button key={c.id + c.cat} className="carrier-list-row" onClick={() => onCarrier(c.id)}>
                  <span className="rank-num">{String(i+1).padStart(2,"0")}</span>
                  <span className="carrier-logo-dot" style={{ background: window.carrierColor(c.id) }}>{c.name[0]}</span>
                  <div className="cl-name">
                    <div className="cl-name-main">{c.name} {c.sponsored && <SponsoredTag />}</div>
                    <div className="cl-name-sub">{catLabel} · {c.shipments} shipments tracked in LA</div>
                  </div>
                  <span className="cl-trend"><TrendArrow trend={c.trend} /></span>
                  <span className="cl-score">{c.score}</span>
                  <LetterBadge score={c.score} size="md" />
                  <span className="cl-arrow">→</span>
                </button>
              );
            })}
          </div>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { CarrierPage, MembersPage, CarriersPage, CarrierIntelFeed });
