// Drivers hub — the front door for the people who actually move the freight.
// Free utilities + the trust contract. Recruitment surface for the data engine.

const { useState: useStateDr, useEffect: useEffectDr, useRef: useRefDr, useMemo: useMemoDr } = React;

const YR_CHAIN_COLOR = {
  pilot: "#E31837", ta: "#0C4DA2", loves: "#E51E25", sapp: "#0F4DA8",
  petro: "#FFA94D", "love-s": "#E51E25",
};

// =============================================================
// YARD RADAR — driver-utility map. Truck stops (chain-colored)
// + cold-storage receivers (driver-relevant brands) + cross-dock
// terminals. Same dark control-room treatment as the other
// radars but with warm chain colors so it feels like a driver's
// dispatch console, not a corporate dashboard.
// =============================================================

function YardRadar({ user, onNav }) {
  const mapRef = useRefDr(null);
  const containerRef = useRefDr(null);
  const layersRef = useRefDr({});
  const lcRef = useRefDr(null);
  const [stops, setStops] = useStateDr([]);
  const [coldRcv, setColdRcv] = useStateDr([]);
  const [terminals, setTerminals] = useStateDr([]);
  const [activeChain, setActiveChain] = useStateDr(null);
  const [loading, setLoading] = useStateDr(true);

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

  useEffectDr(() => {
    let alive = true;
    if (!window.SI_DB || !window.SI_DB.raw) return;
    (async () => {
      const [ts, rcv, terms, carriers] = await Promise.all([
        window.SI_DB.raw.select("truck_stops",
          "select=id,chain,name,lat,lng,city,state,metro_city_id&limit=2500"
        ).catch(() => []),
        window.SI_DB.raw.select("receiver_locations",
          "select=brand,name,lat,lng,city,state&brand=in.(lineage,americold)&limit=200"
        ).catch(() => []),
        window.SI_DB.raw.select("entities",
          "select=id,slug,name,parent_id,lat,lng,address&type=eq.facility_xdock"
        ).catch(() => []),
        window.SI_DB.raw.select("entities",
          "select=id,slug,name&type=eq.carrier"
        ).catch(() => []),
      ]);
      if (!alive) return;
      const idToSlug = {};
      (carriers || []).forEach(c => { idToSlug[c.id] = c.slug; });
      const termsWithSlug = (terms || []).map(t => ({
        ...t, carrier_slug: idToSlug[t.parent_id] || null,
      })).filter(t => t.lat != null && t.lng != null);
      setStops(Array.isArray(ts) ? ts : []);
      setColdRcv(Array.isArray(rcv) ? rcv : []);
      setTerminals(termsWithSlug);
      setLoading(false);
    })();
    return () => { alive = false; };
  }, []);

  const chains = useMemoDr(() => {
    const counts = {};
    stops.forEach(s => { if (s.chain) counts[s.chain] = (counts[s.chain] || 0) + 1; });
    return Object.entries(counts).sort((a,b) => b[1]-a[1]);
  }, [stops]);

  const stopsFiltered = useMemoDr(() =>
    stops.filter(s => s.lat != null && s.lng != null && (!activeChain || s.chain === activeChain)),
    [stops, activeChain]);

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

  // Layers.
  useEffectDr(() => {
    const map = mapRef.current;
    if (!map || !window.L) return;
    const oldLayers = Object.values(layersRef.current);
    oldLayers.forEach(lg => { if (lg && map.hasLayer(lg)) map.removeLayer(lg); });
    layersRef.current = {};

    function dot(latLng, color, size, popupHtml) {
      const html = `<span style="display:inline-block;width:${size}px;height:${size}px;
        border-radius:50%;background:${color};border:1.5px solid rgba(255,255,255,0.55);
        box-shadow:0 0 4px rgba(0,0,0,0.5)"></span>`;
      const icon = window.L.divIcon({
        className: "yr-icon", html,
        iconSize: [size + 4, size + 4], iconAnchor: [(size + 4) / 2, (size + 4) / 2],
      });
      const m = window.L.marker(latLng, { icon, riseOnHover: true });
      if (popupHtml) m.bindPopup(popupHtml);
      return m;
    }

    const stopsLayer = window.L.layerGroup(stopsFiltered.map(s => {
      const color = YR_CHAIN_COLOR[s.chain] || "#FFB347";
      const popup = isAuthed ? `
        <div class="yr-pop">
          <div class="yr-pop-eye" style="color:${color}">🛻 ${(s.chain || "stop").toUpperCase()}</div>
          <div class="yr-pop-num">${s.name || (s.chain || "Truck stop")}</div>
          <div class="yr-pop-meta">${[s.city, s.state].filter(Boolean).join(", ") || `${s.lat.toFixed(3)}, ${s.lng.toFixed(3)}`}</div>
          <a class="yr-pop-link" target="_blank" rel="noopener noreferrer"
             href="https://www.google.com/maps/search/?api=1&query=${encodeURIComponent((s.name||"")+" "+(s.city||""))}">
             Open in Maps ↗
          </a>
        </div>` : `
        <div class="yr-pop">
          <div class="yr-pop-eye" style="color:${color}">🛻 ${(s.chain || "stop").toUpperCase()}</div>
          <div class="yr-pop-meta yr-pop-cta">Sign in for name · address · maps deep-link →</div>
        </div>`;
      return dot([s.lat, s.lng], color, 6, popup);
    }));

    const coldLayer = window.L.layerGroup(coldRcv.filter(r => r.lat != null && r.lng != null)
      .map(r => {
        const color = "#22D3EE";
        const popup = isAuthed ? `
          <div class="yr-pop">
            <div class="yr-pop-eye" style="color:${color}">❄️ ${(r.brand || "").toUpperCase()}</div>
            <div class="yr-pop-num">${r.name || r.brand}</div>
            <div class="yr-pop-meta">${[r.city, r.state].filter(Boolean).join(", ")}</div>
          </div>` : `
          <div class="yr-pop">
            <div class="yr-pop-eye" style="color:${color}">❄️ Cold storage</div>
            <div class="yr-pop-meta yr-pop-cta">Sign in for name · address →</div>
          </div>`;
        return dot([r.lat, r.lng], color, 9, popup);
      }));

    const termLayer = window.L.layerGroup(terminals.map(t => {
      const color = "#A78BFA";
      const popup = isAuthed ? `
        <div class="yr-pop">
          <div class="yr-pop-eye" style="color:${color}">🚚 ${(t.carrier_slug || "").replace(/-/g," ").toUpperCase()}</div>
          <div class="yr-pop-num">${t.name}</div>
          <div class="yr-pop-meta">${t.address || ""}</div>
        </div>` : `
        <div class="yr-pop">
          <div class="yr-pop-eye" style="color:${color}">🚚 LTL terminal</div>
          <div class="yr-pop-meta yr-pop-cta">Sign in for carrier · address →</div>
        </div>`;
      return dot([t.lat, t.lng], color, 10, popup);
    }));

    stopsLayer.addTo(map);
    coldLayer.addTo(map);
    termLayer.addTo(map);
    layersRef.current = { stops: stopsLayer, cold: coldLayer, terms: termLayer };

    if (!lcRef.current) {
      lcRef.current = window.L.control.layers(null, {}, {
        collapsed: false, position: "bottomleft",
      }).addTo(map);
    } else {
      oldLayers.forEach(lg => lcRef.current.removeLayer(lg));
    }
    lcRef.current.addOverlay(stopsLayer, `🛻 Truck stops (${stopsFiltered.length})`);
    lcRef.current.addOverlay(coldLayer,  `❄️ Cold storage (${coldRcv.length})`);
    lcRef.current.addOverlay(termLayer,  `🚚 LTL terminals (${terminals.length})`);
  }, [stopsFiltered, coldRcv, terminals, isAuthed]);

  return (
    <section className="yr-radar">
      <style>{`
        .yr-radar { position: relative; background: #0a0e15; overflow: hidden;
          border-bottom: 1px solid #1f2937; }
        .yr-radar-map { width: 100%; height: 70vh; min-height: 500px; max-height: 760px; background: #0a0e15; }
        @media (max-width: 760px) { .yr-radar-map { height: 60vh; min-height: 400px; } }
        .yr-radar-map::after {
          content: ""; position: absolute; inset: 0; pointer-events: none;
          background: radial-gradient(ellipse at center, transparent 55%, rgba(10,14,21,0.55) 100%);
          z-index: 401;
        }
        .yr-icon { background: transparent !important; border: 0 !important; }
        .yr-title { position: absolute; top: 18px; left: 22px; z-index: 500;
          color: #fff; pointer-events: none; max-width: 600px; }
        .yr-title-eye { font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.18em;
          text-transform: uppercase; color: #FFB347;
          display: inline-flex; align-items: center; gap: 8px;
          padding: 6px 10px; background: rgba(0,0,0,0.5); border-radius: 4px;
          backdrop-filter: blur(6px); }
        .yr-title-eye .dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%;
          background: #FFB347; animation: yr-livedot 1.6s ease-in-out infinite; }
        @keyframes yr-livedot {
          0%, 100% { box-shadow: 0 0 0 0 rgba(255,179,71,0.6); }
          70% { box-shadow: 0 0 0 8px rgba(255,179,71,0); }
        }
        .yr-title-h { font-family: var(--font-serif); font-size: clamp(28px, 4vw, 44px);
          line-height: 1.05; letter-spacing: -0.025em; margin: 12px 0 6px;
          text-shadow: 0 2px 16px rgba(0,0,0,0.6); }
        .yr-title-h em { font-style: italic; color: #FFB347; }
        .yr-title-sub { font-size: 14px; color: #cbd5e1; line-height: 1.45;
          text-shadow: 0 1px 8px rgba(0,0,0,0.6); max-width: 540px; }

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

        .yr-cta-overlay { position: absolute; top: 18px; right: 22px; z-index: 500;
          background: rgba(10,14,21,0.85); backdrop-filter: blur(10px);
          border: 1px solid rgba(255,179,71,0.35); border-radius: 8px;
          padding: 14px 18px; max-width: 320px; color: #f1f5f9;
          box-shadow: 0 12px 36px rgba(0,0,0,0.4); }
        .yr-cta-eye { font-family: var(--font-mono); font-size: 10px;
          letter-spacing: 0.18em; text-transform: uppercase; color: #FFB347; margin-bottom: 6px; }
        .yr-cta-h { font-family: var(--font-serif); font-size: 17px;
          letter-spacing: -0.015em; margin: 0 0 6px; }
        .yr-cta-sub { font-size: 12px; color: #94a3b8; line-height: 1.45; margin-bottom: 10px; }
        .yr-cta-btn { display: inline-flex; align-items: center; gap: 6px;
          background: #FFB347; color: #0a0e15; border: 0;
          padding: 8px 14px; border-radius: 5px; font-family: inherit;
          font-weight: 600; font-size: 13px; cursor: pointer; }
        .leaflet-control-layers { background: rgba(10,14,21,0.85) !important; backdrop-filter: blur(10px);
          border: 1px solid rgba(255,255,255,0.08) !important; border-radius: 6px !important;
          padding: 10px 12px !important; color: #cbd5e1 !important; font-family: var(--font-mono); font-size: 11px; }
        .leaflet-control-layers label { color: #cbd5e1 !important; }
        .leaflet-popup-content-wrapper { background: rgba(10,14,21,0.95) !important; color: #f1f5f9;
          border: 1px solid rgba(255,255,255,0.08); border-radius: 8px; }
        .leaflet-popup-tip { background: rgba(10,14,21,0.95) !important; }
        .leaflet-popup-close-button { color: #94a3b8 !important; }
        .leaflet-control-zoom a { background: rgba(10,14,21,0.85) !important; color: #cbd5e1 !important;
          border: 1px solid rgba(255,255,255,0.08) !important; }
        .yr-pop { font-family: var(--font-sans, system-ui); min-width: 200px; padding: 4px 2px; }
        .yr-pop-eye { font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.14em;
          text-transform: uppercase; margin-bottom: 4px; }
        .yr-pop-num { font-family: var(--font-serif); font-size: 16px; letter-spacing: -0.01em; color: #f1f5f9; }
        .yr-pop-meta { font-size: 11px; color: #94a3b8; margin-top: 4px; line-height: 1.45; }
        .yr-pop-cta { color: #FFB347; font-weight: 500; }
        .yr-pop-link { display: inline-block; margin-top: 8px; font-family: var(--font-mono);
          font-size: 10px; letter-spacing: 0.12em; text-transform: uppercase; color: #FFB347;
          text-decoration: none; border-bottom: 1px dotted #FFB347; }
      `}</style>

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

      <div className="yr-title">
        <span className="yr-title-eye">
          <span className="dot" />
          {loading ? "Loading the network…" :
            `${stopsFiltered.length.toLocaleString()} stops · ${coldRcv.length} cold · ${terminals.length} terminals`}
        </span>
        <h1 className="yr-title-h">
          Your road, <em>mapped.</em>
        </h1>
        <p className="yr-title-sub">
          Pilot · TA · Love's · Sapp Bros, plus every named cold-storage and cross-dock terminal.
          Free for drivers, forever. Filter by chain below.
        </p>
      </div>

      {!isAuthed && (
        <div className="yr-cta-overlay">
          <div className="yr-cta-eye"><span style={{display:"inline-block",width:6,height:6,borderRadius:"50%",background:"#FFB347",marginRight:6,verticalAlign:"middle"}}/>Anonymous view</div>
          <h3 className="yr-cta-h">Tap-to-route from any pin.</h3>
          <p className="yr-cta-sub">
            Sign in for the stop name, address, and one-tap "Open in Maps" link.
            Free magic-link, free forever for drivers.
          </p>
          <button className="yr-cta-btn" onClick={() => onNav("signin")}>Sign in →</button>
        </div>
      )}

      <div className="yr-chips">
        <button className="yr-chip" data-active={activeChain === null}
                onClick={() => setActiveChain(null)}>
          ALL · {stops.length.toLocaleString()}
        </button>
        {chains.map(([chain, count]) => (
          <button key={chain} className="yr-chip"
                  data-active={activeChain === chain}
                  style={{ "--chip-c": YR_CHAIN_COLOR[chain] || "#FFB347" }}
                  onClick={() => setActiveChain(activeChain === chain ? null : chain)}>
            <span className="yr-chip-dot" />
            {chain.toUpperCase()}
            <span className="yr-chip-meta">{count.toLocaleString()}</span>
          </button>
        ))}
      </div>
    </section>
  );
}

function DriversPage({ onNav }) {
  const [authedUser, setAuthedUser] = useStateDr(null);
  // Inline magic-link state for the gate. Drivers send themselves a sign-in
  // link without leaving The Yard; the dashboard auth flow takes over from
  // their email client.
  const [gateEmail, setGateEmail] = useStateDr("");
  const [gateBusy, setGateBusy] = useStateDr(false);
  const [gateSent, setGateSent] = useStateDr(false);
  const [gateErr, setGateErr] = useStateDr(null);

  useEffectDr(() => {
    let alive = true;
    if (window.SI_DB && window.SI_DB.auth && window.SI_DB.auth.getCurrentUser) {
      window.SI_DB.auth.getCurrentUser().then(u => { if (alive) setAuthedUser(u); }).catch(() => {});
    }
    return () => { alive = false; };
  }, []);

  async function gateSubmit(e) {
    e.preventDefault();
    const v = gateEmail.trim();
    if (!v.includes("@")) { setGateErr("That email looks off — double-check it."); return; }
    setGateBusy(true); setGateErr(null);
    try {
      await window.SI_DB.auth.sendMagicLink(v);
      setGateSent(true);
    } catch (err) {
      setGateErr(String(err && err.message || "Couldn't send the link. Try again in a minute."));
    } finally {
      setGateBusy(false);
    }
  }
  const isAuthed = !!(authedUser && authedUser.email);
  // Service plaques — every utility this platform offers a driver, in one
  // flat grid so a cold visitor takes in the whole menu at a glance. Each
  // plaque carries an accent stripe whose hue groups it loosely (blue =
  // places, green = tools, red = voice) without forcing section dividers.
  const tiles = [
    {
      icon: "🛰", title: "Find your dock",
      kicker: "33,000+ docks · 18 brands",
      body: "Every Walmart, Home Depot, Lowe's, Target, Costco, Kroger, Aldi, Safeway, Publix, Amazon FC, and named cold-storage receiver. Search by brand, state, or city. Open in maps.",
      cta: "Find a dock", accent: "oklch(0.55 0.18 250)",
      onClick: () => onNav("receivers"),
    },
    {
      icon: "🛻", title: "Truck stops",
      kicker: "Pilot · TA · Love's · Sapp Bros",
      body: "2,250+ truck stops on the network, color-coded by chain, with one-tap directions. No login, no ads, no tracking.",
      cta: "See the map", accent: "oklch(0.55 0.18 250)",
      onClick: () => onNav("account"),
    },
    {
      icon: "⚖", title: "Weigh stations",
      kicker: "All 48 + DC · OSM-pinned",
      body: "Every state weigh and inspection station. One-tap directions, search by name, filter by state. Live open / bypass / closed status is on the way.",
      cta: "Open the map", accent: "oklch(0.55 0.18 250)",
      onClick: () => onNav("weigh"),
    },
    {
      icon: "🛣", title: "Toll roads + passes",
      kicker: "5-axle rates · pass coverage",
      body: "Every major US toll road with truck rates and plate-billing premiums. Pass cards show which states each transponder covers — E-ZPass, SunPass, TollTag, PikePass, FasTrak, Bestpass.",
      cta: "Open the table", accent: "oklch(0.55 0.18 250)",
      onClick: () => onNav("tolls"),
    },
    {
      icon: "🔧", title: "Truck + reefer repair",
      kicker: "Truck / reefer / both",
      body: "Mechanical service across the lower 48. Filter truck-only, reefer-only, or both. Thermo King + Carrier Transicold detection. Phone, hours, directions in every popup.",
      cta: "Find a shop", accent: "oklch(0.55 0.18 250)",
      onClick: () => onNav("repair"),
    },
    {
      icon: "🏗", title: "Carrier hub atlas",
      kicker: "Where the carriers actually operate",
      body: "Carrier-owned terminals and sortation hubs — UPS, FedEx, Amazon, Old Dominion, Saia, Estes — grouped by city and carrier. Private network nodes, not third-party cross-dock services.",
      cta: "Browse the atlas", accent: "oklch(0.55 0.18 250)",
      onClick: () => onNav("xdocks"),
    },
    {
      icon: "🧰", title: "Driver tools",
      kicker: "6 tools · all free, all private",
      body: "HOS clock · pay-per-hour calculator · detention timer with dispute-letter generator · fuel surcharge · OO breakeven CPM · CDL / medical / hazmat / TWIC renewal tracker. Local to your device.",
      cta: "Open tools", accent: "oklch(0.55 0.18 145)",
      onClick: () => onNav("tools"),
    },
    {
      icon: "📜", title: "Hours of service",
      kicker: "49 CFR 395 · plain English",
      body: "Every limit a property-carrying driver lives under. Six rules, the splits, the exceptions, and the questions drivers actually ask — with citation if you need it on the side of the road.",
      cta: "Read the rules", accent: "oklch(0.55 0.18 145)",
      onClick: () => onNav("hos"),
    },
    {
      icon: "🌩", title: "Weather + roads",
      kicker: "22 metros · live",
      body: "7-day forecasts, severe-weather alerts, and road conditions across the freight network. Same read our paid subscribers get.",
      cta: "Open the dashboard", accent: "oklch(0.55 0.18 145)",
      onClick: () => onNav("account"),
    },
    {
      icon: "📨", title: "Drop a tip",
      kicker: "Sealed by default · you choose",
      body: "Yard going sideways? Dock running four hours late? Manager pushing illegal hours? Tell us. You decide what's public, what stays sealed, and you can delete it any time.",
      cta: "Submit anonymously", accent: "oklch(0.55 0.20 25)",
      onClick: () => onNav("terminals"),
    },
    {
      icon: "🗑", title: "Manage your tips",
      kicker: "Email-token · no account needed",
      body: "Anything you submitted, you control. Sealed tips get hard-deleted. Public tips get your name pulled. Always. No questions.",
      cta: "Manage my tips", accent: "oklch(0.55 0.20 25)",
      onClick: () => onNav("manage"),
    },
    {
      icon: "📊", title: "Methodology",
      kicker: "How we score · what we promise",
      body: "The full trust contract — what we publish, what we never publish, how driver intel rolls into facility scores (and why it doesn't tank carrier headlines on one bad day).",
      cta: "See the math", accent: "oklch(0.55 0.20 25)",
      onClick: () => onNav("methodology"),
    },
  ];

  return (
    <div className="drivers-page">
      {/* YARD RADAR — driver-facing focal map: truck stops, cold storage,
          cross-dock terminals. Free for drivers, forever. */}
      <YardRadar user={authedUser} onNav={onNav} />
      <style>{`
        .drivers-page { background: var(--paper, #fff); }

        .dr-hero { padding: 88px 24px 56px; max-width: 1100px; margin: 0 auto; position: relative; }
        .dr-mark {
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.32em;
          text-transform: uppercase; color: var(--ink-soft); margin-bottom: 28px;
          display: inline-flex; align-items: center; gap: 10px;
        }
        .dr-mark .dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%;
          background: oklch(0.55 0.18 145); animation: dr-pulse 1.6s infinite; }
        @keyframes dr-pulse { 0%,100%{opacity:1;transform:scale(1)} 50%{opacity:0.55;transform:scale(0.85)} }
        .dr-quote {
          font-family: var(--font-serif); font-size: 64px; line-height: 1.04;
          letter-spacing: -0.028em; margin: 0; font-weight: 400; color: var(--ink);
          max-width: 980px;
        }
        .dr-quote em { font-style: italic; color: var(--red, oklch(0.50 0.16 250)); }
        .dr-quote-attr {
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.18em;
          text-transform: uppercase; color: var(--ink-soft); margin-top: 24px;
        }
        @media (max-width: 700px) { .dr-quote { font-size: 38px; } }

        .dr-stats {
          margin-top: 48px; padding-top: 28px; border-top: 1px solid var(--rule);
          display: grid; grid-template-columns: repeat(4, 1fr); gap: 0;
        }
        @media (max-width: 880px) { .dr-stats { grid-template-columns: repeat(2, 1fr); } }
        @media (max-width: 480px) { .dr-stats { grid-template-columns: 1fr; gap: 14px; } }
        .dr-stat {
          padding: 0 28px; border-right: 1px solid var(--rule);
          display: flex; flex-direction: column; gap: 6px;
        }
        .dr-stat:first-child { padding-left: 0; }
        .dr-stat:last-child { border-right: 0; padding-right: 0; }
        @media (max-width: 880px) {
          .dr-stat { padding: 0 20px; }
          .dr-stat:nth-child(2n) { border-right: 0; }
          .dr-stat:nth-child(2n+1) { padding-left: 0; }
        }
        @media (max-width: 480px) {
          .dr-stat { padding: 0; border-right: 0; border-bottom: 1px solid var(--rule); padding-bottom: 14px; }
          .dr-stat:last-child { border-bottom: 0; padding-bottom: 0; }
        }
        .dr-stat-num {
          font-family: var(--font-serif); font-size: 32px; line-height: 1;
          letter-spacing: -0.02em; color: var(--ink); font-weight: 600;
        }
        .dr-stat-l {
          font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.14em;
          text-transform: uppercase; color: var(--ink-soft); line-height: 1.4;
        }
        .dr-stat-l strong { color: oklch(0.55 0.18 145); font-weight: 700; }

        .dr-grid-section { max-width: 1180px; margin: 40px auto 32px; padding: 0 24px; }
        .dr-grid-h {
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.32em;
          text-transform: uppercase; color: var(--ink-soft); padding-bottom: 14px;
          border-bottom: 1px solid var(--rule); margin-bottom: 28px;
          display: flex; justify-content: space-between; align-items: baseline;
        }
        .dr-grid-h-r { font-size: 10px; letter-spacing: 0.16em; }
        .dr-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 18px; }
        @media (max-width: 980px) { .dr-grid { grid-template-columns: repeat(2, 1fr); } }
        @media (max-width: 640px) { .dr-grid { grid-template-columns: 1fr; } }

        /* Plaque — every tile carries a vertical accent rail (color set per
           tile via --accent inline style). Hover lifts the plaque, deepens
           the rail, and reveals a faint inner glow. */
        .dr-tile {
          background: #fff; border: 1px solid var(--rule); border-radius: 8px;
          padding: 26px 26px 24px 30px;
          display: flex; flex-direction: column; position: relative;
          transition: border-color 0.18s, transform 0.18s, box-shadow 0.18s;
          cursor: pointer; overflow: hidden;
          min-height: 230px;
        }
        .dr-tile::before {
          content: ""; position: absolute; top: 0; bottom: 0; left: 0; width: 4px;
          background: var(--accent, var(--ink));
          transition: width 0.18s;
        }
        .dr-tile:hover {
          border-color: var(--ink);
          transform: translateY(-3px);
          box-shadow: 0 12px 28px -16px oklch(0.25 0.02 250 / 0.25);
        }
        .dr-tile:hover::before { width: 6px; }
        .dr-tile-icon {
          font-size: 32px; line-height: 1; margin-bottom: 16px;
          width: 52px; height: 52px; border-radius: 8px;
          display: inline-flex; align-items: center; justify-content: center;
          background: color-mix(in oklch, var(--accent, var(--ink)) 10%, #fff);
        }
        .dr-tile-kicker {
          font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.18em;
          text-transform: uppercase;
          color: color-mix(in oklch, var(--accent, var(--ink)) 80%, var(--ink-soft));
          margin-bottom: 8px; font-weight: 600;
        }
        .dr-tile-title {
          font-family: var(--font-serif); font-size: 24px; letter-spacing: -0.012em;
          margin: 0 0 12px; line-height: 1.18; color: var(--ink); font-weight: 600;
        }
        .dr-tile-body {
          color: var(--ink-soft); font-size: 14px; line-height: 1.55;
          margin: 0 0 20px; flex: 1;
        }
        .dr-tile-cta {
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.14em;
          text-transform: uppercase; font-weight: 700;
          color: var(--accent, var(--ink));
        }

        .dr-rules { background: oklch(0.97 0.005 60); border-top: 1px solid var(--rule);
          border-bottom: 1px solid var(--rule); padding: 56px 24px; margin-top: 56px; }
        .dr-rules-inner { max-width: 1100px; margin: 0 auto; }
        .dr-rules-h {
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.32em;
          text-transform: uppercase; color: var(--ink-soft); margin-bottom: 28px;
          display: flex; justify-content: space-between; align-items: baseline;
          padding-bottom: 14px; border-bottom: 1px solid var(--rule);
        }
        .dr-rules-grid {
          display: grid; grid-template-columns: repeat(4, 1fr); gap: 0;
        }
        @media (max-width: 880px) { .dr-rules-grid { grid-template-columns: repeat(2, 1fr); } }
        @media (max-width: 480px) { .dr-rules-grid { grid-template-columns: 1fr; } }
        .dr-rule {
          padding: 0 28px 0 0; border-right: 1px solid var(--rule);
          display: flex; flex-direction: column; gap: 12px;
        }
        .dr-rule:last-child { border-right: 0; padding-right: 0; }
        @media (max-width: 880px) {
          .dr-rule { padding: 0 24px 24px 0; border-right: 0;
            border-bottom: 1px solid var(--rule); margin-bottom: 24px; }
          .dr-rule:last-child { border-bottom: 0; margin-bottom: 0; padding-bottom: 0; }
        }
        .dr-rule + .dr-rule { padding-left: 28px; }
        @media (max-width: 880px) { .dr-rule + .dr-rule { padding-left: 0; } }
        .dr-rule-num {
          font-family: var(--font-serif); font-size: 44px; letter-spacing: -0.04em;
          line-height: 1; color: var(--red, oklch(0.50 0.16 250)); font-weight: 600;
        }
        .dr-rule-h {
          font-family: var(--font-serif); font-size: 17px; letter-spacing: -0.005em;
          margin: 0; line-height: 1.25;
        }
        .dr-rule-b {
          font-size: 13px; color: var(--ink-soft); line-height: 1.5; margin: 0;
        }

        .dr-gate {
          max-width: 1100px; margin: 24px auto 0; padding: 40px 24px;
          background: #fff; border: 1px solid var(--rule); border-radius: 8px;
          position: relative; overflow: hidden;
        }
        .dr-gate::before {
          content: ""; position: absolute; left: 0; top: 0; bottom: 0; width: 4px;
          background: oklch(0.55 0.18 145);
        }
        .dr-gate-h {
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.32em;
          text-transform: uppercase; color: var(--ink-soft); margin-bottom: 16px;
          padding-bottom: 14px; border-bottom: 1px solid var(--rule);
        }
        .dr-gate-title {
          font-family: var(--font-serif); font-size: 30px; line-height: 1.18;
          letter-spacing: -0.02em; margin: 0 0 14px; color: var(--ink);
        }
        .dr-gate-sub {
          font-size: 15px; line-height: 1.55; color: var(--ink-soft);
          margin: 0 0 24px; max-width: 720px;
        }
        .dr-gate-form {
          display: flex; gap: 8px; max-width: 560px; align-items: stretch;
          flex-wrap: wrap;
        }
        .dr-gate-email {
          flex: 1; min-width: 240px; font-family: inherit; font-size: 15px;
          padding: 12px 14px; border: 1px solid var(--rule); border-radius: 6px;
          background: var(--paper); color: var(--ink); outline: none;
          transition: border-color 0.15s;
        }
        .dr-gate-email:focus { border-color: var(--ink); }
        .dr-gate-btn {
          font-family: inherit; font-size: 14px; padding: 12px 22px;
          border-radius: 6px; cursor: pointer; border: 1px solid var(--ink);
          background: var(--ink); color: #fff; font-weight: 600;
          letter-spacing: 0.02em; white-space: nowrap;
        }
        .dr-gate-btn:hover { opacity: 0.85; }
        .dr-gate-btn:disabled { opacity: 0.5; cursor: not-allowed; }
        .dr-gate-foot {
          margin-top: 16px; font-family: var(--font-mono); font-size: 11px;
          letter-spacing: 0.06em; color: var(--ink-soft); line-height: 1.6;
        }
        .dr-gate-foot a {
          color: var(--ink); border-bottom: 1px solid var(--rule);
          padding-bottom: 1px; text-decoration: none;
        }
        .dr-gate-msg {
          margin-top: 14px; padding: 12px 14px; border-radius: 6px;
          font-size: 14px; line-height: 1.5;
        }
        .dr-gate-msg-ok {
          background: oklch(0.96 0.04 145); color: oklch(0.40 0.14 145);
          border: 1px solid oklch(0.85 0.08 145);
        }
        .dr-gate-msg-err {
          background: oklch(0.96 0.05 25); color: oklch(0.40 0.18 25);
          border: 1px solid oklch(0.85 0.10 25);
        }

        .dr-utility {
          max-width: 1100px; margin: 0 auto; padding: 56px 24px 0;
        }
        .dr-utility-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; }
        @media (max-width: 640px) { .dr-utility-grid { grid-template-columns: 1fr; } }
        .dr-utility-tile {
          background: #fff; border: 1px solid var(--rule); border-radius: 6px;
          padding: 18px 20px; display: grid; grid-template-columns: 32px 1fr auto;
          gap: 16px; align-items: center; cursor: pointer;
          transition: border-color 0.15s;
        }
        .dr-utility-tile:hover { border-color: var(--ink); }
        .dr-utility-icon { font-size: 22px; line-height: 1; }
        .dr-utility-body h4 {
          font-family: var(--font-serif); font-size: 17px; letter-spacing: -0.005em;
          margin: 0 0 4px;
        }
        .dr-utility-body p {
          margin: 0; font-size: 12px; color: var(--ink-soft); line-height: 1.45;
        }
        .dr-utility-cta {
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.14em;
          text-transform: uppercase; color: var(--ink); font-weight: 700;
          white-space: nowrap;
        }

        .dr-cta-section { padding: 72px 24px 96px; max-width: 1100px; margin: 0 auto; }
        .dr-cta-row {
          display: grid; grid-template-columns: 1fr auto; gap: 32px; align-items: center;
          padding-top: 32px; border-top: 1px solid var(--rule);
        }
        @media (max-width: 700px) { .dr-cta-row { grid-template-columns: 1fr; } }
        .dr-cta-line {
          font-family: var(--font-serif); font-size: 26px; letter-spacing: -0.015em;
          line-height: 1.3; margin: 0; color: var(--ink);
        }
        .dr-cta-btn { font-family: inherit; font-size: 14px; padding: 14px 22px;
          border-radius: 6px; cursor: pointer; border: 1px solid var(--ink);
          background: var(--ink); color: #fff; font-weight: 600;
          letter-spacing: 0.02em; white-space: nowrap;
        }
        .dr-cta-btn:hover { opacity: 0.85; }
      `}</style>

      <section className="dr-hero">
        <div className="dr-mark"><span className="dot" /> The Yard</div>
        <h1 className="dr-quote">
          Ask the <em>drivers.</em>
        </h1>
        <div className="dr-quote-attr">
          If you want to know what's going on at a trucking company.
        </div>

        {/* Stat strip — what's actually in the yard right now. Numbers are
            stable infrastructure counts (receivers, truck stops, metros) +
            the always-free promise. Reads as a posted board, not a pitch. */}
        <div className="dr-stats">
          <div className="dr-stat">
            <div className="dr-stat-num">33,455</div>
            <div className="dr-stat-l">Docks pinned · 18 brands</div>
          </div>
          <div className="dr-stat">
            <div className="dr-stat-num">2,254</div>
            <div className="dr-stat-l">Truck stops on the network</div>
          </div>
          <div className="dr-stat">
            <div className="dr-stat-num">22</div>
            <div className="dr-stat-l">Metros · live weather + roads</div>
          </div>
          <div className="dr-stat">
            <div className="dr-stat-num">$0</div>
            <div className="dr-stat-l"><strong>Always free</strong> · for drivers</div>
          </div>
        </div>
      </section>

      {/* Plaque grid — every utility on offer, visible to everyone (anon or
          authed). One flat grid so the menu reads in seconds. */}
      <section className="dr-grid-section">
        <div className="dr-grid-h">
          <span>Everything we offer drivers</span>
          <span className="dr-grid-h-r">{tiles.length} live · all free</span>
        </div>
        <div className="dr-grid">
          {tiles.map((t, i) => (
            <div className="dr-tile" key={i} onClick={t.onClick}
                 style={{ ["--accent"]: t.accent }}>
              <div className="dr-tile-icon">{t.icon}</div>
              <div className="dr-tile-kicker">{t.kicker}</div>
              <h3 className="dr-tile-title">{t.title}</h3>
              <p className="dr-tile-body">{t.body}</p>
              <div className="dr-tile-cta">{t.cta} →</div>
            </div>
          ))}
        </div>
      </section>

      {!isAuthed && (
        <section className="dr-gate" aria-label="Sign in to The Yard">
          <div className="dr-gate-h">Save your work · sign in</div>
          <h2 className="dr-gate-title">
            {gateSent ? "Check your email." : "Sign in to save tips, timers, and renewals."}
          </h2>
          {!gateSent ? (
            <>
              <p className="dr-gate-sub">
                You can use everything above without an account. Sign in if you want
                tips and saved tools tied to your inbox. One email, no password, no upsell.
              </p>
              <form onSubmit={gateSubmit} className="dr-gate-form">
                <input
                  type="email"
                  className="dr-gate-email"
                  placeholder="you@yourcarrier.com (or any inbox)"
                  value={gateEmail}
                  onChange={e => { setGateEmail(e.target.value); setGateErr(null); }}
                  autoComplete="email"
                  required
                />
                <button type="submit" className="dr-gate-btn" disabled={gateBusy || !gateEmail.trim()}>
                  {gateBusy ? "Sending…" : "Send me a link →"}
                </button>
              </form>
              {gateErr && <div className="dr-gate-msg dr-gate-msg-err">{gateErr}</div>}
              <p className="dr-gate-foot">
                Already in once? Same email, we'll email you back in.
                {" · "}<a href="#/methodology" onClick={e => { e.preventDefault(); onNav("methodology"); }}>Trust contract</a>
              </p>
            </>
          ) : (
            <>
              <p className="dr-gate-sub">
                We sent a sign-in link to <strong>{gateEmail}</strong>. Open it on this device
                and you'll drop straight back in. The link's good for an hour.
              </p>
              <div className="dr-gate-msg dr-gate-msg-ok">
                Didn't get it? Check spam, or <a href="#" style={{ borderBottom: "1px solid", textDecoration: "none", color: "inherit" }}
                  onClick={e => { e.preventDefault(); setGateSent(false); }}>send to a different email</a>.
              </div>
            </>
          )}
        </section>
      )}

      <section className="dr-rules">
        <div className="dr-rules-inner">
          <div className="dr-rules-h">
            <span>House rules</span>
            <span style={{ fontSize: 10, letterSpacing: "0.16em" }}>For tips you drop here</span>
          </div>
          <div className="dr-rules-grid">
            <div className="dr-rule">
              <div className="dr-rule-num">01</div>
              <h4 className="dr-rule-h">Sealed by default.</h4>
              <p className="dr-rule-b">Your name's not on it unless you say so. No carrier can pay to bury it.</p>
            </div>
            <div className="dr-rule">
              <div className="dr-rule-num">02</div>
              <h4 className="dr-rule-h">Counted, never quoted.</h4>
              <p className="dr-rule-b">Sealed tips become numbers — waits, scores, patterns. Words stay yours.</p>
            </div>
            <div className="dr-rule">
              <div className="dr-rule-num">03</div>
              <h4 className="dr-rule-h">Delete any time.</h4>
              <p className="dr-rule-b">Sealed gone is gone. Published gets your identity stripped. We don't argue.</p>
            </div>
            <div className="dr-rule">
              <div className="dr-rule-num">04</div>
              <h4 className="dr-rule-h">Yard, not brand.</h4>
              <p className="dr-rule-b">A bad day at one dock doesn't tank a carrier. Intel rolls up at the gate.</p>
            </div>
          </div>
        </div>
      </section>

      <section className="dr-cta-section">
        <div className="dr-cta-row">
          <p className="dr-cta-line">
            Drop a line on the dock you know best. Tell the next driver what they're rolling into.
          </p>
          <button className="dr-cta-btn" onClick={() => onNav("terminals")}>Find your dock →</button>
        </div>
      </section>

      <div style={{ height: 96 }} />
    </div>
  );
}

window.DriversPage = DriversPage;
