// =============================================================
// page-reefer.jsx — Reefer / Cold-Chain Intel
//
// Data: USDA AMS SC National Truck Rate Report (slug 2375)
// Views: produce_currently_shipping, produce_calendar_seasons,
//        usda_reefer_lanes
// Presentation: district cards + heatmap calendar + rate explorer
// =============================================================

(function () {
  const { useState, useEffect, useMemo } = React;

  const SB_URL = "https://fspqxobtsgyzzcdvpqul.supabase.co";
  const SB_KEY = "sb_publishable_0zNSihwdiVEKHD_HQj7Oqw_wEGGPFf6";
  const SB_H   = { apikey: SB_KEY, Authorization: `Bearer ${SB_KEY}` };

  const MONTHS = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

  // Inject CSS animations once
  (function injectReeferStyles() {
    if (document.getElementById("reefer-anim-css")) return;
    const s = document.createElement("style");
    s.id = "reefer-anim-css";
    s.textContent = `
      @keyframes reeferPulse {
        0%,100% { opacity:1; transform:scale(1); }
        50%      { opacity:0.45; transform:scale(1.55); }
      }
      @keyframes reeferBarFill {
        from { width: 0% !important; }
      }
      @keyframes reeferFadeUp {
        from { opacity:0; transform:translateY(8px); }
        to   { opacity:1; transform:translateY(0); }
      }
      .reefer-pulse { animation: reeferPulse 1.6s ease-in-out infinite; }
      .reefer-bar   { animation: reeferBarFill 0.7s cubic-bezier(0.22,1,0.36,1) both; }
      .reefer-card  { animation: reeferFadeUp 0.4s ease both; }
      .reefer-cal-row:hover td { background: rgba(22,163,74,0.04) !important; }
      .reefer-cal-row:hover td:first-child { background: rgba(22,163,74,0.06) !important; }
      @keyframes flowOut { to { stroke-dashoffset: -18; } }
      @keyframes flowIn  { to { stroke-dashoffset:  18; } }
    `;
    document.head.appendChild(s);
  })();

  // Map long USDA district names → short display labels
  const DISTRICT_LABELS = [
    ["CENTRAL AND SOUTH FLORIDA",                 "S. Florida"],
    ["SOUTH AND CENTRAL DISTRICT CALIFORNIA",     "Central CA"],
    ["YAKIMA VALLEY AND WENATCHEE",               "Yakima WA"],
    ["IMPERIAL, COACHELLA",                       "Imperial Valley"],
    ["MEXICO CROSSINGS THROUGH NOGALES",          "Nogales AZ"],
    ["MEXICO CROSSINGS THROUGH SOUTH TEXAS",      "S. Texas"],
    ["MEXICO CROSSINGS",                          "Mexico Crossing"],
    ["OXNARD DISTRICT",                           "Oxnard CA"],
    ["KERN DISTRICT",                             "Kern CA"],
    ["VIDALIA DISTRICT",                          "Vidalia GA"],
    ["LOWER RIO GRANDE",                          "Rio Grande TX"],
    ["NEW YORK",                                  "New York"],
    ["MICHIGAN",                                  "Michigan"],
    ["NORTH CAROLINA",                            "N. Carolina"],
    ["WISCONSIN",                                 "Wisconsin"],
    ["IDAHO",                                     "Idaho/E. Oregon"],
  ];

  // Geographic coords for each USDA district (for map pins)
  const DISTRICT_COORDS = [
    ["CENTRAL AND SOUTH FLORIDA",              [25.8, -80.3]],
    ["SOUTH AND CENTRAL DISTRICT CALIFORNIA",  [36.8, -120.5]],
    ["YAKIMA VALLEY AND WENATCHEE",            [46.6, -120.5]],
    ["IMPERIAL, COACHELLA",                    [33.1, -115.5]],
    ["MEXICO CROSSINGS THROUGH NOGALES",       [31.3, -110.9]],
    ["MEXICO CROSSINGS THROUGH SOUTH TEXAS",   [26.2,  -98.3]],
    ["MEXICO CROSSINGS",                       [31.3, -110.9]],
    ["OXNARD DISTRICT",                        [34.2, -119.2]],
    ["KERN DISTRICT",                          [35.4, -119.0]],
    ["VIDALIA DISTRICT",                       [32.2,  -82.4]],
    ["LOWER RIO GRANDE",                       [26.2,  -97.7]],
    ["NEW YORK",                               [40.7,  -73.9]],
    ["MICHIGAN",                               [44.3,  -85.5]],
    ["NORTH CAROLINA",                         [35.8,  -78.6]],
    ["WISCONSIN",                              [44.5,  -89.5]],
    ["IDAHO",                                  [43.6, -116.2]],
  ];

  function findCoords(market) {
    const up = (market || "").toUpperCase();
    for (const [k, v] of DISTRICT_COORDS) {
      if (up.includes(k)) return v;
    }
    return null;
  }

  // ── Produce Origins Map ──────────────────────────────────────
  function ProduceOriginMap({ activeNow }) {
    const { useRef: useRefMap, useMemo: useMemoMap } = React;
    const mapRef        = useRefMap(null);
    const elRef         = useRefMap(null);
    const layerRef      = useRefMap(null);
    const insetMapRef   = useRefMap(null);
    const insetElRef    = useRefMap(null);
    const insetLayerRef = useRefMap(null);

    // Summary counts for the stat strip below the map
    const summary = useMemoMap(() => {
      const districts = new Set();
      let adequate = 0, slight = 0, shortage = 0, surplus = 0;
      for (const row of activeNow) {
        districts.add(row.origin_market);
        const a = (row.availability || "").toLowerCase();
        if (a.includes("shortage") && a.includes("slight")) slight++;
        else if (a.includes("shortage")) shortage++;
        else if (a.includes("surplus")) surplus++;
        else adequate++;
      }
      return { districts: districts.size, commodities: activeNow.length, adequate, slight, shortage, surplus };
    }, [activeNow]);

    useEffect(() => {
      if (!elRef.current || !window.L || mapRef.current) return;
      const map = window.L.map(elRef.current, {
        zoomControl: false, scrollWheelZoom: false,
        attributionControl: false,
        dragging: false, touchZoom: false,
        doubleClickZoom: false, boxZoom: false, keyboard: false,
      }).setView([38.5, -96], 4);
      window.L.tileLayer(
        "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png",
        { subdomains: "abcd", maxZoom: 12 }
      ).addTo(map);
      mapRef.current = map;
      setTimeout(() => map.invalidateSize(), 60);
      return () => { try { map.remove(); } catch {} mapRef.current = null; };
    }, []);

    // Inset map — California detail (uses Pacific Ocean whitespace)
    useEffect(() => {
      if (!insetElRef.current || !window.L || insetMapRef.current) return;
      const map = window.L.map(insetElRef.current, {
        zoomControl: false, scrollWheelZoom: false,
        attributionControl: false,
        dragging: false, touchZoom: false,
        doubleClickZoom: false, boxZoom: false, keyboard: false,
      }).setView([35.2, -120.5], 6);
      window.L.tileLayer(
        "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png",
        { subdomains: "abcd", maxZoom: 14 }
      ).addTo(map);
      insetMapRef.current = map;
      setTimeout(() => map.invalidateSize(), 80);
      return () => { try { map.remove(); } catch {} insetMapRef.current = null; };
    }, []);

    useEffect(() => {
      const map = mapRef.current;
      if (!map || !window.L) return;
      if (layerRef.current) { try { map.removeLayer(layerRef.current); } catch {} }

      const byDistrict = {};
      for (const row of activeNow) {
        const k = row.origin_market;
        if (!byDistrict[k]) byDistrict[k] = { items: [], avail: row.availability };
        byDistrict[k].items.push(row);
      }

      const markers = [];
      for (const [origin, data] of Object.entries(byDistrict)) {
        const coords = findCoords(origin);
        if (!coords) continue;
        const st = availStyle(data.avail);
        const n  = data.items.length;
        const sz = Math.min(10 + n * 2, 30);
        const isShortage = data.avail && data.avail.toLowerCase().includes("shortage");
        // Marker: solid fill + white border + shadow (same pattern as other site maps)
        const html = `<span style="display:block;width:${sz}px;height:${sz}px;border-radius:50%;background:${st.dot};border:2px solid rgba(255,255,255,0.9);box-shadow:0 2px 8px rgba(0,0,0,0.35),0 0 0 3px ${st.dot}33;${isShortage ? "animation:reeferPulse 1.6s ease-in-out infinite;" : ""}"></span>`;
        const icon = window.L.divIcon({
          className: "", html,
          iconSize: [sz + 6, sz + 6],
          iconAnchor: [(sz + 6) / 2, (sz + 6) / 2],
        });
        const m = window.L.marker(coords, { icon });
        m.bindPopup(
          `<b style="font-size:13px;font-family:inherit">${shortDistrict(origin)}</b><br>` +
          `<span style="color:${st.dot};font-weight:600;font-size:12px">${st.label}</span><br>` +
          `<span style="opacity:0.6;font-size:12px">${n} commodit${n === 1 ? "y" : "ies"} shipping</span>`
        );
        markers.push(m);
      }
      const layer = window.L.layerGroup(markers);
      layer.addTo(map);
      layerRef.current = layer;
    }, [activeNow]);

    // Sync inset markers whenever activeNow changes
    useEffect(() => {
      const map = insetMapRef.current;
      if (!map || !window.L) return;
      if (insetLayerRef.current) { try { map.removeLayer(insetLayerRef.current); } catch {} }

      const byDistrict = {};
      for (const row of activeNow) {
        const k = row.origin_market;
        if (!byDistrict[k]) byDistrict[k] = { items: [], avail: row.availability };
        byDistrict[k].items.push(row);
      }
      const insetMarkers = [];
      for (const [origin, data] of Object.entries(byDistrict)) {
        const coords = findCoords(origin);
        if (!coords) continue;
        const st = availStyle(data.avail);
        const n  = data.items.length;
        const sz = Math.min(12 + n * 2, 28);
        const isShortage = data.avail && data.avail.toLowerCase().includes("shortage");
        const html = `<span style="display:block;width:${sz}px;height:${sz}px;border-radius:50%;background:${st.dot};border:2px solid rgba(255,255,255,0.95);box-shadow:0 2px 8px rgba(0,0,0,0.35),0 0 0 3px ${st.dot}33;${isShortage ? "animation:reeferPulse 1.6s ease-in-out infinite;" : ""}"></span>`;
        const icon = window.L.divIcon({ className: "", html, iconSize: [sz + 6, sz + 6], iconAnchor: [(sz + 6) / 2, (sz + 6) / 2] });
        const m = window.L.marker(coords, { icon });
        m.bindPopup(
          `<b style="font-size:13px;font-family:inherit">${shortDistrict(origin)}</b><br>` +
          `<span style="color:${st.dot};font-weight:600;font-size:12px">${st.label}</span><br>` +
          `<span style="opacity:0.6;font-size:12px">${n} commodit${n === 1 ? "y" : "ies"}</span>`
        );
        insetMarkers.push(m);
      }
      const insetLayer = window.L.layerGroup(insetMarkers);
      insetLayer.addTo(map);
      insetLayerRef.current = insetLayer;
    }, [activeNow]);

    if (!activeNow.length) return null;

    return (
      <div style={{ marginBottom: 40 }}>
        <div style={{ fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", opacity: 0.45, marginBottom: 6 }}>
          Live shipping origins
        </div>
        <h2 style={{ fontSize: 20, fontWeight: 700, margin: "0 0 12px", letterSpacing: "-0.01em" }}>
          Where produce is shipping from right now
        </h2>

        {/* Map — same container style as other site maps */}
        <div style={{ borderRadius: 10, overflow: "hidden", border: "1px solid #e0e0e0", boxShadow: "0 2px 16px rgba(0,0,0,0.07)", position: "relative" }}>
          <div ref={elRef} style={{ height: 300, background: "#f5f5f0" }} />

          {/* California detail inset — top-right corner over Atlantic whitespace
              (was bottom-left, but it covered the CA/SW pins it was supposed to magnify) */}
          <div style={{
            position: "absolute", top: 10, right: 10,
            width: 158, height: 145,
            borderRadius: 8, overflow: "hidden",
            border: "2.5px solid #fff",
            boxShadow: "0 3px 14px rgba(0,0,0,0.22)",
            zIndex: 500,
          }}>
            <div ref={insetElRef} style={{ height: "100%" }} />
            {/* Inset label */}
            <div style={{
              position: "absolute", top: 5, left: 5,
              background: "rgba(255,255,255,0.93)",
              borderRadius: 4, padding: "2px 7px",
              fontSize: 10, fontWeight: 700, letterSpacing: "0.05em",
              color: "#333", textTransform: "uppercase",
              boxShadow: "0 1px 4px rgba(0,0,0,0.10)",
            }}>
              California Detail
            </div>
          </div>
        </div>

        {/* Summary stat strip — like HubStatusMap */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(100px, 1fr))", gap: 1, marginTop: 1, borderRadius: "0 0 10px 10px", overflow: "hidden", border: "1px solid #e0e0e0", borderTop: "none" }}>
          {[
            { n: summary.districts,  label: "Districts",     color: "#16a34a", bg: "#f0fdf4" },
            { n: summary.commodities, label: "Commodities",  color: "#16a34a", bg: "#f0fdf4" },
            { n: summary.adequate,   label: "Adequate",      color: "#15803d", bg: "#dcfce7" },
            { n: summary.slight,     label: "Slight shortage", color: "#ca8a04", bg: "#fef9c3" },
            { n: summary.shortage,   label: "Shortage",      color: "#dc2626", bg: "#fee2e2" },
            { n: summary.surplus,    label: "Surplus trucks", color: "#1d4ed8", bg: "#dbeafe" },
          ].map(({ n, label, color, bg }) => (
            <div key={label} style={{ background: bg, padding: "10px 14px", textAlign: "center" }}>
              <div style={{ fontSize: 20, fontWeight: 700, color, lineHeight: 1.1 }}>{n}</div>
              <div style={{ fontSize: 11, opacity: 0.6, marginTop: 2, whiteSpace: "nowrap" }}>{label}</div>
            </div>
          ))}
        </div>

        {/* Legend row */}
        <div style={{ display: "flex", flexWrap: "wrap", gap: 16, marginTop: 10, opacity: 0.55, fontSize: 12 }}>
          {[
            ["#22c55e", "Adequate"], ["#f59e0b", "Slight shortage"],
            ["#ef4444", "Shortage"], ["#3b82f6", "Surplus"],
          ].map(([color, label]) => (
            <div key={label} style={{ display: "flex", alignItems: "center", gap: 5 }}>
              <span style={{ width: 9, height: 9, borderRadius: "50%", background: color, display: "inline-block", border: "1.5px solid rgba(255,255,255,0.9)", boxShadow: "0 1px 3px rgba(0,0,0,0.25)" }} />
              {label}
            </div>
          ))}
          <span style={{ opacity: 0.6, marginLeft: "auto", fontSize: 11 }}>Click a pin for details · Pin size = commodity count</span>
        </div>
      </div>
    );
  }

  function shortDistrict(market) {
    if (!market) return "";
    const up = market.toUpperCase();
    for (const [k, v] of DISTRICT_LABELS) {
      if (up.includes(k)) return v;
    }
    return market.split(",")[0].replace(/\s*(district|valley|crossings)\s*/gi, "").trim();
  }

  function cap(s) {
    if (!s) return "";
    return s.replace(/\b\w/g, c => c.toUpperCase());
  }

  function fmtRate(low, high) {
    if (!low && !high) return null;
    const lo = low  ? `$${Number(low).toLocaleString()}`  : null;
    const hi = high ? `$${Number(high).toLocaleString()}` : null;
    if (lo && hi && lo !== hi) return `${lo} – ${hi}`;
    return lo || hi;
  }

  // Truck availability → color + short label
  function availStyle(avail) {
    const a = (avail || "").toLowerCase();
    if (a.includes("shortage") && a.includes("slight"))
      return { bg: "#fff7e6", border: "#f59e0b", dot: "#f59e0b", label: "Slight Shortage" };
    if (a.includes("shortage"))
      return { bg: "#fef2f2", border: "#ef4444", dot: "#ef4444", label: "Shortage" };
    if (a.includes("surplus"))
      return { bg: "#eff6ff", border: "#3b82f6", dot: "#3b82f6", label: "Surplus" };
    return { bg: "#f0fdf4", border: "#22c55e", dot: "#22c55e", label: "Adequate" };
  }

  // ── District Cards ──────────────────────────────────────────
  function DistrictCards({ activeNow }) {
    // Group by origin district
    const districts = useMemo(() => {
      const map = {};
      for (const row of activeNow) {
        const key = row.origin_market;
        if (!map[key]) map[key] = { origin: key, items: [] };
        map[key].items.push(row);
      }
      return Object.values(map).sort((a, b) => b.items.length - a.items.length);
    }, [activeNow]);

    if (!districts.length) return null;

    return (
      <div style={{ marginBottom: 40 }}>
        <div style={{
          fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase",
          opacity: 0.45, marginBottom: 6,
        }}>Active shipping districts</div>
        <h2 style={{ fontSize: 20, fontWeight: 700, margin: "0 0 16px", letterSpacing: "-0.01em" }}>
          What's moving this week
        </h2>
        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))",
          gap: 14,
        }}>
          {districts.map((d, di) => {
            // Dominant availability across commodities in this district
            const avails = d.items.map(i => i.availability).filter(Boolean);
            const dominant = avails.sort((a, b) =>
              avails.filter(x => x === b).length - avails.filter(x => x === a).length
            )[0];
            const st = availStyle(dominant);
            const rates = d.items.filter(i => i.avg_rate > 0);
            const lo = rates.length ? Math.min(...rates.map(i => i.avg_rate)) : null;
            const hi = rates.length ? Math.max(...rates.map(i => i.avg_rate)) : null;
            const topCommodities = d.items
              .sort((a, b) => b.avg_rate - a.avg_rate)
              .slice(0, 6)
              .map(i => cap(i.commodity));

            return (
              <div key={d.origin} className="reefer-card" style={{
                background: "#fff",
                border: `1px solid ${st.border}`,
                borderLeft: `4px solid ${st.border}`,
                borderRadius: 10,
                padding: "16px 18px",
                position: "relative",
                animationDelay: `${di * 60}ms`,
              }}>
                {/* District name */}
                <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 4, letterSpacing: "-0.01em" }}>
                  {shortDistrict(d.origin)}
                </div>

                {/* Availability badge */}
                <div style={{
                  display: "inline-flex", alignItems: "center", gap: 5,
                  background: st.bg, borderRadius: 20, padding: "2px 9px",
                  fontSize: 11, fontWeight: 600, letterSpacing: "0.08em",
                  textTransform: "uppercase", color: st.dot, marginBottom: 12,
                }}>
                  <span
                    className={st.label === "Shortage" ? "reefer-pulse" : ""}
                    style={{ width: 6, height: 6, borderRadius: "50%", background: st.dot, display: "inline-block" }}
                  />
                  {st.label}
                </div>

                {/* Rate range */}
                {lo && hi && (
                  <div style={{ marginBottom: 12 }}>
                    <div style={{ fontSize: 11, opacity: 0.45, textTransform: "uppercase", letterSpacing: "0.12em", marginBottom: 4 }}>
                      Rate range / load
                    </div>
                    <div style={{ position: "relative", height: 8, background: "#f0f0f0", borderRadius: 4, overflow: "hidden" }}>
                      <div style={{
                        position: "absolute", left: 0, top: 0, bottom: 0,
                        width: "100%",
                        background: `linear-gradient(90deg, ${st.border}55, ${st.border})`,
                        borderRadius: 4,
                      }} />
                    </div>
                    <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginTop: 3, fontWeight: 600 }}>
                      <span style={{ opacity: 0.6 }}>${Number(lo).toLocaleString()}</span>
                      <span>${Number(hi).toLocaleString()}</span>
                    </div>
                  </div>
                )}

                {/* Commodities */}
                <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
                  {topCommodities.map(c => (
                    <span key={c} style={{
                      fontSize: 12, padding: "2px 8px", borderRadius: 3,
                      background: "#f5f5f5", color: "#444",
                    }}>
                      {c}
                    </span>
                  ))}
                  {d.items.length > 6 && (
                    <span style={{ fontSize: 12, padding: "2px 8px", opacity: 0.4 }}>
                      +{d.items.length - 6} more
                    </span>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  // ── Rate gate overlay ────────────────────────────────────────
  function RateGate({ onNav }) {
    return (
      <div style={{
        position: "absolute", inset: 0, zIndex: 10,
        display: "flex", alignItems: "center", justifyContent: "center",
        background: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.72) 28%, rgba(255,255,255,0.97) 55%)",
        borderRadius: 8,
      }}>
        <div style={{
          marginTop: 80,
          background: "#fff",
          border: "1px solid #e5e5e5",
          borderRadius: 12,
          padding: "28px 32px",
          textAlign: "center",
          boxShadow: "0 8px 32px rgba(0,0,0,0.10)",
          maxWidth: 340,
        }}>
          <div style={{ fontSize: 28, marginBottom: 10 }}>📦</div>
          <div style={{ fontWeight: 700, fontSize: 17, marginBottom: 6, letterSpacing: "-0.01em" }}>
            Lane rates are free — just sign in
          </div>
          <div style={{ fontSize: 13, opacity: 0.55, marginBottom: 20, lineHeight: 1.5 }}>
            Magic link email, no password. One click and you're in — same account works across all pages.
          </div>
          <button
            onClick={() => onNav("signin")}
            style={{
              width: "100%", padding: "11px 20px",
              background: "#16a34a", color: "#fff",
              border: "none", borderRadius: 7, cursor: "pointer",
              fontWeight: 700, fontSize: 14, letterSpacing: "0.01em",
            }}
          >
            Sign in to see rates →
          </button>
          <div style={{ marginTop: 12, fontSize: 12, opacity: 0.4 }}>
            Already have an account? Same button.
          </div>
        </div>
      </div>
    );
  }

  // ── Blurred teaser rows (shown when not signed in) ───────────
  function TeaserRows() {
    const widths = [
      [55, 35, 70], [40, 55, 55], [65, 30, 80], [45, 60, 45],
    ];
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 2, filter: "blur(5px)", userSelect: "none", pointerEvents: "none" }}>
        {widths.map(([c1, c2, bar], i) => (
          <div key={i} style={{
            display: "grid", gridTemplateColumns: "180px 160px 1fr 120px",
            gap: 12, alignItems: "center", padding: "10px 14px",
            background: i % 2 === 0 ? "#fafafa" : "#fff", borderRadius: 6,
          }}>
            <div style={{ height: 14, borderRadius: 4, background: "#ddd", width: `${c1}%` }} />
            <div style={{ height: 12, borderRadius: 4, background: "#e8e8e8", width: `${c2}%` }} />
            <div style={{ height: 14, borderRadius: 7, background: `linear-gradient(90deg, #86efac, #16a34a)`, width: `${bar}%`, opacity: 0.6 }} />
            <div style={{ height: 12, borderRadius: 4, background: "#e8e8e8", width: "60%", marginLeft: "auto" }} />
          </div>
        ))}
      </div>
    );
  }

  // ── Rate Explorer ────────────────────────────────────────────
  function RateExplorer({ lanes, onNav }) {
    const [selOrigin, setSelOrigin] = useState("all");
    const [selDest,   setSelDest]   = useState("all");
    const signedIn = !!(window.SI_DB && window.SI_DB.auth && window.SI_DB.auth.readSession());

    const origins = useMemo(() => {
      const s = new Set(lanes.map(l => l.origin_market));
      return Array.from(s).sort();
    }, [lanes]);

    const dests = useMemo(() => {
      const src = selOrigin === "all" ? lanes : lanes.filter(l => l.origin_market === selOrigin);
      const s = new Set(src.map(l => l.destination));
      return Array.from(s).sort();
    }, [lanes, selOrigin]);

    const filtered = useMemo(() => {
      return lanes
        .filter(l => selOrigin === "all" || l.origin_market === selOrigin)
        .filter(l => selDest   === "all" || l.destination === selDest)
        .sort((a, b) => b.avg_rate - a.avg_rate)
        .slice(0, 60);
    }, [lanes, selOrigin, selDest]);

    const maxRate = useMemo(() => Math.max(...filtered.map(l => l.rate_high || l.avg_rate || 0)), [filtered]);

    if (!lanes.length) return null;

    return (
      <div style={{ marginBottom: 48 }}>
        <div style={{ fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", opacity: 0.45, marginBottom: 6 }}>
          Lane rates
        </div>
        <h2 style={{ fontSize: 20, fontWeight: 700, margin: "0 0 4px", letterSpacing: "-0.01em" }}>
          Rate Explorer
        </h2>
        <p style={{ fontSize: 13, opacity: 0.55, margin: "0 0 18px" }}>
          USDA reported rates, current 14-day window. Filter by origin or destination.
        </p>

        {/* Filters */}
        <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: 20 }}>
          <select
            value={selOrigin}
            onChange={e => { setSelOrigin(e.target.value); setSelDest("all"); }}
            style={{
              fontFamily: "inherit", fontSize: 13, padding: "8px 12px",
              border: "1px solid #d0d0d0", borderRadius: 6, background: "#fff",
              color: "inherit", minWidth: 200,
            }}
          >
            <option value="all">All origins</option>
            {origins.map(o => <option key={o} value={o}>{shortDistrict(o)}</option>)}
          </select>
          <select
            value={selDest}
            onChange={e => setSelDest(e.target.value)}
            style={{
              fontFamily: "inherit", fontSize: 13, padding: "8px 12px",
              border: "1px solid #d0d0d0", borderRadius: 6, background: "#fff",
              color: "inherit", minWidth: 160,
            }}
          >
            <option value="all">All destinations</option>
            {dests.map(d => <option key={d} value={d}>{d}</option>)}
          </select>
        </div>

        {/* Rate cards — gated when not signed in */}
        <div style={{ position: "relative" }}>
          {signedIn ? (
            <>
              <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                {filtered.map((lane, i) => {
                  const st = availStyle(lane.availability);
                  const barPct = maxRate > 0 ? ((lane.rate_high || lane.avg_rate) / maxRate) * 100 : 0;
                  const loBarPct = maxRate > 0 ? ((lane.rate_low || lane.avg_rate) / maxRate) * 100 : 0;
                  return (
                    <div key={i} style={{
                      display: "grid",
                      gridTemplateColumns: "180px 160px 1fr 120px",
                      gap: 12, alignItems: "center",
                      padding: "10px 14px",
                      background: i % 2 === 0 ? "#fafafa" : "#fff",
                      borderRadius: 6, fontSize: 13,
                    }}>
                      <div style={{ fontWeight: 600 }}>{cap(lane.commodity)}</div>
                      <div style={{ fontSize: 12, opacity: 0.6, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                        {shortDistrict(lane.origin_market)} → {lane.destination}
                      </div>
                      <div style={{ position: "relative", height: 14, background: "#eee", borderRadius: 7 }}>
                        <div className="reefer-bar" style={{
                          position: "absolute", left: 0, top: 0, bottom: 0,
                          width: `${loBarPct}%`, background: "#d0d0d0", borderRadius: 7,
                          animationDelay: `${i * 30}ms`,
                        }} />
                        <div className="reefer-bar" style={{
                          position: "absolute", left: 0, top: 0, bottom: 0,
                          width: `${barPct}%`,
                          background: `linear-gradient(90deg, ${st.dot}88, ${st.dot})`,
                          borderRadius: 7,
                          animationDelay: `${i * 30 + 80}ms`,
                        }} />
                        <div style={{
                          position: "absolute", right: 8, top: 0, bottom: 0,
                          display: "flex", alignItems: "center",
                          fontSize: 11, fontWeight: 700, color: "#333",
                          whiteSpace: "nowrap",
                        }}>
                          {fmtRate(lane.rate_low, lane.rate_high)}
                        </div>
                      </div>
                      <div style={{
                        display: "inline-flex", alignItems: "center", gap: 4, justifyContent: "flex-end",
                        fontSize: 11, color: st.dot, fontWeight: 600,
                      }}>
                        <span style={{ width: 6, height: 6, borderRadius: "50%", background: st.dot, display: "inline-block" }} />
                        {st.label}
                      </div>
                    </div>
                  );
                })}
              </div>
              {filtered.length === 0 && (
                <div style={{ padding: "32px 0", textAlign: "center", opacity: 0.4, fontSize: 14 }}>
                  No lanes match this filter.
                </div>
              )}
            </>
          ) : (
            <>
              <TeaserRows />
              <RateGate onNav={onNav} />
            </>
          )}
        </div>
        <div style={{ marginTop: 10, fontSize: 12, opacity: 0.4, textAlign: "right" }}>
          USDA AMS Market News · SC National Truck Rate Report · Updated weekly
        </div>
      </div>
    );
  }

  // ── Lane Flow Map ─────────────────────────────────────────────
  const DEST_COORDS = {
    "Atlanta":      [33.75, -84.39],
    "Baltimore":    [39.29, -76.61],
    "Boston":       [42.36, -71.06],
    "Chicago":      [41.85, -87.65],
    "Dallas":       [32.78, -96.80],
    "Los Angeles":  [34.05, -118.24],
    "Miami":        [25.77, -80.19],
    "New York":     [40.71, -74.01],
    "Philadelphia": [39.95, -75.17],
    "Seattle":      [47.61, -122.33],
  };

  // All origin markets that appear in usda_reefer_lanes (exact DB strings)
  const LANE_ORIGIN_COORDS = [
    ["SALINAS-WATSONVILLE",                           [36.70, -121.60]],
    ["SANTA MARIA",                                   [34.95, -120.44]],
    ["SAN LUIS VALLEY",                               [37.70, -105.50]],
    ["SOUTH AND CENTRAL DISTRICT CALIFORNIA",         [36.50, -120.50]],
    ["KERN DISTRICT",                                 [35.40, -119.00]],
    ["OXNARD DISTRICT",                               [34.20, -119.20]],
    ["CENTRAL AND SOUTH FLORIDA",                     [25.80,  -80.30]],
    ["IMPERIAL, COACHELLA",                           [33.10, -115.50]],
    ["MEXICO CROSSINGS THROUGH NOGALES",              [31.30, -110.90]],
    ["MEXICO CROSSINGS THROUGH SOUTH TEXAS",          [26.20,  -98.30]],
    ["YAKIMA VALLEY AND WENATCHEE",                   [46.60, -120.50]],
    ["VIDALIA DISTRICT",                              [32.20,  -82.40]],
    ["NEW YORK",                                      [40.70,  -73.90]],
  ];

  function findLaneOriginCoords(market) {
    const up = (market || "").toUpperCase();
    for (const [k, v] of LANE_ORIGIN_COORDS) {
      if (up.includes(k)) return v;
    }
    return null;
  }

  // ── Meat hauler lanes (DAT reefer data, May 2026) ────────────
  const MEAT_ORIGIN_COORDS = {
    "GARDEN CITY, KS": [37.97, -100.87],
    "DODGE CITY, KS":  [37.75, -100.02],
    "OMAHA, NE":       [41.26,  -95.94],
    "LEXINGTON, NE":   [40.78,  -99.74],
    "SIOUX FALLS, SD": [43.55,  -96.73],
  };

  const MEAT_LANES = [
    { origin:"GARDEN CITY, KS", dest:"Los Angeles", miles:1238, avg_rate:2410, rate_low:1687, rate_high:2976, rpm:1.95 },
    { origin:"GARDEN CITY, KS", dest:"Seattle",     miles:1618, avg_rate:3356, rate_low:2349, rate_high:3859, rpm:2.07 },
    { origin:"GARDEN CITY, KS", dest:"Chicago",     miles: 900, avg_rate:2090, rate_low:1635, rate_high:2635, rpm:2.32 },
    { origin:"DODGE CITY, KS",  dest:"Chicago",     miles: 843, avg_rate:2059, rate_low:1619, rate_high:2536, rpm:2.44 },
    { origin:"DODGE CITY, KS",  dest:"Dallas",      miles: 461, avg_rate:1541, rate_low:1327, rate_high:1580, rpm:3.34 },
    { origin:"OMAHA, NE",       dest:"Boston",      miles:1452, avg_rate:3285, rate_low:2300, rate_high:3828, rpm:2.26 },
    { origin:"OMAHA, NE",       dest:"New York",    miles:1262, avg_rate:2988, rate_low:2092, rate_high:3648, rpm:2.37 },
    { origin:"OMAHA, NE",       dest:"Chicago",     miles: 472, avg_rate:1741, rate_low:1337, rate_high:1864, rpm:3.69 },
    { origin:"LEXINGTON, NE",   dest:"Chicago",     miles: 689, avg_rate:1822, rate_low:1553, rate_high:2369, rpm:2.65 },
    { origin:"LEXINGTON, NE",   dest:"Los Angeles", miles:1335, avg_rate:2698, rate_low:1888, rate_high:3413, rpm:2.02 },
    { origin:"LEXINGTON, NE",   dest:"Dallas",      miles: 712, avg_rate:1882, rate_low:1612, rate_high:2447, rpm:2.64 },
    { origin:"SIOUX FALLS, SD", dest:"Dallas",      miles: 840, avg_rate:2324, rate_low:1830, rate_high:2778, rpm:2.77 },
    { origin:"SIOUX FALLS, SD", dest:"Los Angeles", miles:1726, avg_rate:3034, rate_low:2308, rate_high:3771, rpm:1.76 },
    { origin:"SIOUX FALLS, SD", dest:"New York",    miles:1385, avg_rate:3894, rate_low:2726, rate_high:4478, rpm:2.81 },
    { origin:"SIOUX FALLS, SD", dest:"Chicago",     miles: 573, avg_rate:1734, rate_low:1580, rate_high:1953, rpm:3.03 },
  ].map(l => ({
    ...l,
    oCoords: MEAT_ORIGIN_COORDS[l.origin],
    dCoords: DEST_COORDS[l.dest],
    netPerMile: +(l.rpm - 2.10).toFixed(2),
  })).filter(l => l.oCoords && l.dCoords);

  function meatRpmColor(rpm) {
    if (!rpm) return "#9ca3af";
    if (rpm >= 3.00) return "#15803d";
    if (rpm >= 2.50) return "#22c55e";
    if (rpm >= 2.10) return "#f59e0b";
    return "#dc2626";
  }

  // Industry owner-op reefer breakeven (ATBS / OOIDA data)
  const NATIONAL_CPM = 2.10;

  function haversineMiles(c1, c2) {
    const R = 3959;
    const lat1 = c1[0] * Math.PI / 180, lat2 = c2[0] * Math.PI / 180;
    const dlat = lat2 - lat1, dlon = (c2[1] - c1[1]) * Math.PI / 180;
    const a = Math.sin(dlat/2)**2 + Math.cos(lat1)*Math.cos(lat2)*Math.sin(dlon/2)**2;
    return R * 2 * Math.asin(Math.sqrt(a));
  }

  function laneRateColor(rate) {
    if (!rate) return "#9ca3af";
    if (rate >= 9500) return "#dc2626";
    if (rate >= 8500) return "#f97316";
    if (rate >= 7500) return "#f59e0b";
    if (rate >= 6000) return "#22c55e";
    return "#3b82f6";
  }

  function LaneFlowMap({ lanes }) {
    const { useRef: useRefLF, useState: useStateLF, useMemo: useMemoLF } = React;
    const mapRef   = useRefLF(null);
    const elRef    = useRefLF(null);
    const layerRef = useRefLF(null);
    const [mode, setMode]           = useStateLF("outbound");
    const [commodity, setCommodity] = useStateLF("produce");

    // Aggregate: one entry per unique origin×destination (best rate + commodity list)
    const grouped = useMemoLF(() => {
      const map = {};
      for (const lane of lanes) {
        const dCoords = DEST_COORDS[lane.destination];
        const oCoords = findLaneOriginCoords(lane.origin_market);
        if (!dCoords || !oCoords) continue;
        const key = `${lane.origin_market}||${lane.destination}`;
        if (!map[key]) {
          map[key] = {
            origin: lane.origin_market, dest: lane.destination,
            oCoords, dCoords,
            avg_rate: lane.avg_rate || 0,
            rate_low: lane.rate_low, rate_high: lane.rate_high,
            commodities: [],
          };
        }
        if (lane.commodity) map[key].commodities.push(cap(lane.commodity));
        if ((lane.avg_rate || 0) > map[key].avg_rate) {
          map[key].avg_rate  = lane.avg_rate;
          map[key].rate_low  = lane.rate_low;
          map[key].rate_high = lane.rate_high;
        }
      }
      // Enrich with mileage + profitability
      return Object.values(map).map(lane => {
        const miles = Math.round(haversineMiles(lane.oCoords, lane.dCoords));
        const revPerMile = miles > 0 && lane.avg_rate > 0 ? lane.avg_rate / miles : null;
        const netPerMile = revPerMile !== null ? revPerMile - NATIONAL_CPM : null;
        return { ...lane, miles, revPerMile, netPerMile };
      });
    }, [lanes]);

    // Top 5 produce lanes by rate
    const topLanes = useMemoLF(() =>
      [...grouped].sort((a, b) => b.avg_rate - a.avg_rate).slice(0, 5),
    [grouped]);

    // Top 5 meat lanes by RPM
    const meatTop5 = useMemoLF(() =>
      [...MEAT_LANES].filter(l => l.oCoords && l.dCoords).sort((a, b) => b.rpm - a.rpm).slice(0, 5),
    []);

    useEffect(() => {
      if (!elRef.current || !window.L || mapRef.current) return;
      const map = window.L.map(elRef.current, {
        zoomControl: true, scrollWheelZoom: false,
        attributionControl: false,
        dragging: true, touchZoom: false,
        doubleClickZoom: false, boxZoom: false, keyboard: false,
      }).setView([38.5, -96], 4);
      window.L.tileLayer(
        "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png",
        { subdomains: "abcd", maxZoom: 12 }
      ).addTo(map);
      mapRef.current = map;
      setTimeout(() => map.invalidateSize(), 60);
      return () => { try { map.remove(); } catch {} mapRef.current = null; };
    }, []);

    useEffect(() => {
      const map = mapRef.current;
      if (!map || !window.L) return;
      if (commodity === "produce" && !grouped.length) return;
      if (layerRef.current) { try { map.removeLayer(layerRef.current); } catch {} }
      const lg = window.L.layerGroup();

      if (commodity === "meat") {
        const seenDest = new Set();
        for (const lane of MEAT_LANES) {
          if (!lane.oCoords || !lane.dCoords) continue;
          const color  = meatRpmColor(lane.rpm);
          const badge  = lane.netPerMile >= 0
            ? `<span style="background:#dcfce7;color:#15803d;border-radius:4px;padding:1px 6px;font-size:11px;font-weight:700">✓ +$${lane.netPerMile.toFixed(2)}/mi above breakeven</span>`
            : `<span style="background:#fee2e2;color:#dc2626;border-radius:4px;padding:1px 6px;font-size:11px;font-weight:700">⚠ $${Math.abs(lane.netPerMile).toFixed(2)}/mi below breakeven</span>`;
          const pl = window.L.polyline([lane.oCoords, lane.dCoords], { color, weight: 2.5, opacity: 0.78 });
          pl.on("add", function () {
            const el = this.getElement();
            if (!el) return;
            el.style.strokeDasharray = "12 6";
            el.style.animation = "flowOut 0.9s linear infinite";
          });
          pl.bindPopup(
            `<div style="font-family:inherit;min-width:210px">` +
            `<b style="font-size:13px">🥩 ${lane.origin} → ${lane.dest}</b><br>` +
            `<span style="color:${color};font-weight:700;font-size:15px">$${lane.avg_rate.toLocaleString()}</span>` +
            `<span style="opacity:0.5;font-size:11px;margin-left:6px">($${lane.rate_low.toLocaleString()}–$${lane.rate_high.toLocaleString()})</span><br>` +
            `<div style="font-size:11px;opacity:0.55;margin:3px 0">~${lane.miles.toLocaleString()} mi · <b>$${lane.rpm.toFixed(2)}/mi RPM</b> · Breakeven: $${NATIONAL_CPM.toFixed(2)}/mi</div>` +
            badge + `</div>`
          );
          pl.addTo(lg);

          // Origin marker (packing plant dot)
          const oHtml = `<span style="display:block;width:11px;height:11px;border-radius:50%;background:${color};border:2px solid rgba(255,255,255,0.9);box-shadow:0 2px 8px rgba(0,0,0,0.3)"></span>`;
          window.L.marker(lane.oCoords, {
            icon: window.L.divIcon({ className: "", html: oHtml, iconSize: [13,13], iconAnchor: [6,6] })
          }).bindTooltip(lane.origin, { permanent: false, direction: "top" }).addTo(lg);

          if (!seenDest.has(lane.dest)) {
            seenDest.add(lane.dest);
            window.L.circleMarker(lane.dCoords, {
              radius: 7, color: "#fff", fillColor: "#1e293b", fillOpacity: 0.85, weight: 2,
            }).bindTooltip(lane.dest, { permanent: false, direction: "top" }).addTo(lg);
          }
        }
      } else if (mode === "outbound") {
        const seenDest = new Set();
        const seenOrigin = new Set();
        for (const lane of grouped) {
          const { oCoords, dCoords, avg_rate, rate_low, rate_high, commodities, origin, dest } = lane;
          const color  = laneRateColor(avg_rate);
          const weight = 1.2 + Math.min(commodities.length / 5, 2.8);

          const pl = window.L.polyline([oCoords, dCoords], { color, weight, opacity: 0.72 });
          pl.on("add", function () {
            const el = this.getElement();
            if (!el) return;
            el.style.strokeDasharray = "12 6";
            el.style.animation = "flowOut 0.9s linear infinite";
          });
          const profBadge = lane.netPerMile !== null
            ? (lane.netPerMile >= 0
                ? `<span style="background:#dcfce7;color:#15803d;border-radius:4px;padding:1px 6px;font-size:11px;font-weight:700">✓ +$${lane.netPerMile.toFixed(2)}/mi above cost</span>`
                : `<span style="background:#fee2e2;color:#dc2626;border-radius:4px;padding:1px 6px;font-size:11px;font-weight:700">⚠ $${lane.netPerMile.toFixed(2)}/mi — tight</span>`)
            : "";
          const milesLine = lane.miles
            ? `<div style="font-size:11px;opacity:0.55;margin:3px 0">~${lane.miles.toLocaleString()} mi · ` +
              `Rev/mi: <b>$${(lane.revPerMile||0).toFixed(2)}</b> · Avg reefer cost: <b>$${NATIONAL_CPM.toFixed(2)}</b></div>`
            : "";
          pl.bindPopup(
            `<div style="font-family:inherit;min-width:200px">` +
            `<b style="font-size:13px">${shortDistrict(origin)} → ${dest}</b><br>` +
            `<span style="color:${color};font-weight:700;font-size:15px">` +
            `$${Number(rate_low||0).toLocaleString()} – $${Number(rate_high||0).toLocaleString()}</span><br>` +
            milesLine + profBadge +
            `<div style="margin-top:5px;opacity:0.6;font-size:11px">${commodities.slice(0,6).join(", ")}` +
            `${commodities.length > 6 ? ` +${commodities.length-6} more` : ""}</div></div>`
          );
          pl.addTo(lg);

          if (!seenDest.has(dest)) {
            seenDest.add(dest);
            window.L.circleMarker(dCoords, {
              radius: 7, color: "#fff", fillColor: "#1e293b", fillOpacity: 0.85, weight: 2,
            }).bindTooltip(dest, { permanent: false, direction: "top" }).addTo(lg);
          }
          if (!seenOrigin.has(origin)) {
            seenOrigin.add(origin);
            const sz = 10;
            const html = `<span style="display:block;width:${sz}px;height:${sz}px;border-radius:50%;background:${color};border:2px solid rgba(255,255,255,0.9);box-shadow:0 2px 8px rgba(0,0,0,0.3)"></span>`;
            window.L.marker(oCoords, {
              icon: window.L.divIcon({ className: "", html, iconSize: [14,14], iconAnchor: [7,7] })
            }).bindTooltip(shortDistrict(origin), { permanent: false, direction: "top" }).addTo(lg);
          }
        }
      } else {
        // Return mode — one line per destination city back to CA hub (not per-lane)
        const CA_HUB = [35.8, -119.5]; // Central CA produce hub
        const byDest = {};
        for (const lane of grouped) {
          if (!lane.dCoords) continue;
          if (!byDest[lane.dest]) byDest[lane.dest] = { dest: lane.dest, dCoords: lane.dCoords, rates: [] };
          if (lane.avg_rate > 0) byDest[lane.dest].rates.push(lane.avg_rate);
        }

        for (const data of Object.values(byDest)) {
          const avgOut = data.rates.length
            ? Math.round(data.rates.reduce((s, v) => s + v, 0) / data.rates.length) : 0;
          const backhaulLo = Math.round(avgOut * 0.35 / 100) * 100;
          const backhaulHi = Math.round(avgOut * 0.50 / 100) * 100;
          const miles = Math.round(haversineMiles(data.dCoords, CA_HUB));

          const pl = window.L.polyline([data.dCoords, CA_HUB], {
            color: "#6366f1", weight: 2.5, opacity: 0.6,
          });
          pl.on("add", function () {
            const el = this.getElement();
            if (!el) return;
            el.style.strokeDasharray = "4 10";
            el.style.animation = "flowIn 1.4s linear infinite";
          });
          pl.bindPopup(
            `<div style="font-family:inherit;min-width:190px">` +
            `<b style="font-size:13px">${data.dest} → California</b><br>` +
            `<div style="font-size:12px;opacity:0.55;margin:4px 0">~${miles.toLocaleString()} mi empty return</div>` +
            `<div style="font-size:14px;font-weight:700;color:#6366f1">Est. backhaul $${backhaulLo.toLocaleString()}–$${backhaulHi.toLocaleString()}</div>` +
            `<div style="font-size:11px;opacity:0.45;margin-top:3px">35–50% of avg outbound ($${avgOut.toLocaleString()})</div>` +
            `</div>`
          );
          pl.addTo(lg);

          window.L.circleMarker(data.dCoords, {
            radius: 7, color: "#fff", fillColor: "#6366f1", fillOpacity: 0.8, weight: 2,
          }).bindTooltip(data.dest, { permanent: false, direction: "top" }).addTo(lg);
        }

        // Single CA hub marker
        const hubHtml = `<span style="display:block;width:14px;height:14px;border-radius:50%;background:#16a34a;border:2.5px solid rgba(255,255,255,0.95);box-shadow:0 2px 10px rgba(22,163,74,0.5)"></span>`;
        window.L.marker(CA_HUB, {
          icon: window.L.divIcon({ className: "", html: hubHtml, iconSize: [18,18], iconAnchor: [9,9] })
        }).bindTooltip("California Produce Hub", { permanent: false, direction: "top" }).addTo(lg);
      }

      lg.addTo(map);
      layerRef.current = lg;
    }, [grouped, mode, commodity]);

    if (commodity === "produce" && !grouped.length) return null;

    return (
      <div style={{ marginBottom: 48 }}>
        <div style={{ fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", opacity: 0.45, marginBottom: 6 }}>
          Truck corridors
        </div>
        <h2 style={{ fontSize: 20, fontWeight: 700, margin: "0 0 4px", letterSpacing: "-0.01em" }}>
          {commodity === "meat" ? "Meat & protein hauler corridors — what the lanes pay" : "How produce gets to market — and what it pays"}
        </h2>
        <p style={{ fontSize: 13, opacity: 0.55, margin: "0 0 14px" }}>
          {commodity === "meat"
            ? "15 active reefer lanes from Midwest packing plants. DAT May 2026. Click any line for rate + RPM profitability."
            : "Live outbound reefer lanes from each shipping district. Click any line for rate + commodity detail."}
        </p>

        {/* Commodity toggle */}
        <div style={{ display: "flex", gap: 8, marginBottom: 10, flexWrap: "wrap" }}>
          {[
            { id: "produce", label: "🥬  Produce", color: "#16a34a" },
            { id: "meat",    label: "🥩  Meat & Protein", color: "#b45309" },
          ].map(({ id, label, color }) => (
            <button key={id} onClick={() => setCommodity(id)} style={{
              padding: "7px 16px", fontSize: 13, borderRadius: 7, cursor: "pointer",
              border: `1.5px solid ${commodity === id ? color : "#d0d0d0"}`,
              background: commodity === id ? color : "#fff",
              color: commodity === id ? "#fff" : "inherit",
              fontWeight: commodity === id ? 700 : 400,
              transition: "all 0.15s",
            }}>{label}</button>
          ))}
        </div>

        {/* Mode toggle — produce only */}
        {commodity === "produce" && (
          <div style={{ display: "flex", gap: 8, marginBottom: 14, flexWrap: "wrap" }}>
            {[
              { id: "outbound", label: "▶  Outbound — produce heading east", color: "#16a34a" },
              { id: "return",   label: "◀  Backhaul — empty trucks back to CA", color: "#6366f1" },
            ].map(({ id, label, color }) => (
              <button key={id} onClick={() => setMode(id)} style={{
                padding: "7px 16px", fontSize: 13, borderRadius: 7, cursor: "pointer",
                border: `1.5px solid ${mode === id ? color : "#d0d0d0"}`,
                background: mode === id ? color : "#fff",
                color: mode === id ? "#fff" : "inherit",
                fontWeight: mode === id ? 700 : 400,
                transition: "all 0.15s",
              }}>{label}</button>
            ))}
          </div>
        )}

        {/* Backhaul info banner — produce only */}
        {commodity === "produce" && mode === "return" && (
          <div style={{
            padding: "12px 16px", borderRadius: 8, marginBottom: 14,
            background: "#eef2ff", border: "1px solid #c7d2fe", fontSize: 13,
            display: "flex", gap: 10, alignItems: "flex-start",
          }}>
            <span style={{ fontSize: 20, lineHeight: 1 }}>🔄</span>
            <div>
              <b>Where the empty trucks go.</b> After dropping a produce load in a city, reefer trucks
              need to get back to California to pick up the next load. Each line shows one of those
              return corridors. Click any line to see the estimated backhaul rate.
            </div>
          </div>
        )}

        {/* Map */}
        <div style={{ borderRadius: 10, overflow: "hidden", border: "1px solid #e0e0e0", boxShadow: "0 2px 16px rgba(0,0,0,0.07)" }}>
          <div ref={elRef} style={{ height: 380, background: "#f5f5f0" }} />
        </div>

        {/* Legend + profitability benchmark */}
        {(commodity === "produce" ? mode === "outbound" : true) && (
          <div style={{ marginTop: 10 }}>
            <div style={{
              padding: "10px 14px", borderRadius: 8,
              background: "#fafaf7", border: "1px solid #e6e6df",
            }}>
              <div style={{
                fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase",
                fontWeight: 700, opacity: 0.55, marginBottom: 8,
              }}>
                Line color = {commodity === "meat" ? "rate per mile (RPM)" : "rate per truckload"}
              </div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 14, fontSize: 12, opacity: 0.78, alignItems: "center" }}>
                {commodity === "meat" ? (
                  <>
                    {[
                      ["#15803d", "≥ $3.00/mi (strong profit)"],
                      ["#22c55e", "$2.50–$3.00 (healthy)"],
                      ["#f59e0b", "$2.10–$2.50 (tight)"],
                      ["#dc2626", "< $2.10 (below breakeven)"],
                    ].map(([color, label]) => (
                      <div key={label} style={{ display: "flex", alignItems: "center", gap: 6 }}>
                        <span style={{ display: "inline-block", width: 26, height: 4, borderRadius: 2, background: color }} />
                        {label}
                      </div>
                    ))}
                    <span style={{ marginLeft: "auto", opacity: 0.55, fontSize: 11 }}>DAT May 2026 · Click lane for detail</span>
                  </>
                ) : (
                  <>
                    {[
                      ["#dc2626", "$9,500+ (premium)"],
                      ["#f97316", "$8,500–$9,500"],
                      ["#f59e0b", "$7,500–$8,500"],
                      ["#22c55e", "$6,000–$7,500"],
                      ["#3b82f6", "< $6,000 (short hop / soft)"],
                    ].map(([color, label]) => (
                      <div key={label} style={{ display: "flex", alignItems: "center", gap: 6 }}>
                        <span style={{ display: "inline-block", width: 26, height: 4, borderRadius: 2, background: color }} />
                        {label}
                      </div>
                    ))}
                    <span style={{ marginLeft: "auto", opacity: 0.55, fontSize: 11 }}>Line weight = commodity count · Click lane for detail</span>
                  </>
                )}
              </div>
            </div>
            {/* National avg cost reference bar */}
            <div style={{
              marginTop: 10, padding: "9px 14px", borderRadius: 7,
              background: "#f8fafc", border: "1px solid #e2e8f0",
              display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap", fontSize: 12,
            }}>
              <span style={{ fontWeight: 600, opacity: 0.6 }}>📊 Profitability benchmark</span>
              <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <span style={{ display: "inline-block", width: 14, height: 14, borderRadius: 3, background: "#dc2626", opacity: 0.25 }} />
                <span style={{ opacity: 0.65 }}>National avg reefer cost: <b>$2.10/mi</b> (ATBS/OOIDA owner-op)</span>
              </div>
              <div style={{ display: "flex", gap: 10 }}>
                <span style={{ background: "#dcfce7", color: "#15803d", borderRadius: 4, padding: "1px 8px", fontWeight: 700 }}>✓ above breakeven</span>
                <span style={{ background: "#fee2e2", color: "#dc2626", borderRadius: 4, padding: "1px 8px", fontWeight: 700 }}>⚠ tight / below</span>
              </div>
            </div>
          </div>
        )}

        {/* Top lanes strip */}
        {commodity === "meat" ? (
          meatTop5.length > 0 && (
            <div style={{ marginTop: 14 }}>
              <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.14em", opacity: 0.45, marginBottom: 8 }}>
                Top meat hauler lanes by RPM
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 8 }}>
                {meatTop5.map((lane, i) => {
                  const color = meatRpmColor(lane.rpm);
                  const profitable = lane.netPerMile >= 0;
                  return (
                    <div key={i} style={{
                      padding: "12px 14px", borderRadius: 8,
                      border: `1px solid ${color}44`,
                      borderLeft: `4px solid ${color}`,
                      background: "#fff",
                    }}>
                      <div style={{ fontSize: 12, opacity: 0.55, marginBottom: 2 }}>
                        🥩 {lane.origin.split(",")[0]} → {lane.dest}
                        <span style={{ opacity: 0.45, marginLeft: 4 }}>~{lane.miles.toLocaleString()} mi</span>
                      </div>
                      <div style={{ fontWeight: 700, fontSize: 18, color, marginBottom: 4 }}>
                        ${lane.avg_rate.toLocaleString()}
                        <span style={{ fontSize: 12, fontWeight: 400, marginLeft: 6, color: "#6b7280" }}>${lane.rpm.toFixed(2)}/mi RPM</span>
                      </div>
                      <div style={{
                        display: "inline-flex", alignItems: "center", gap: 4,
                        background: profitable ? "#dcfce7" : "#fee2e2",
                        color: profitable ? "#15803d" : "#dc2626",
                        borderRadius: 5, padding: "2px 8px",
                        fontSize: 11, fontWeight: 700,
                      }}>
                        {profitable
                          ? `✓ +$${lane.netPerMile.toFixed(2)}/mi profit`
                          : `⚠ $${Math.abs(lane.netPerMile).toFixed(2)}/mi below breakeven`}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )
        ) : (
          mode === "outbound" && topLanes.length > 0 && (
            <div style={{ marginTop: 14 }}>
              <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.14em", opacity: 0.45, marginBottom: 8 }}>
                Top paying lanes right now
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 8 }}>
                {topLanes.map((lane, i) => {
                  const color = laneRateColor(lane.avg_rate);
                  const profitable = lane.netPerMile !== null && lane.netPerMile >= 0;
                  return (
                    <div key={i} style={{
                      padding: "12px 14px", borderRadius: 8,
                      border: `1px solid ${color}44`,
                      borderLeft: `4px solid ${color}`,
                      background: "#fff",
                      position: "relative",
                    }}>
                      <div style={{ fontSize: 12, opacity: 0.55, marginBottom: 2 }}>
                        {shortDistrict(lane.origin)} → {lane.dest}
                        {lane.miles ? <span style={{ opacity: 0.45, marginLeft: 4 }}>~{lane.miles.toLocaleString()} mi</span> : null}
                      </div>
                      <div style={{ fontWeight: 700, fontSize: 18, color, marginBottom: 4 }}>
                        ${Number(lane.avg_rate).toLocaleString()}
                      </div>
                      {lane.netPerMile !== null && (
                        <div style={{
                          display: "inline-flex", alignItems: "center", gap: 4,
                          background: profitable ? "#dcfce7" : "#fee2e2",
                          color: profitable ? "#15803d" : "#dc2626",
                          borderRadius: 5, padding: "2px 8px",
                          fontSize: 11, fontWeight: 700, marginBottom: 4,
                        }}>
                          {profitable
                            ? `✓ +$${lane.netPerMile.toFixed(2)}/mi profit`
                            : `⚠ $${lane.netPerMile.toFixed(2)}/mi margin`}
                        </div>
                      )}
                      <div style={{ fontSize: 11, opacity: 0.4, marginTop: 2 }}>
                        {lane.commodities.slice(0,3).join(", ")}
                        {lane.commodities.length > 3 ? ` +${lane.commodities.length-3}` : ""}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )
        )}
      </div>
    );
  }

  // ── Calendar cell ─────────────────────────────────────────────
  const NOW_MONTH = new Date().getMonth() + 1; // 1-12

  function CellBlock({ cell, monthIdx }) {
    const isNow = (monthIdx + 1) === NOW_MONTH;
    const colBg = isNow ? "rgba(251,191,36,0.08)" : "transparent";

    if (!cell) {
      return (
        <td style={{ padding: "2px 2px", textAlign: "center", background: colBg }}>
          <div style={{
            width: 36, height: 26, borderRadius: 5, margin: "0 auto",
            background: isNow ? "rgba(251,191,36,0.18)" : "#efefef",
            border: isNow ? "1.5px solid rgba(251,191,36,0.35)" : "1px solid transparent",
          }} />
        </td>
      );
    }

    const wc   = cell.week_count || 0;
    const rate = cell.avg_rate;
    let bg, shadow, textColor;
    if (wc >= 4)      { bg = "#14532d"; shadow = "0 0 10px rgba(20,83,45,0.55)";  textColor = "rgba(255,255,255,0.92)"; }
    else if (wc >= 3) { bg = "#16a34a"; shadow = "0 0 8px rgba(22,163,74,0.45)"; textColor = "rgba(255,255,255,0.88)"; }
    else if (wc >= 2) { bg = "#4ade80"; shadow = "none";                           textColor = "#14532d"; }
    else              { bg = "#bbf7d0"; shadow = "none";                           textColor = "#166534"; }

    const rateLabel = wc >= 3 && rate ? `$${Math.round(rate / 1000)}k` : null;
    const tip = `${MONTHS[monthIdx]}: ${wc} week${wc === 1 ? "" : "s"} active${rate ? ` · ~$${Number(rate).toLocaleString()}/load avg` : ""}`;

    return (
      <td style={{ padding: "2px 2px", textAlign: "center", background: colBg }}>
        <div title={tip} style={{
          width: 36, height: 26, borderRadius: 5, margin: "0 auto",
          background: bg, boxShadow: shadow,
          border: isNow ? "1.5px solid rgba(251,191,36,0.6)" : "1px solid transparent",
          display: "flex", alignItems: "center", justifyContent: "center",
          fontSize: 9, fontWeight: 700, color: textColor,
          cursor: "default", letterSpacing: "0.01em",
        }}>
          {rateLabel}
        </div>
      </td>
    );
  }

  // ── Main page ─────────────────────────────────────────────────
  window.ReeferPage = function ReeferPage({ onNav }) {
    const [activeNow, setActiveNow] = useState([]);
    const [calData,   setCalData]   = useState([]);
    const [laneData,  setLaneData]  = useState([]);
    const [loading,   setLoading]   = useState(true);
    const [calOrigin, setCalOrigin] = useState("all");
    const [calSearch, setCalSearch] = useState("");

    useEffect(() => {
      Promise.all([
        fetch(`${SB_URL}/rest/v1/produce_currently_shipping?select=*&order=last_seen.desc,commodity`, { headers: SB_H })
          .then(r => r.ok ? r.json() : []),
        fetch(`${SB_URL}/rest/v1/produce_calendar_seasons?select=*&order=commodity,origin_market,month_num`, { headers: SB_H })
          .then(r => r.ok ? r.json() : []),
        fetch(`${SB_URL}/rest/v1/usda_reefer_lanes?select=*&order=avg_rate.desc`, { headers: SB_H })
          .then(r => r.ok ? r.json() : []),
      ]).then(([active, cal, lanes]) => {
        setActiveNow(Array.isArray(active) ? active : []);
        setCalData(Array.isArray(cal) ? cal : []);
        setLaneData(Array.isArray(lanes) ? lanes : []);
        setLoading(false);
      }).catch(() => setLoading(false));
    }, []);

    const calOrigins = useMemo(() => {
      const s = new Set(calData.map(d => d.origin_market).filter(Boolean));
      return ["all", ...Array.from(s).sort()];
    }, [calData]);

    const calRows = useMemo(() => {
      let src = calOrigin === "all" ? calData : calData.filter(d => d.origin_market === calOrigin);
      if (calSearch.trim()) {
        const q = calSearch.trim().toLowerCase();
        src = src.filter(d => (d.commodity || "").toLowerCase().includes(q));
      }
      const map = {};
      for (const row of src) {
        const key = `${row.commodity}||${row.origin_market}`;
        if (!map[key]) map[key] = { commodity: row.commodity, origin: row.origin_market, months: Array(12).fill(null) };
        const idx = (Number(row.month_num) || 1) - 1;
        if (idx >= 0 && idx < 12) map[key].months[idx] = row;
      }
      return Object.values(map).sort((a, b) => a.commodity.localeCompare(b.commodity));
    }, [calData, calOrigin, calSearch]);

    if (loading) {
      return (
        <main className="si-page-content">
          <div style={{ padding: "80px 32px", textAlign: "center", opacity: 0.4, fontSize: 14 }}>
            Loading reefer intel…
          </div>
        </main>
      );
    }

    return (
      <main className="si-page-content">
        <div style={{ maxWidth: 1160, margin: "0 auto", padding: "36px 20px 80px" }}>

          {/* Header */}
          <div style={{ marginBottom: 36 }}>
            <div style={{ fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", opacity: 0.45, marginBottom: 6 }}>
              Cold Chain
            </div>
            <h1 style={{ fontSize: 32, fontWeight: 700, margin: "0 0 8px", letterSpacing: "-0.02em" }}>
              Reefer Intel
            </h1>
            <p style={{ fontSize: 14, opacity: 0.55, margin: 0, maxWidth: 580 }}>
              Which produce is shipping, from where, at what rate, and whether trucks are tight —
              built from USDA AMS federal market reports, updated weekly.
            </p>
          </div>

          {/* Origins Map */}
          <ProduceOriginMap activeNow={activeNow} />

          {/* District Cards */}
          <DistrictCards activeNow={activeNow} />

          {/* Rate Explorer */}
          <RateExplorer lanes={laneData} onNav={onNav} />

          {/* Lane Flow Map — how produce gets to market + profitability */}
          <LaneFlowMap lanes={laneData} />

          {/* Produce Calendar */}
          <div style={{ marginBottom: 48 }}>
            <div style={{ fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", opacity: 0.45, marginBottom: 6 }}>
              Seasonal calendar
            </div>
            <h2 style={{ fontSize: 20, fontWeight: 700, margin: "0 0 4px", letterSpacing: "-0.01em" }}>
              Produce Shipping Calendar
            </h2>
            <p style={{ fontSize: 13, opacity: 0.55, margin: "0 0 16px" }}>
              When each commodity ships by district. Hover any cell for week count and rate.
              <span style={{ marginLeft: 8, background: "#fef9c3", borderRadius: 4, padding: "1px 6px", fontSize: 11, fontWeight: 600, color: "#92400e" }}>
                ★ Current month highlighted
              </span>
            </p>

            {/* Search + district filter row */}
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginBottom: 14, alignItems: "center" }}>
              <div style={{ position: "relative", flexShrink: 0 }}>
                <input
                  type="text"
                  placeholder="Search commodity…"
                  value={calSearch}
                  onChange={e => setCalSearch(e.target.value)}
                  style={{
                    fontFamily: "inherit", fontSize: 13, padding: "6px 10px 6px 30px",
                    border: "1px solid #d0d0d0", borderRadius: 6, background: "#fff",
                    color: "inherit", width: 180, outline: "none",
                  }}
                />
                <span style={{ position: "absolute", left: 9, top: "50%", transform: "translateY(-50%)", opacity: 0.35, fontSize: 14, pointerEvents: "none" }}>⌕</span>
              </div>
              {calOrigins.length > 2 && calOrigins.map(o => (
                <button key={o} onClick={() => setCalOrigin(o)} style={{
                  padding: "5px 13px", fontSize: 12, borderRadius: 20, cursor: "pointer",
                  border: "1px solid " + (calOrigin === o ? "#16a34a" : "#ddd"),
                  background: calOrigin === o ? "#16a34a" : "transparent",
                  color: calOrigin === o ? "#fff" : "inherit",
                  fontWeight: calOrigin === o ? 600 : 400,
                  transition: "all 0.15s",
                }}>
                  {o === "all" ? "All Districts" : shortDistrict(o)}
                </button>
              ))}
            </div>

            {calRows.length === 0 ? (
              <div style={{ padding: "60px 0", textAlign: "center", opacity: 0.4, fontSize: 14 }}>
                {calSearch ? `No results for "${calSearch}"` : "Calendar data loads as weekly USDA reports are ingested."}
              </div>
            ) : (
              <>
                <div style={{ overflowX: "auto", borderRadius: 10, border: "1px solid #e0e0e0", boxShadow: "0 2px 12px rgba(0,0,0,0.05)" }}>
                  <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
                    <thead>
                      <tr style={{ background: "#f7f7f7" }}>
                        <th style={{
                          textAlign: "left", padding: "11px 16px",
                          borderBottom: "2px solid #e0e0e0", fontWeight: 600,
                          minWidth: 230, whiteSpace: "nowrap",
                          position: "sticky", left: 0, background: "#f7f7f7", zIndex: 2,
                        }}>
                          Commodity · District
                          <span style={{ fontWeight: 400, opacity: 0.45, marginLeft: 8, fontSize: 11 }}>
                            {calRows.length} shown
                          </span>
                        </th>
                        {MONTHS.map((m, mi) => {
                          const isNow = (mi + 1) === NOW_MONTH;
                          return (
                            <th key={m} style={{
                              padding: "8px 2px", textAlign: "center",
                              borderBottom: "2px solid " + (isNow ? "#f59e0b" : "#e0e0e0"),
                              background: isNow ? "rgba(251,191,36,0.15)" : "transparent",
                              minWidth: 42, position: "relative",
                            }}>
                              <div style={{ fontSize: 11, fontWeight: isNow ? 700 : 500, color: isNow ? "#b45309" : "inherit", opacity: isNow ? 1 : 0.55 }}>
                                {m}
                              </div>
                              {isNow && (
                                <div style={{ fontSize: 9, fontWeight: 700, color: "#b45309", letterSpacing: "0.06em", marginTop: 1 }}>NOW</div>
                              )}
                            </th>
                          );
                        })}
                        <th style={{
                          padding: "11px 14px", textAlign: "right",
                          borderBottom: "2px solid #e0e0e0",
                          fontWeight: 500, opacity: 0.45, fontSize: 11, minWidth: 110, whiteSpace: "nowrap",
                        }}>Season</th>
                      </tr>
                    </thead>
                    <tbody>
                      {calRows.map((row, ri) => {
                        const activeMos = row.months.filter(Boolean).length;
                        const rates = row.months.filter(c => c && c.avg_rate > 0).map(c => c.avg_rate);
                        const avgRateAll = rates.length ? Math.round(rates.reduce((s, v) => s + v, 0) / rates.length) : null;
                        return (
                          <tr key={ri} className="reefer-cal-row" style={{ borderBottom: "1px solid #f0f0f0" }}>
                            <td style={{
                              padding: "7px 16px", position: "sticky", left: 0,
                              background: "#fff", zIndex: 1, whiteSpace: "nowrap",
                              borderBottom: "1px solid #f0f0f0",
                            }}>
                              <span style={{ fontWeight: 600, fontSize: 13 }}>{cap(row.commodity)}</span>
                              <span style={{ opacity: 0.35, fontSize: 11, marginLeft: 6 }}>· {shortDistrict(row.origin)}</span>
                            </td>
                            {row.months.map((cell, mi) => (
                              <CellBlock key={mi} cell={cell} monthIdx={mi} />
                            ))}
                            <td style={{ padding: "7px 14px", textAlign: "right", whiteSpace: "nowrap" }}>
                              <span style={{
                                display: "inline-block", fontSize: 11, fontWeight: 600,
                                color: activeMos >= 9 ? "#15803d" : activeMos >= 6 ? "#16a34a" : activeMos >= 3 ? "#ca8a04" : "#6b7280",
                                background: activeMos >= 9 ? "#dcfce7" : activeMos >= 6 ? "#f0fdf4" : activeMos >= 3 ? "#fef9c3" : "#f3f4f6",
                                borderRadius: 20, padding: "2px 8px",
                              }}>
                                {activeMos} mo
                              </span>
                              {avgRateAll && (
                                <span style={{ fontSize: 11, opacity: 0.45, marginLeft: 6 }}>
                                  ~${Math.round(avgRateAll / 1000)}k avg
                                </span>
                              )}
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>

                {/* Legend */}
                <div style={{ marginTop: 14, display: "flex", flexWrap: "wrap", gap: 14, alignItems: "center", fontSize: 12 }}>
                  {[
                    { bg: "#14532d", label: "Peak · 4+ weeks", glow: true },
                    { bg: "#16a34a", label: "Strong · 3 weeks", glow: false },
                    { bg: "#4ade80", label: "Active · 2 weeks", glow: false },
                    { bg: "#bbf7d0", label: "Light · 1 week",  glow: false },
                    { bg: "#efefef", label: "Off season",       glow: false },
                  ].map(({ bg, label, glow }) => (
                    <div key={label} style={{ display: "flex", alignItems: "center", gap: 5, opacity: 0.7 }}>
                      <span style={{
                        display: "inline-block", width: 20, height: 14, borderRadius: 3, background: bg,
                        boxShadow: glow ? "0 0 6px rgba(20,83,45,0.5)" : "none",
                      }} />
                      {label}
                    </div>
                  ))}
                  <span style={{ marginLeft: "auto", opacity: 0.4 }}>
                    <a href="https://www.ams.usda.gov/market-news" target="_blank" rel="noopener noreferrer" style={{ color: "inherit" }}>USDA AMS Market News</a> · Updated weekly
                  </span>
                </div>
              </>
            )}
          </div>

          {/* Fuel-impact article callout */}
          <div style={{
            padding: "20px 24px", borderRadius: 8,
            border: "1px solid #fde4cf", background: "#fef9f3",
            display: "flex", alignItems: "center", justifyContent: "space-between",
            flexWrap: "wrap", gap: 16, marginBottom: 14,
          }}>
            <div style={{ maxWidth: 540 }}>
              <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", fontWeight: 700, color: "#b45309", marginBottom: 6 }}>
                ⛽  New · Markets desk
              </div>
              <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 4 }}>
                Diesel is eating the reefer rate
              </div>
              <div style={{ fontSize: 13, opacity: 0.7, lineHeight: 1.45 }}>
                Why several West-Coast and short-haul protein lanes plot below the $2.10/mi breakeven right now —
                and what shippers should expect when the surcharge program lags the pump.
              </div>
            </div>
            <button onClick={() => {
              window.location.hash = "#/insights/diesel-eats-the-reefer-rate-2026";
            }} style={{
              padding: "9px 20px", borderRadius: 6, border: "1px solid #b45309", cursor: "pointer",
              background: "#b45309", color: "white", fontWeight: 600, fontSize: 13, whiteSpace: "nowrap",
            }}>
              Read the analysis →
            </button>
          </div>

          {/* Tools callout */}
          <div style={{
            padding: "20px 24px", borderRadius: 8,
            border: "1px solid #e0dff5", background: "#f8f7ff",
            display: "flex", alignItems: "center", justifyContent: "space-between",
            flexWrap: "wrap", gap: 16,
          }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>Know the rate — now run the numbers</div>
              <div style={{ fontSize: 13, opacity: 0.6 }}>
                Fuel surcharge, load pay calculator, owner-op CPM — all free.
              </div>
            </div>
            <button onClick={() => onNav("tools")} style={{
              padding: "9px 20px", borderRadius: 6, border: "none", cursor: "pointer",
              background: "#4a3fbf", color: "white", fontWeight: 600, fontSize: 13, whiteSpace: "nowrap",
            }}>
              Open Rate Calculators →
            </button>
          </div>

        </div>
      </main>
    );
  };
})();
