// Shipper dossier page — /#/sh/<slug>
//
// Sister to page-carrier-detail.jsx. The /sh prefix avoids collision with
// the /#/shippers directory route. Adapted fields: industry, freight
// spend, DC + store counts, primary carriers, primary lanes; no fleet
// or safety blocks. Hex US map rebadged as "DC + retail footprint."

const { useState: useStateSD, useEffect: useEffectSD, useMemo: useMemoSD } = React;

const HEX_LAYOUT_SD = [
  ["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],
];

const STATE_NAMES_SD = {
  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",
};

// Shipper "footprint" = where their DCs + stores live. Population-weighted
// for retail; cluster around HQ + supply-chain corridors for industrial.
function mockShipperFootprint(shipper) {
  const rank = shipper.rank || 100;
  const hq = (shipper.hq_state || "").toUpperCase();
  const industry = (shipper.industry || "").toLowerCase();
  let seed = 0;
  for (const c of shipper.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_SD);
  const dist = {};
  // Population-weighted retail bias.
  const retailHeavy = ["CA","TX","FL","NY","PA","IL","OH","GA","NC","MI","NJ","VA","WA","AZ","TN","IN","MA","MO","MD","WI","CO"];
  const cpgHeavy = ["TX","CA","IL","OH","PA","GA","FL","IN","TN","NC","WI","MO","NJ"];
  const industrialHeavy = ["TX","OH","MI","IL","IN","PA","CA","KY","TN","NC","WI"];
  let aff = retailHeavy;
  if (industry.includes("cpg") || industry.includes("food") || industry.includes("grocery") || industry.includes("beverage")) aff = cpgHeavy;
  else if (industry.includes("industrial") || industry.includes("automotive") || industry.includes("chemical")) aff = industrialHeavy;

  for (const s of aff) dist[s] = 40 + rand() * 60;
  if (STATE_NAMES_SD[hq] && !dist[hq]) dist[hq] = 70 + rand() * 30;
  const reach = Math.min(50, Math.max(10, Math.round(55 - rank * 0.4)));
  const remaining = states.filter((s) => !dist[s]);
  const pickCount = Math.min(reach - aff.length, 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 HexUSMapSD({ values }) {
  const [hover, setHover] = useStateSD(null);
  const sortedVals = Object.values(values).sort((a, b) => b - a);
  const max = sortedVals[0] || 1;
  function colorFor(v) {
    if (v == null) return "rgba(255,255,255,0.05)";
    const t = v / max;
    if (t < 0.04) return "rgba(95,169,255,0.10)";
    if (t < 0.20) return "rgba(95,169,255,0.28)";
    if (t < 0.40) return "rgba(95,169,255,0.50)";
    if (t < 0.65) return "rgba(95,169,255,0.75)";
    return "rgba(95,169,255,1.00)";
  }
  const HEX_W = 56, HEX_H = 64, ROW_H = 50, COL_W = 56;
  const cols = Math.max(...HEX_LAYOUT_SD.map((s) => s[1])) + 1;
  const rows = Math.max(...HEX_LAYOUT_SD.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_SD.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_SD[hover] || hover}</div>
          <div style={{ opacity: 0.7, fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em" }}>
            {values[hover] != null ? `${Math.round(values[hover])} est. footprint score` : "no signal"}
          </div>
        </div>
      )}
    </div>
  );
}

function deriveShipperVerdict(shipper, dossier) {
  if (shipper.verdict_override === "distress") return { tier: "distress", label: "▲ Distress", trustScore: 42, why: (shipper.notes || "").split(";")[0].slice(0, 140) + "…" };
  if (shipper.verdict_override === "watch")    return { tier: "watch",    label: "⚠ Watch",    trustScore: 62, why: (shipper.notes || "").split(";")[0].slice(0, 140) + "…" };
  if (shipper.verdict_override === "no_flags") return { tier: "no_flags", label: "○ No flags", trustScore: 78, why: "Editor reviewed and cleared." };
  const notes = (shipper.notes || "").toLowerCase();
  // Tightened: 'covenant' false-positives on company names; specific phrases only.
  const distress = [
    "bankruptcy", "chapter 11", "going concern", "going-concern",
    "covenant violation", "covenant breach", "covenant default",
    "delisting", "restatement", "fraud", "indictment",
  ];
  const watch = [
    "downsizing", "warehouse closure", "layoffs", "warn act",
    "spin-off", "underperform", "lawsuit", "consolidating",
  ];
  let tier = "no_flags", label = "○ No flags", trustScore = 78;
  let why = "No public-record red flag in the last 24 months. (Heuristic — not a positive verification.)";
  // Heuristic Distress is downgraded — Distress requires editor approval.
  for (const m of distress) if (notes.includes(m)) { tier = "watch"; label = "⚠ Watch"; trustScore = 62; why = (shipper.notes || "").split(";")[0].slice(0, 140) + "…"; break; }
  if (tier === "no_flags") for (const m of watch) if (notes.includes(m)) { tier = "watch"; label = "⚠ Watch"; trustScore = 62; why = (shipper.notes || "").split(";")[0].slice(0, 140) + "…"; break; }
  const sigs = dossier && dossier.signals_json;
  if (Array.isArray(sigs) && sigs.some((s) => (s.severity || "").toLowerCase() === "critical") && tier === "no_flags") {
    tier = "watch"; label = "⚠ Watch"; trustScore = 58; why = "SEC EDGAR critical events on the public record.";
  }
  return { tier, label, why, trustScore };
}

function fmtRevenueSD(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 fmtCount(n) {
  if (!n) return "—";
  return n.toLocaleString("en-US");
}
function fmtAgeSD(s) {
  if (!s.founded) return "—";
  const yrs = (new Date()).getFullYear() - s.founded;
  return `${s.founded} · ${yrs} yrs`;
}

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

  useEffectSD(() => {
    if (!slug) return;
    let cancelled = false;
    setLoading(true);
    setError(null);
    fetch(`/api/shipper-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) { setError(String(e.message || e)); setLoading(false); }});
    return () => { cancelled = true; };
  }, [slug]);

  useEffectSD(() => {
    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`;
        return `${Math.floor(s / 60)}m ago`;
      };
      setUpdatedAgo(fmt());
    };
    tick();
    const id = setInterval(tick, 30000);
    return () => clearInterval(id);
  }, [data]);

  const verdict = useMemoSD(() => (data ? deriveShipperVerdict(data.shipper, data.dossier) : null), [data]);
  const stateValues = useMemoSD(() => (data ? mockShipperFootprint(data.shipper) : {}), [data]);
  const topStates = useMemoSD(() => Object.entries(stateValues).sort((a, b) => b[1] - a[1]).slice(0, 8), [stateValues]);

  if (!slug) {
    return (
      <div style={pageStyleSD}>
        <div style={{ padding: 64, textAlign: "center", color: "#fff" }}>
          <h1 style={{ fontSize: 32 }}>Pick a shipper</h1>
          <p style={{ opacity: 0.7 }}>Try /#/sh/walmart or /#/sh/amazon-com.</p>
          <button onClick={() => onNav && onNav("home")} style={btnGhostSD}>← Home</button>
        </div>
      </div>
    );
  }
  if (loading) return <div style={pageStyleSD}><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={pageStyleSD}>
        <div style={{ padding: 64, textAlign: "center", color: "#fff", maxWidth: 560, margin: "0 auto" }}>
          <h1 style={{ fontSize: 32, marginBottom: 12 }}>No shipper matched <code>{slug}</code></h1>
          <p style={{ opacity: 0.7, marginBottom: 24 }}>
            We currently cover the Top 100 U.S. shippers by inferred freight spend. Try{" "}
            <code>amazon-com</code>, <code>walmart</code>, <code>general-motors</code>,{" "}
            <code>ford-motor</code>, <code>costco</code>, <code>kroger</code>.
          </p>
          <button onClick={() => onNav && onNav("home")} style={btnGhostSD}>← Home</button>
        </div>
      </div>
    );
  }
  if (error) return <div style={pageStyleSD}><div style={{ padding: 64, color: "#fff", maxWidth: 560, margin: "0 auto" }}><h1>Couldn't load this dossier</h1><p style={{ opacity: 0.7 }}>{error}</p><button onClick={() => onNav && onNav("home")} style={btnGhostSD}>← Home</button></div></div>;

  const s = data.shipper;
  const verdictColor = verdict.tier === "distress" ? "#ff6868" : verdict.tier === "watch" ? "#ffb84d" : "#5fd9a8";
  const freightPct = s.freight_spend_pct_of_revenue ? `${Number(s.freight_spend_pct_of_revenue).toFixed(1)}%` : null;

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

        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16, color: "rgba(255,255,255,0.65)", fontSize: 13 }}>
          <div>
            <a href="#/" style={linkStyleSD}>← Shipping Clarity</a>
            <span style={{ margin: "0 8px", opacity: 0.4 }}>/</span>
            <span style={{ opacity: 0.7 }}>Shipper 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>

        {/* Identity + Verdict */}
        <div style={gridRowSD(["8fr","4fr"])}>
          <CardSD>
            <EyebrowSD>SHIPPER IDENTITY</EyebrowSD>
            <h1 style={{ fontSize: 44, fontWeight: 800, lineHeight: 1.05, letterSpacing: "-0.02em", margin: "8px 0 4px" }}>{s.name}</h1>
            {s.parent && s.parent !== s.name && <div style={{ fontSize: 16, opacity: 0.55, marginBottom: 16 }}>{s.parent}</div>}
            <div style={{ display: "flex", flexWrap: "wrap", gap: "10px 24px", marginTop: 14, fontSize: 14 }}>
              {s.industry && <AttrSD label="Industry" value={s.industry.toUpperCase().replace(/-/g, " ")} />}
              {s.sub_industry && <AttrSD label="Sub-industry" value={s.sub_industry.toUpperCase().replace(/-/g, " ")} />}
              {s.hq_city && <AttrSD label="HQ" value={`${s.hq_city}, ${s.hq_state || ""}`} />}
              {s.ownership && <AttrSD label="Ownership" value={s.ownership.toUpperCase()} />}
              {s.founded && <AttrSD label="Founded" value={fmtAgeSD(s)} />}
              {s.public && s.ticker && <AttrSD label="Ticker" value={s.ticker} />}
              {s.rank && <AttrSD label="Top 100 rank" value={`#${s.rank}`} />}
              {data.enrichment && data.enrichment.parent && data.enrichment.parent !== "unknown" && data.enrichment.parent !== s.parent && (
                <AttrSD label="Parent" value={data.enrichment.parent} />
              )}
            </div>
          </CardSD>
          <CardSD style={{ borderLeft: `4px solid ${verdictColor}` }}>
            <EyebrowSD>TRUST VERDICT</EyebrowSD>
            <div style={{ fontSize: 32, fontWeight: 800, color: verdictColor, marginTop: 8, letterSpacing: "-0.02em" }}>{verdict.label}</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>
          </CardSD>
        </div>

        {/* Hero stats */}
        <div style={gridRowSD(["3fr","3fr","3fr","3fr"])}>
          <StatCardSD label="Annual freight spend" value={fmtRevenueSD(s.estimated_freight_spend_usd)} sub="Est. revenue × industry %" />
          <StatCardSD label="2024 revenue" value={fmtRevenueSD(s.annual_revenue_2024_usd)} sub={s.public ? "10-K reported" : "Industry estimate"} />
          <StatCardSD label="US distribution centers" value={fmtCount(s.us_dc_count_estimate)} sub="Estimate" />
          {s.us_store_count_estimate ? (
            <StatCardSD label="US retail outlets" value={fmtCount(s.us_store_count_estimate)} sub="Estimate" />
          ) : (
            <CardSD>
              <EyebrowSD>FREIGHT INTENSITY</EyebrowSD>
              <div style={{ fontSize: 36, fontWeight: 800, marginTop: 8, lineHeight: 1, letterSpacing: "-0.02em" }}>
                {freightPct || "—"}
              </div>
              <div style={{ fontSize: 12, opacity: 0.6, marginTop: 8 }}>
                Freight as % of revenue · industry-typical
              </div>
            </CardSD>
          )}
        </div>

        {/* Hex map + companion */}
        <div style={gridRowSD(["8fr","4fr"])}>
          <CardSD>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
              <EyebrowSD>{s.us_store_count_estimate ? "DC + RETAIL FOOTPRINT" : "DC + INBOUND FOOTPRINT"}</EyebrowSD>
              <ProvisionalBadgeSD />
            </div>
            <HexUSMapSD 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 · est. inbound + outbound footprint</span>
            </div>
          </CardSD>
          <CardSD>
            <EyebrowSD>TOP STATES</EyebrowSD>
            <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_SD[abbr] || abbr}</span>
                  <span style={{ opacity: 0.85, fontVariantNumeric: "tabular-nums" }}>{Math.round(v)}</span>
                </li>
              ))}
            </ol>
          </CardSD>
        </div>

        {/* Carrier mix + lanes */}
        <div style={gridRowSD(["6fr","6fr"])}>
          <CardSD>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <EyebrowSD>PRIMARY CARRIERS</EyebrowSD>
              {(!s.primary_carriers || s.primary_carriers.length === 0) && <ProvisionalBadgeSD />}
            </div>
            {s.primary_carriers && s.primary_carriers.length > 0 ? (
              <div style={{ marginTop: 14, display: "flex", flexWrap: "wrap", gap: 8 }}>
                {s.primary_carriers.map((c, i) => (
                  <span key={i} style={{ padding: "6px 12px", background: "rgba(95,169,255,0.08)", border: "1px solid rgba(95,169,255,0.3)", borderRadius: 999, fontSize: 13 }}>
                    {c}
                  </span>
                ))}
              </div>
            ) : (
              <div style={{ marginTop: 14, fontSize: 13, opacity: 0.6 }}>
                Primary carrier roster not yet attributed for this shipper. EDGAR + Wayback ImportYeti pass next.
              </div>
            )}
          </CardSD>
          <CardSD>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <EyebrowSD>PRIMARY LANES</EyebrowSD>
              {(!s.primary_lanes_estimate || s.primary_lanes_estimate.length === 0) && <ProvisionalBadgeSD />}
            </div>
            {s.primary_lanes_estimate && s.primary_lanes_estimate.length > 0 ? (
              <ul style={{ margin: "12px 0 0", padding: 0, listStyle: "none", fontSize: 13 }}>
                {s.primary_lanes_estimate.slice(0, 8).map((l, i) => (
                  <li key={i} style={{ padding: "8px 0", borderBottom: "1px solid rgba(255,255,255,0.06)" }}>{l}</li>
                ))}
              </ul>
            ) : (
              <div style={{ marginTop: 14, fontSize: 13, opacity: 0.6 }}>
                Primary lane attribution pending — sourced from DAT public lane heat + EDGAR major-customer disclosures.
              </div>
            )}
          </CardSD>
        </div>

        {/* Commodities + DC metros (Sonnet enrichment) */}
        {data.enrichment && (
          (Array.isArray(data.enrichment.primary_commodities) && data.enrichment.primary_commodities.length > 0) ||
          (Array.isArray(data.enrichment.key_dc_metros)        && data.enrichment.key_dc_metros.length > 0) ||
          (Array.isArray(data.enrichment.subsidiaries)         && data.enrichment.subsidiaries.length > 0)
        ) && (
          <div style={gridRowSD(["6fr","6fr"])}>
            <CardSD>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                <EyebrowSD>WHAT THEY SHIP MOST</EyebrowSD>
                <span style={{ fontSize: 10, opacity: 0.45, fontFamily: "var(--font-mono)" }}>SONNET-DERIVED</span>
              </div>
              {Array.isArray(data.enrichment.primary_commodities) && data.enrichment.primary_commodities.length > 0 ? (
                <div style={{ marginTop: 14, display: "flex", flexWrap: "wrap", gap: 8 }}>
                  {data.enrichment.primary_commodities
                    .filter(c => c && c !== "unknown")
                    .map((c, i) => (
                      <span key={i} style={{ padding: "6px 12px", background: "rgba(95,217,168,0.10)", border: "1px solid rgba(95,217,168,0.35)", borderRadius: 999, fontSize: 13, textTransform: "capitalize" }}>
                        {c}
                      </span>
                    ))}
                </div>
              ) : (
                <div style={{ marginTop: 14, fontSize: 13, opacity: 0.6 }}>
                  Commodity profile pending — re-run the Sonnet enrichment.
                </div>
              )}
              {Array.isArray(data.enrichment.subsidiaries) && data.enrichment.subsidiaries.filter(s => s && s !== "unknown").length > 0 && (
                <div style={{ marginTop: 18 }}>
                  <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em", opacity: 0.5, marginBottom: 6 }}>
                    Notable subsidiaries
                  </div>
                  <div style={{ fontSize: 13, opacity: 0.75, lineHeight: 1.5 }}>
                    {data.enrichment.subsidiaries.filter(x => x && x !== "unknown").slice(0, 8).join(" · ")}
                  </div>
                </div>
              )}
            </CardSD>
            <CardSD>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                <EyebrowSD>KEY DC METROS</EyebrowSD>
                <span style={{ fontSize: 10, opacity: 0.45, fontFamily: "var(--font-mono)" }}>SONNET-DERIVED</span>
              </div>
              {Array.isArray(data.enrichment.key_dc_metros) && data.enrichment.key_dc_metros.length > 0 ? (
                <ol style={{ margin: "12px 0 0", padding: 0, listStyle: "none", fontSize: 13 }}>
                  {data.enrichment.key_dc_metros
                    .filter(m => m && m !== "unknown")
                    .slice(0, 6)
                    .map((m, i) => (
                      <li key={i} style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", borderBottom: "1px solid rgba(255,255,255,0.06)" }}>
                        <span><strong style={{ opacity: 0.45, marginRight: 8 }}>{i + 1}.</strong>{m}</span>
                      </li>
                    ))}
                </ol>
              ) : (
                <div style={{ marginTop: 14, fontSize: 13, opacity: 0.6 }}>
                  DC metro list pending — re-run the Sonnet enrichment.
                </div>
              )}
            </CardSD>
          </div>
        )}

        {/* Editorial note + facts */}
        <div style={gridRowSD(["12fr"])}>
          <CardSD>
            <EyebrowSD>CORPORATE NOTE</EyebrowSD>
            <div style={{ marginTop: 12, fontSize: 14, lineHeight: 1.55, opacity: 0.85 }}>
              {s.notes || "No editorial note on file."}
            </div>
            {s.notable_facts && s.notable_facts.length > 0 && (
              <div style={{ marginTop: 18 }}>
                <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em", opacity: 0.5, marginBottom: 6 }}>
                  Notable facts
                </div>
                <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, lineHeight: 1.6 }}>
                  {s.notable_facts.slice(0, 6).map((f, i) => (<li key={i}>{f}</li>))}
                </ul>
              </div>
            )}
            {s.primary_source_url && (
              <div style={{ marginTop: 14 }}>
                <a href={s.primary_source_url} target="_blank" rel="noopener noreferrer" style={{ ...linkStyleSD, fontSize: 13 }}>
                  → Primary source ({new URL(s.primary_source_url).hostname.replace(/^www\./, "")})
                </a>
              </div>
            )}
          </CardSD>
        </div>

        {/* Litigation + sealed */}
        <div style={gridRowSD(["7fr","5fr"])}>
          <CardSD>
            <EyebrowSD>LITIGATION & MATERIAL EVENTS · 24 MONTHS</EyebrowSD>
            {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={linkStyleSD}>/#/research</a>.
              </div>
            )}
          </CardSD>
          <CardSD>
            <EyebrowSD>FACILITY-SIDE INTEL · SEALED</EyebrowSD>
            <div style={{ marginTop: 14, fontSize: 14, lineHeight: 1.5, opacity: 0.78 }}>
              Per the two-tier disclosure rule, driver-derived facility intel
              stays sealed — we surface counts only, never names.
            </div>
            <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 10, fontSize: 13 }}>
              <SealedRowSD
                label="Verified intel rows (24mo)"
                value={(data.sealed_intel && data.sealed_intel.total_24mo) || 0}
              />
              <SealedRowSD
                label="Recent activity (90d)"
                value={(data.sealed_intel && data.sealed_intel.recent_90d) || 0}
              />
              <SealedRowSD
                label="Multi-source corroboration"
                value={(data.sealed_intel && data.sealed_intel.shipper_signals) || 0}
              />
            </div>
            <div style={{ fontSize: 11, opacity: 0.5, marginTop: 14, textTransform: "uppercase", letterSpacing: "0.08em" }}>
              Live joins · intel_submissions + shipper_signals
            </div>
          </CardSD>
        </div>

        {/* Sources */}
        <div style={gridRowSD(["12fr"])}>
          <CardSD>
            <EyebrowSD>SOURCES</EyebrowSD>
            <div style={{ marginTop: 12, display: "flex", flexWrap: "wrap", gap: 10 }}>
              {s.sec_cik && <SourceLinkSD href={`https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=${s.sec_cik}&type=&dateb=&owner=include&count=40`} label="SEC EDGAR · filings" />}
              {s.sec_cik && <SourceLinkSD href={`https://efts.sec.gov/LATEST/search-index?q=%22${encodeURIComponent(s.name)}%22&forms=10-K`} label="EDGAR · 10-K full-text" />}
              {s.primary_source_url && <SourceLinkSD href={s.primary_source_url} label="Editorial source" />}
              <SourceLinkSD href={`https://echo.epa.gov/facilities/facility-search/results?p_fn=${encodeURIComponent(s.name)}`} label="EPA ECHO · facility compliance" />
              <SourceLinkSD href={`https://www.osha.gov/ords/pls/odi/sir_results?p_company_name=${encodeURIComponent(s.name)}`} label="OSHA · injury reports" />
              <SourceLinkSD href={`https://www.courtlistener.com/?q=${encodeURIComponent(s.name)}&type=r`} label="CourtListener · litigation" />
            </div>
          </CardSD>
        </div>

        {/* CTA */}
        <div style={gridRowSD(["12fr"])}>
          <CardSD 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 }}>Shipper Risk Report on {s.name}</h3>
                <div style={{ fontSize: 13, opacity: 0.78, maxWidth: 600 }}>
                  Full 10-K freight-spend disclosure walk · OSHA + EPA facility flags ·
                  primary-carrier vendor map · DC closure / WARN notice exposure ·
                  detention pattern · 5-year freight-spend trajectory.
                </div>
              </div>
              <a href={`#/risk-report?shipper=${encodeURIComponent(s.slug)}`} style={btnPrimarySD}>
                Order $499 deep-dive →
              </a>
            </div>
          </CardSD>
        </div>

        <div style={legalFooterSD}>
          <strong>Disclaimer.</strong> Identity, regulatory, and corporate facts are sourced from
          public records (SEC EDGAR filings, EPA ECHO, OSHA, court dockets, news cited inline).
          Annual revenue, freight spend, DC count, and store count for non-public companies are
          industry estimates. The hex-map state distribution is <strong>illustrative</strong>
          until live source data 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. Not investment
          advice, not legal advice, not a credit report. Corrections:
          corrections@shippingclarity.com.
        </div>

      </div>
    </div>
  );
}

const legalFooterSD = {
  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 pageStyleSD = {
  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 cardBgSD = "rgba(255,255,255,0.04)";
const cardBorderSD = "1px solid rgba(255,255,255,0.10)";
function CardSD({ children, style }) { return <div style={{ background: cardBgSD, border: cardBorderSD, borderRadius: 12, padding: 20, ...style }}>{children}</div>; }
function EyebrowSD({ children }) { return <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.16em", color: "#5fa9ff", fontWeight: 600 }}>{children}</div>; }
function AttrSD({ 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 StatCardSD({ label, value, sub }) { return <CardSD><EyebrowSD>{label}</EyebrowSD><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>}</CardSD>; }
function ProvisionalBadgeSD() { return <span style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.08em", padding: "3px 8px", border: "1px solid rgba(255,184,77,0.6)", borderRadius: 3, color: "#ffb84d", whiteSpace: "nowrap" }}>Illustrative · live source pending</span>; }
function SealedRowSD({ 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 SourceLinkSD({ 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 linkStyleSD = { color: "#5fa9ff", textDecoration: "none" };
const btnGhostSD = { 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 btnPrimarySD = { display: "inline-block", padding: "12px 24px", background: "#5fa9ff", color: "#0a1224", borderRadius: 8, fontWeight: 700, textDecoration: "none", fontSize: 15, whiteSpace: "nowrap" };
function gridRowSD(cols) { return { display: "grid", gridTemplateColumns: cols.join(" "), gap: 16, marginBottom: 16 }; }

window.ShipperDetailPage = ShipperDetailPage;
