// LandAI — Data Store landing page. DC component (x-imported by Canvas-2.dc.html).
// Original LandAI design inspired by a generic data-store layout. React is injected.
(function () {
const { useState, useEffect, useRef } = React;

const INK = "#14171C";
const APP_STORE_URL = "https://apps.apple.com/us/app/landai-property-maps/id6753875511";
const WEB_APP_URL = "https://app.landai.app";
const openUrl = (u) => window.open(u, "_blank", "noopener");
const GREEN_DK = "#14171C";
const GREEN = "#2E6BF0";
const GREEN_DEEP = "#0E1116";
const CORAL = "#2E6BF0";
const CREAM = "#EFEADF";
const MINT = "#E7EDF6";
const GRAY = "#5C6168";
const BORDER = "#E4DFD3";
const PAPER = "#F4F1EA";
const SERIF = "'Newsreader', Georgia, serif";
const W = "min(1440px, 100%)";
const STORE_PAGE_HEIGHT = "max(940px, 100vh)";
const COUNTY_STORE_PRICE = 100;
const STATE_STORE_PRICE_PER_SUPPORTED_COUNTY = 50;
const INCLUDED_EXPORT_FORMATS = ["FileGDB", "Shapefile", "GeoPackage", "GeoJSON", "CSV"];
const INCLUDED_FORMAT_LABEL = "All formats included";
const DATA_STORE_CART_STORAGE_KEY = "landai:data-store-cart:v1";
const formatStoreCurrency = (value) => `$${Number(value || 0).toLocaleString()}`;

function normalizeStoredCartItem(item) {
  if (!item || typeof item !== "object") return null;
  const place = String(item.place || "").trim();
  const product = String(item.product || "").trim();
  const price = Number(item.price);
  if (!place || !product || !Number.isFinite(price) || price < 0) return null;
  return {
    ...item,
    place,
    product,
    price,
    records: String(item.records || ""),
    type: item.type === "state" ? "state" : "county",
  };
}

function readStoredDataStoreCart() {
  if (typeof window === "undefined" || !window.localStorage) return [];
  try {
    const raw = window.localStorage.getItem(DATA_STORE_CART_STORAGE_KEY);
    if (!raw) return [];
    const parsed = JSON.parse(raw);
    if (!Array.isArray(parsed)) return [];
    return parsed.map(normalizeStoredCartItem).filter(Boolean);
  } catch (err) {
    console.warn("[data-store-cart] Could not read stored cart", err);
    return [];
  }
}

function writeStoredDataStoreCart(cart) {
  if (typeof window === "undefined" || !window.localStorage) return;
  try {
    const cleaned = Array.isArray(cart) ? cart.map(normalizeStoredCartItem).filter(Boolean) : [];
    if (!cleaned.length) window.localStorage.removeItem(DATA_STORE_CART_STORAGE_KEY);
    else window.localStorage.setItem(DATA_STORE_CART_STORAGE_KEY, JSON.stringify(cleaned));
  } catch (err) {
    console.warn("[data-store-cart] Could not save cart", err);
  }
}

function MobileStyles() {
  return (
    <style>{`
      @media (max-width: 767px) {
        html, body {
          overflow-x: hidden;
        }

        .landai-page-shell,
        .landai-store-shell {
          width: 100% !important;
          min-height: 100vh !important;
          height: auto !important;
          overflow: visible !important;
          box-shadow: none !important;
        }

        .landai-nav {
          padding: 14px 16px 12px !important;
          flex-wrap: wrap !important;
          align-items: center !important;
          gap: 12px !important;
        }

        .landai-nav-links {
          order: 3 !important;
          width: 100% !important;
          gap: 20px !important;
          overflow-x: auto !important;
          padding: 4px 0 2px !important;
          -webkit-overflow-scrolling: touch !important;
        }

        .landai-nav-actions {
          gap: 10px !important;
          margin-left: auto !important;
        }

        .landai-nav-actions > span {
          font-size: 13px !important;
        }

        .landai-nav-actions > button {
          padding: 9px 14px !important;
          font-size: 13px !important;
        }

        .landai-hero,
        .landai-coverage-section,
        .landai-footer-main,
        .landai-store-split,
        .landai-cart-split,
        .landai-support-split {
          flex-direction: column !important;
        }

        .landai-hero {
          padding: 34px 18px 42px !important;
          gap: 28px !important;
          align-items: stretch !important;
        }

        .landai-hero h1 {
          font-size: 42px !important;
          line-height: 1.04 !important;
        }

        .landai-hero p {
          font-size: 16px !important;
          margin-bottom: 24px !important;
        }

        .landai-hero-actions,
        .landai-state-actions,
        .landai-contact-actions,
        .landai-cart-pay-tabs {
          flex-direction: column !important;
          align-items: stretch !important;
        }

        .landai-hero-actions button,
        .landai-state-actions button,
        .landai-contact-actions button {
          width: 100% !important;
        }

        .landai-county-list-toolbar {
          align-items: stretch !important;
        }

        .landai-county-list-toolbar > div:last-child {
          width: 100% !important;
        }

        .landai-county-list-toolbar label {
          flex: 1 1 150px !important;
          justify-content: space-between !important;
        }

        .landai-county-list-toolbar select {
          min-width: 0 !important;
          flex: 1 !important;
        }

        .landai-hero-art {
          height: 280px !important;
          border-radius: 16px !important;
        }

        .landai-hero-preview-controls {
          top: 12px !important;
          left: 12px !important;
          right: 12px !important;
          gap: 8px !important;
        }

        .landai-hero-preview-search {
          flex-basis: 100% !important;
          max-width: none !important;
          height: 38px !important;
          padding: 0 12px !important;
          font-size: 12px !important;
        }

        .landai-hero-preview-legend {
          padding: 8px 10px !important;
          font-size: 10.5px !important;
        }

        .landai-hero-preview-card {
          left: 12px !important;
          right: 12px !important;
          bottom: 12px !important;
          width: auto !important;
          padding: 12px !important;
          border-radius: 15px !important;
        }

        .landai-hero-preview-formats,
        .landai-hero-preview-field-row {
          display: none !important;
        }

        .landai-section {
          padding: 44px 18px !important;
        }

        .landai-section h2,
        .landai-final-cta h2 {
          font-size: 30px !important;
          line-height: 1.15 !important;
        }

        .landai-grid-3 {
          grid-template-columns: 1fr !important;
          gap: 26px !important;
        }

        .landai-step-card {
          align-items: flex-start !important;
          gap: 18px !important;
          padding: 20px !important;
        }

        .landai-contact-card {
          padding: 22px !important;
          border-radius: 14px !important;
        }

        .landai-footer {
          padding: 42px 18px 28px !important;
        }

        .landai-footer-main {
          gap: 32px !important;
        }

        .landai-footer-bottom {
          align-items: flex-start !important;
          flex-direction: column !important;
          gap: 10px !important;
        }

        .landai-store-split,
        .landai-cart-split,
        .landai-support-split {
          height: auto !important;
          min-height: 0 !important;
          overflow: visible !important;
        }

        .landai-store-left,
        .landai-cart-left,
        .landai-support-content {
          width: 100% !important;
          height: auto !important;
          overflow: visible !important;
          padding: 26px 18px 42px !important;
          box-sizing: border-box !important;
        }

        .landai-store-map {
          order: -1 !important;
          width: 100% !important;
          flex: none !important;
          height: 58vh !important;
          min-height: 420px !important;
          max-height: 620px !important;
        }

        .landai-store-left h1 {
          font-size: 31px !important;
          line-height: 1.06 !important;
        }

        .landai-stat-strip {
          display: grid !important;
          grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
          border-radius: 10px !important;
        }

        .landai-stat-strip > div {
          min-height: 96px !important;
        }

        .landai-doc-buttons,
        .landai-state-list {
          display: flex !important;
          flex-direction: column !important;
          columns: auto !important;
          gap: 10px !important;
        }

        .landai-map-controls {
          top: 12px !important;
          left: 12px !important;
          right: 12px !important;
          gap: 10px !important;
          align-items: flex-start !important;
          flex-wrap: wrap !important;
        }

        .landai-map-search {
          max-width: none !important;
          min-width: 0 !important;
        }

        .landai-map-legend {
          max-width: calc(100vw - 24px) !important;
          font-size: 11.5px !important;
          background: #fff !important;
          border-radius: 10px !important;
          padding: 9px 12px !important;
          box-shadow: 0 6px 20px rgba(16,40,30,0.15) !important;
        }

        .landai-state-stats,
        .landai-county-stats {
          grid-template-columns: 1fr !important;
          gap: 14px !important;
        }

        .landai-state-map,
        .landai-county-map {
          width: 100% !important;
          flex: none !important;
          height: 48vh !important;
          min-height: 360px !important;
          order: -1 !important;
        }

        .landai-product-card,
        .landai-delivery-card {
          padding: 20px !important;
          border-radius: 14px !important;
        }

        .landai-schema-option span + div span:last-child {
          display: block !important;
          margin-left: 0 !important;
          margin-top: 4px !important;
        }

        .landai-field-columns,
        .landai-other-counties {
          columns: auto !important;
        }

        .landai-county-row {
          align-items: flex-start !important;
          gap: 10px !important;
        }

        .landai-county-row-actions {
          flex-direction: column !important;
          gap: 8px !important;
        }

        .landai-support-sidebar {
          width: 100% !important;
          border-right: none !important;
          border-bottom: 1px solid ${BORDER} !important;
          padding: 24px 18px !important;
        }

        .landai-support-tabs {
          flex-direction: row !important;
          overflow-x: auto !important;
          padding-bottom: 2px !important;
        }

        .landai-support-tabs > div {
          white-space: nowrap !important;
          flex-shrink: 0 !important;
        }

        .landai-doc-table,
        .landai-coverage-table,
        .landai-cart-table {
          overflow-x: auto !important;
          -webkit-overflow-scrolling: touch !important;
        }

        .landai-doc-table > div,
        .landai-coverage-table > div,
        .landai-cart-table > div {
          min-width: 720px !important;
        }

        .landai-coverage-page {
          padding: 26px 18px 44px !important;
        }

        .landai-cart-right {
          flex: none !important;
          width: 100% !important;
          padding: 30px 18px 42px !important;
          border-left: none !important;
          border-top: 1px solid ${BORDER} !important;
          box-sizing: border-box !important;
        }
      }
    `}</style>
  );
}

// ---------- shared bits ----------
function Logo({ light }) {
  const c = light ? "#F1ECDD" : INK;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
      <div style={{ width: 34, height: 34, borderRadius: 9.5, background: "#fff", border: `1px solid ${BORDER}`, display: "flex", alignItems: "center", justifyContent: "center" }}>
        <svg width="20" height="20" viewBox="0 0 36 36">
          <path d="M18 5 L31 12 L18 19 L5 12 Z" fill="#2E7D5B" />
          <path d="M5 18 L18 25 L31 18" fill="none" stroke="#2E7D5B" strokeWidth="2.4" strokeLinejoin="round" />
          <path d="M5 24 L18 31 L31 24" fill="none" stroke="#9bbfae" strokeWidth="2.4" strokeLinejoin="round" />
        </svg>
      </div>
      <span style={{ fontSize: 22, fontWeight: 700, color: c, letterSpacing: -0.4 }}>LandAI</span>
    </div>
  );
}

function StepIcon({ kind }) {
  const common = { fill: "none", stroke: "#F1ECDD", strokeWidth: 2.2, strokeLinecap: "round", strokeLinejoin: "round" };
  const panel = { fill: "#20242C", stroke: "rgba(241,236,221,0.12)", strokeWidth: 1.2 };
  const inner = {
    geo: (
      <g>
        <rect x="10" y="12" width="44" height="40" rx="8" {...panel} />
        <path d="M16 40l10-4 12 4 10-4" {...common} />
        <path d="M16 25l10-4 12 4 10-4v21l-10 4-12-4-10 4V25z" {...common} />
        <path d="M26 21v21M38 25v21" {...common} opacity="0.75" />
        <circle cx="39" cy="19" r="7" fill={GREEN} />
        <circle cx="39" cy="19" r="2.4" fill="#fff" />
        <path d="M25 31h9" stroke="#7FB0FF" strokeWidth="2.2" strokeLinecap="round" />
      </g>
    ),
    options: (
      <g>
        <rect x="11" y="12" width="42" height="40" rx="8" {...panel} />
        <rect x="17" y="19" width="30" height="6" rx="3" fill="#F1ECDD" opacity="0.94" />
        <rect x="17" y="29" width="30" height="6" rx="3" fill="#F1ECDD" opacity="0.6" />
        <rect x="17" y="39" width="30" height="6" rx="3" fill="#F1ECDD" opacity="0.34" />
        <path d="M42 20l4-4M45 20l2-2" stroke="#7FB0FF" strokeWidth="2" strokeLinecap="round" />
        <path d="M22 49l7 5 13-14" fill="none" stroke={GREEN} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
      </g>
    ),
    addons: (
      <g>
        <rect x="10" y="12" width="44" height="40" rx="8" {...panel} />
        <path d="M20 23h24M20 33h24M20 43h24" {...common} opacity="0.75" />
        <circle cx="27" cy="23" r="4.4" fill="#7FB0FF" />
        <circle cx="39" cy="33" r="4.4" fill="#F1ECDD" />
        <circle cx="25" cy="43" r="4.4" fill={GREEN} />
        <path d="M16 52h32" stroke="rgba(241,236,221,0.35)" strokeWidth="2" strokeLinecap="round" />
      </g>
    ),
    checkout: (
      <g>
        <rect x="10" y="12" width="44" height="40" rx="8" {...panel} />
        <rect x="17" y="20" width="30" height="20" rx="3" {...common} />
        <path d="M17 26h30" {...common} opacity="0.7" />
        <path d="M28 47h8M32 40v7" {...common} />
        <path d="M32 30v7M32 37l-4-4M32 37l4-4" stroke="#7FB0FF" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
        <circle cx="44" cy="18" r="3" fill={GREEN} />
      </g>
    ),
  }[kind];
  return (
    <div style={{ width: 92, height: 92, borderRadius: 18, background: "linear-gradient(145deg,#10141A,#172538)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.06)" }}>
      <svg width="64" height="64" viewBox="0 0 64 64">{inner}</svg>
    </div>
  );
}

// hero data-store preview
function ParcelMap() {
  const supported = "#34C759";
  const noData = "#FFB454";
  const countyTiles = Array.from({ length: 104 }, (_, i) => {
    const col = i % 13;
    const row = Math.floor(i / 13);
    const offline = [4, 9, 16, 22, 29, 35, 47, 58, 63, 71, 82, 94, 100].includes(i);
    return { x: 44 + col * 32, y: 92 + row * 27, offline };
  });
  const fieldRows = [["owner", 99], ["address", 97], ["sale date", 71]];

  return (
    <>
      <svg viewBox="0 0 720 440" preserveAspectRatio="xMidYMid slice" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
        <defs>
          <linearGradient id="ds-hero-water" x1="0" x2="1" y1="0" y2="1">
            <stop offset="0" stopColor="#f7faf8" />
            <stop offset="1" stopColor="#d8e4e2" />
          </linearGradient>
          <radialGradient id="ds-hero-glow" cx="62%" cy="42%" r="62%">
            <stop offset="0" stopColor="#ffffff" stopOpacity="0.92" />
            <stop offset="1" stopColor="#ffffff" stopOpacity="0" />
          </radialGradient>
          <filter id="ds-hero-shadow" x="-20%" y="-20%" width="140%" height="140%">
            <feDropShadow dx="0" dy="18" stdDeviation="18" floodColor="#10281E" floodOpacity="0.18" />
          </filter>
        </defs>
        <rect width="720" height="440" fill="url(#ds-hero-water)" />
        <rect width="720" height="440" fill="url(#ds-hero-glow)" />
        <path d="M-20 330 C95 250 170 280 276 214 C396 140 509 150 744 88 L744 440 L-20 440 Z" fill="#c8d9ce" />
        <path d="M-26 346 C96 265 174 292 282 226 C400 154 512 164 744 104" fill="none" stroke="#2c8f67" strokeWidth="4" opacity="0.42" />
        <path d="M498 42 C560 72 612 56 746 85" fill="none" stroke="#b8c7c3" strokeWidth="34" opacity="0.36" />

        <g transform="rotate(-4 238 194)" stroke="#2c8f67" strokeWidth="1" opacity="0.96">
          {countyTiles.map((tile, i) => (
            <rect key={i} x={tile.x} y={tile.y} width="31" height="26" rx="2" fill={tile.offline ? noData : supported} opacity={tile.offline ? 0.72 : 0.78} />
          ))}
        </g>

        <path d="M282 156 L366 150 L414 180 L402 252 L328 282 L258 248 L248 188 Z" fill="#5fd784" stroke="#0969ff" strokeWidth="4" opacity="0.9" filter="url(#ds-hero-shadow)" />
        <path d="M282 156 L366 150 L414 180 L402 252 L328 282 L258 248 L248 188 Z" fill="none" stroke="#fff" strokeWidth="1.6" opacity="0.82" />
        <circle cx="334" cy="214" r="9" fill="#0969ff" stroke="#fff" strokeWidth="4" />
        <text x="334" y="305" textAnchor="middle" fill="#21302c" fontSize="16" fontWeight="800" fontFamily="Hanken Grotesk, system-ui">Guilford County</text>
        <text x="494" y="256" fill="#73847f" fontSize="58" fontWeight="800" letterSpacing="7" opacity="0.17" fontFamily="Hanken Grotesk, system-ui">NC</text>
      </svg>

      <div className="landai-hero-preview-controls" style={{ position: "absolute", top: 20, left: 20, right: 20, display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
        <div className="landai-hero-preview-search" style={{ flex: "1 1 250px", maxWidth: 312, height: 48, borderRadius: 14, background: "#fff", boxShadow: "0 16px 36px rgba(16,40,30,0.13)", display: "flex", alignItems: "center", gap: 10, padding: "0 16px", color: INK, fontSize: 14, fontWeight: 800 }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#8A9A96" strokeWidth="2.5" strokeLinecap="round"><circle cx="11" cy="11" r="6" /><path d="M16 16l4 4" /></svg>
          Search any county
        </div>
        <div className="landai-hero-preview-legend" style={{ background: "#fff", borderRadius: 14, padding: "11px 13px", boxShadow: "0 16px 36px rgba(16,40,30,0.13)", display: "flex", gap: 12, alignItems: "center", fontSize: 11.5, fontWeight: 800, color: INK }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 9, height: 9, borderRadius: 3, background: supported }} />Available</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 9, height: 9, borderRadius: 3, background: noData }} />No data</span>
        </div>
      </div>

      <div className="landai-hero-preview-card" style={{ position: "absolute", right: 22, bottom: 22, width: 238, background: "#fff", borderRadius: 20, padding: 17, boxShadow: "0 24px 55px rgba(16,40,30,0.22)", border: "1px solid rgba(16,40,30,0.08)" }}>
        <div style={{ fontSize: 15, fontWeight: 900, color: INK }}>Guilford County, NC</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginTop: 13 }}>
          <div>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 18, fontWeight: 900, color: INK }}>222K+</div>
            <div style={{ fontSize: 11, color: GRAY, fontWeight: 800 }}>Parcels</div>
          </div>
          <div>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 18, fontWeight: 900, color: INK }}>6/24</div>
            <div style={{ fontSize: 11, color: GRAY, fontWeight: 800 }}>Data date</div>
          </div>
        </div>
        <div style={{ height: 1, background: "#e9eee9", margin: "14px 0 12px" }} />
        {fieldRows.map(([label, pct]) => (
          <div key={label} className="landai-hero-preview-field-row" style={{ marginTop: 9 }}>
            <div style={{ display: "flex", justifyContent: "space-between", gap: 10, fontSize: 11.5, fontWeight: 900, color: INK, textTransform: "uppercase" }}>
              <span>{label}</span><span style={{ color: "#1C7A5B" }}>{pct}%</span>
            </div>
            <div style={{ height: 7, borderRadius: 999, background: "#e8eee9", overflow: "hidden", marginTop: 5 }}>
              <div style={{ width: `${pct}%`, height: "100%", borderRadius: 999, background: pct > 90 ? supported : GREEN }} />
            </div>
          </div>
        ))}
        <button style={{ width: "100%", border: "none", borderRadius: 12, background: INK, color: "#fff", fontSize: 13, fontWeight: 900, padding: "12px 0", marginTop: 15, fontFamily: "inherit" }}>Add county to cart</button>
      </div>

      <div className="landai-hero-preview-formats" style={{ position: "absolute", left: 20, bottom: 22, display: "flex", gap: 9, flexWrap: "wrap", maxWidth: 278 }}>
        {["FileGDB", "Shapefile", "GeoJSON", "CSV"].map((label) => (
          <span key={label} style={{ padding: "8px 10px", borderRadius: 999, background: "rgba(255,255,255,0.88)", border: "1px solid rgba(16,40,30,0.08)", color: INK, fontSize: 11.5, fontWeight: 900, boxShadow: "0 10px 24px rgba(16,40,30,0.10)" }}>{label}</span>
        ))}
      </div>
    </>
  );
}

// ---------- sections ----------
function Nav({ onHome, onBrowse }) {
  const openStoreLanding = onHome || (() => window.__landaiNav ? window.__landaiNav("store") : (location.href = "/data-store"));
  const links = [["Mobile App", () => window.__landaiNav ? window.__landaiNav("mobile") : (location.href = "/")], ["Data Store", openStoreLanding], ["About", () => window.__landaiNav ? window.__landaiNav("about") : (location.href = "/about")], ["Contact Us", () => window.__landaiNav ? window.__landaiNav("contact") : (location.href = "/contact")]];
  const navItemStyle = (active) => ({
    display: "inline-flex",
    alignItems: "center",
    gap: 7,
    fontSize: 15,
    fontWeight: active ? 700 : 500,
    color: INK,
    cursor: "pointer",
    opacity: active ? 1 : 0.72,
    padding: "7px 11px",
    borderRadius: 999,
    background: active ? "#fff" : "transparent",
    border: active ? `1px solid ${BORDER}` : "1px solid transparent",
    boxShadow: active ? "0 8px 18px rgba(16,40,30,0.06)" : "none"
  });
  const activeDot = <span style={{ width: 7, height: 7, borderRadius: 99, background: GREEN, flexShrink: 0 }} />;
  return (
    <div className="landai-nav" style={{ position: "relative", zIndex: 5, display: "flex", alignItems: "center", justifyContent: "space-between", padding: "22px 48px", background: PAPER, borderBottom: `1px solid ${BORDER}` }}>
      <div onClick={openStoreLanding} style={{ cursor: "pointer" }}><Logo /></div>
      <div className="landai-nav-links" style={{ display: "flex", gap: 34 }}>
        {links.map(([l, fn], i) => (
          <span key={i} onClick={fn} style={navItemStyle(l === "Data Store")}>{l === "Data Store" && activeDot}{l}</span>
        ))}
      </div>
      <div className="landai-nav-actions" style={{ display: "flex", gap: 18, alignItems: "center" }}>
        <span onClick={() => openUrl(WEB_APP_URL)} style={{ fontSize: 15, fontWeight: 500, color: INK, cursor: "pointer" }}>Web app</span>
        <button onClick={() => window.__landaiGetApp && window.__landaiGetApp()} style={{ border: "none", background: INK, color: "#fff", fontSize: 14, fontWeight: 600, padding: "11px 22px", borderRadius: 99, cursor: "pointer", fontFamily: "inherit" }}>Get the app</button>
      </div>
    </div>
  );
}

function Hero({ onBrowse }) {
  return (
    <div className="landai-hero" style={{ background: PAPER, padding: "76px 48px 86px", display: "flex", gap: 56, alignItems: "center" }}>
      <div style={{ flex: 1 }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 8, background: "#fff", border: `1px solid ${BORDER}`, borderRadius: 99, padding: "6px 14px", fontSize: 12.5, fontWeight: 600, color: GRAY, letterSpacing: 0.3 }}>
          <span style={{ width: 7, height: 7, borderRadius: 99, background: GREEN }} />
          LandAI Data Store
        </span>
        <h1 style={{ fontSize: 62, lineHeight: 1.02, color: INK, letterSpacing: -1.4, margin: "22px 0 0" }}>
          Parcel data by the<br />county, <span style={{ fontStyle: "italic", color: GREEN }}>not the contract.</span>
        </h1>
        <p style={{ fontSize: 19, lineHeight: 1.55, color: GRAY, maxWidth: 500, margin: "24px 0 36px" }}>
          Buy parcel data for exactly the area you're working — one county or a whole state. Pick your area, review coverage, and download every file format. No sales calls, no waiting.
        </p>
        <div className="landai-hero-actions" style={{ display: "flex", gap: 14, alignItems: "center" }}>
          <button onClick={onBrowse} style={{ border: "none", background: INK, color: "#fff", fontSize: 16, fontWeight: 600, padding: "16px 30px", borderRadius: 99, cursor: "pointer", fontFamily: "inherit" }}>
            Browse &amp; purchase data
          </button>
          <button onClick={onBrowse} style={{ border: `1.5px solid ${INK}`, background: "transparent", color: INK, fontSize: 16, fontWeight: 600, padding: "15px 28px", borderRadius: 99, cursor: "pointer", fontFamily: "inherit" }}>
            View coverage
          </button>
        </div>
      </div>
      <div className="landai-hero-art" style={{ flex: 1, height: 440, borderRadius: 24, overflow: "hidden", position: "relative", boxShadow: "0 30px 70px rgba(16,40,30,0.18)" }}>
        <ParcelMap />
      </div>
    </div>
  );
}

function ValueBand() {
  const cards = [
    ["Buy exactly the area you need", "One county or a whole state — get parcel data for the geography you're working, and nothing you're not.", "desktop"],
    ["See the price before you buy", "Every county is priced up front. No quotes, no negotiation, no surprises at checkout.", "phone"],
    ["Formats that drop into your tools", "Download as FileGDB, Shapefile, GeoPackage, GeoJSON, or CSV — ready for GIS, a spreadsheet, or your own app.", "bulk"],
  ];
  return (
    <div className="landai-section" style={{ background: PAPER, padding: "72px 48px 80px" }}>
      <h2 style={{ textAlign: "center", fontSize: 38, color: INK, letterSpacing: -0.6, maxWidth: 760, margin: "0 auto 52px", lineHeight: 1.18 }}>
        Skip the sales process. Pick an area, see the price, and download parcel data that's ready to work.
      </h2>
      <div className="landai-grid-3" style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 28, maxWidth: 1180, margin: "0 auto" }}>
        {cards.map(([t, d, kind], i) => (
          <div key={i} style={{ display: "flex", flexDirection: "column" }}>
            <div style={{ height: 200, borderRadius: 18, background: CREAM, border: `1px solid ${BORDER}`, display: "flex", alignItems: "center", justifyContent: "center", overflow: "hidden", marginBottom: 22 }}>
              <MockArt kind={kind} />
            </div>
            <div style={{ fontSize: 22, color: INK, letterSpacing: -0.3, fontFamily: SERIF }}>{t}</div>
            <div style={{ fontSize: 15, color: GRAY, lineHeight: 1.5, marginTop: 8 }}>{d}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function MockArt({ kind }) {
  if (kind === "desktop") return (
    <svg width="220" height="160" viewBox="0 0 220 160">
      <rect x="34" y="20" width="152" height="98" rx="6" fill="#fff" stroke="#c2d2c9" />
      <rect x="34" y="20" width="152" height="16" rx="6" fill="#eef3f0" />
      <rect x="44" y="46" width="60" height="64" rx="3" fill="#f3f6f4" stroke="#dce6e0" />
      <rect x="110" y="46" width="68" height="64" rx="3" fill="#e7efe9" />
      <path d="M118 96 l14-12 12 8 16-16" stroke={GREEN} strokeWidth="2" fill="none" />
      <circle cx="160" cy="68" r="5" fill={CORAL} />
      <rect x="96" y="120" width="28" height="26" fill="#cdd9d2" />
      <rect x="78" y="146" width="64" height="6" rx="3" fill="#cdd9d2" />
    </svg>
  );
  if (kind === "phone") return (
    <svg width="120" height="170" viewBox="0 0 120 170">
      <rect x="30" y="12" width="60" height="146" rx="12" fill="#16221d" />
      <rect x="34" y="16" width="52" height="138" rx="9" fill="#fff" />
      <rect x="40" y="28" width="40" height="8" rx="4" fill="#dce6e0" />
      <rect x="40" y="44" width="40" height="40" rx="4" fill="#e7efe9" />
      <path d="M46 70 l8-7 7 5 9-9" stroke={GREEN} strokeWidth="1.6" fill="none" />
      <rect x="40" y="92" width="40" height="9" rx="4" fill={GREEN_DK} />
      <rect x="40" y="106" width="28" height="6" rx="3" fill="#dce6e0" />
      <rect x="40" y="118" width="34" height="6" rx="3" fill="#dce6e0" />
    </svg>
  );
  return (
    <svg width="200" height="150" viewBox="0 0 200 150">
      <rect x="40" y="22" width="120" height="106" rx="8" fill="#fff" stroke="#c2d2c9" />
      <rect x="56" y="38" width="60" height="9" rx="4" fill={GREEN_DK} />
      {[0,1,2,3].map(i => (
        <g key={i}>
          <rect x="56" y={58 + i*16} width="74" height="8" rx="4" fill="#e2ebe5" />
          <rect x="136" y={57 + i*16} width="10" height="10" rx="2" fill={i<2?GREEN:"#dce6e0"} />
        </g>
      ))}
    </svg>
  );
}

function HowItWorks() {
  const steps = [
    ["Step 1", "Find your area", "Search or tap the map to pick the county or state you're working in.", "geo"],
    ["Step 2", "Get every format", "Each county includes FileGDB, Shapefile, GeoPackage, GeoJSON, and CSV.", "options"],
    ["Step 3", "Review coverage", "Confirm parcel counts, data date, and field completeness before you buy.", "addons"],
    ["Step 4", "Check out and download", "Pay online and your data's ready to go — straight into mapping, outreach, or analysis.", "checkout"],
  ];
  return (
    <div className="landai-section" style={{ background: PAPER, padding: "72px 48px 88px", borderTop: `1px solid ${BORDER}` }}>
      <div style={{ textAlign: "center", fontStyle: "italic", color: GREEN, fontSize: 16, marginBottom: 10, fontFamily: SERIF }}>How it works</div>
      <h2 style={{ textAlign: "center", fontSize: 40, color: INK, letterSpacing: -0.8, margin: 0 }}>Pick an area. Choose your data. Download.</h2>
      <div style={{ textAlign: "center", fontSize: 17, color: GRAY, marginTop: 12, marginBottom: 56 }}>Self-serve from search to download — usually under a minute.</div>
      <div style={{ maxWidth: 760, margin: "0 auto", display: "flex", flexDirection: "column", gap: 30 }}>
        {steps.map(([s, t, d, icon], i) => (
          <div key={i} className="landai-step-card" style={{ display: "flex", gap: 28, alignItems: "center", background: "#fff", border: `1px solid ${BORDER}`, borderRadius: 20, padding: 24 }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 12, letterSpacing: 1.5, color: GREEN, fontWeight: 600 }}>{s.toUpperCase()}</div>
              <div style={{ fontSize: 23, color: INK, letterSpacing: -0.4, margin: "6px 0 8px", fontFamily: SERIF }}>{t}</div>
              <div style={{ fontSize: 16, color: GRAY, lineHeight: 1.5, maxWidth: 480 }}>{d}</div>
            </div>
            <StepIcon kind={icon} />
          </div>
        ))}
      </div>
    </div>
  );
}

function CoveragePreviewGraphic() {
  const fieldRows = [
    ["Owner", 99],
    ["Site address", 97],
    ["Sale date", 71],
  ];
  const countyTiles = Array.from({ length: 66 }, (_, i) => {
    const col = i % 11;
    const row = Math.floor(i / 11);
    const supported = ![3, 8, 14, 21, 29, 36, 44, 51, 57, 63].includes(i);
    return { x: 38 + col * 20, y: 44 + row * 20, supported };
  });

  return (
    <div style={{ flex: 1, position: "relative", height: 330, borderRadius: 24, background: "#dfe7e7", overflow: "hidden", boxShadow: "0 30px 70px rgba(16,40,30,0.18)", border: "1px solid rgba(16,40,30,0.10)" }}>
      <svg viewBox="0 0 560 330" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
        <defs>
          <linearGradient id="coverageWater" x1="0" x2="1" y1="0" y2="1">
            <stop offset="0" stopColor="#edf4f5" />
            <stop offset="1" stopColor="#cfdadb" />
          </linearGradient>
          <filter id="coverageShadow" x="-20%" y="-20%" width="140%" height="140%">
            <feDropShadow dx="0" dy="14" stdDeviation="16" floodColor="#10281E" floodOpacity="0.22" />
          </filter>
        </defs>
        <rect width="560" height="330" fill="url(#coverageWater)" />
        <path d="M-30 244 C68 195 132 219 217 178 C318 130 418 142 590 96 L590 330 L-30 330 Z" fill="#c5d4c9" opacity="0.95" />
        <path d="M-20 259 C73 209 137 233 224 191 C322 146 421 153 582 112" fill="none" stroke="#2c8f67" strokeWidth="3" opacity="0.55" />

        <g transform="rotate(-3 160 100)" stroke="#2c8f67" strokeWidth="1" opacity="0.95">
          {countyTiles.map((tile, i) => (
            <rect key={i} x={tile.x} y={tile.y} width="19" height="19" fill={tile.supported ? "#78D796" : "#FFC66D"} opacity={tile.supported ? 0.82 : 0.78} />
          ))}
        </g>

        <path d="M168 98 L232 93 L265 118 L255 171 L198 188 L146 163 L137 122 Z" fill="#52C77A" stroke="#0969ff" strokeWidth="3" opacity="0.88" filter="url(#coverageShadow)" />
        <path d="M168 98 L232 93 L265 118 L255 171 L198 188 L146 163 L137 122 Z" fill="none" stroke="#fff" strokeWidth="1.2" opacity="0.65" />
        <circle cx="202" cy="139" r="7" fill="#0969ff" stroke="#fff" strokeWidth="3" />
        <text x="202" y="206" textAnchor="middle" fill="#1D2B28" fontSize="14" fontWeight="800" fontFamily="Hanken Grotesk, system-ui">Guilford County</text>
        <text x="84" y="68" fill="#78908B" fontSize="22" fontWeight="800" letterSpacing="5" opacity="0.55" fontFamily="Hanken Grotesk, system-ui">COVERAGE MAP</text>
      </svg>

      <div style={{ position: "absolute", top: 20, left: 22, right: 22, display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
        <div style={{ flex: 1, maxWidth: 292, height: 42, borderRadius: 12, background: "#fff", boxShadow: "0 12px 32px rgba(16,40,30,0.13)", display: "flex", alignItems: "center", gap: 10, padding: "0 14px", fontSize: 13, color: INK, fontWeight: 700 }}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#8A9A96" strokeWidth="2.4" strokeLinecap="round"><circle cx="11" cy="11" r="6" /><path d="M16 16l4 4" /></svg>
          Guilford County, NC
        </div>
        <div style={{ background: "#fff", borderRadius: 12, boxShadow: "0 12px 32px rgba(16,40,30,0.13)", padding: "10px 12px", display: "flex", gap: 12, alignItems: "center", fontSize: 11.5, fontWeight: 800, color: INK }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 9, height: 9, borderRadius: 2, background: "#34C759" }} />Live</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 9, height: 9, borderRadius: 2, background: "#FF9500" }} />No data</span>
        </div>
      </div>

      <div style={{ position: "absolute", right: 22, top: 86, width: 194, background: "#fff", borderRadius: 18, padding: 16, boxShadow: "0 22px 45px rgba(16,40,30,0.18)", border: "1px solid rgba(16,40,30,0.08)" }}>
        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: GREEN, letterSpacing: 1.2, fontWeight: 800, textTransform: "uppercase" }}>County coverage</div>
        <div style={{ fontSize: 20, fontWeight: 800, color: INK, marginTop: 8, lineHeight: 1 }}>222,643</div>
        <div style={{ fontSize: 11, fontWeight: 700, color: GRAY, marginTop: 2 }}>Parcels</div>
        <div style={{ height: 1, background: "#e9eee9", margin: "13px 0" }} />
        <div style={{ display: "grid", gridTemplateColumns: "1fr auto", rowGap: 8, columnGap: 10 }}>
          {fieldRows.map(([label, pct]) => (
            <React.Fragment key={label}>
              <div style={{ fontSize: 11.5, fontWeight: 800, color: INK }}>{label}</div>
              <div style={{ fontSize: 11.5, fontFamily: "'JetBrains Mono', monospace", color: GREEN_DK, fontWeight: 800 }}>{pct}%</div>
              <div style={{ gridColumn: "1 / -1", height: 7, borderRadius: 999, background: "#e8eee9", overflow: "hidden", marginTop: -4 }}>
                <div style={{ width: `${pct}%`, height: "100%", borderRadius: 999, background: pct > 90 ? "#34C759" : "#2E6BF0" }} />
              </div>
            </React.Fragment>
          ))}
        </div>
      </div>

      <div style={{ position: "absolute", left: 22, right: 22, bottom: 18, display: "flex", gap: 10, flexWrap: "wrap" }}>
        {["Data date 6/24/2026", "48 fields", "Ready to buy"].map((label, i) => (
          <div key={label} style={{ padding: "8px 11px", borderRadius: 999, background: i === 2 ? INK : "rgba(255,255,255,0.86)", color: i === 2 ? "#fff" : INK, fontSize: 11.5, fontWeight: 800, boxShadow: "0 10px 24px rgba(16,40,30,0.10)" }}>{label}</div>
        ))}
      </div>
    </div>
  );
}

function Coverage({ onBrowse }) {
  return (
    <div className="landai-section" style={{ background: CREAM, padding: "76px 48px" }}>
      <div className="landai-coverage-section" style={{ maxWidth: 1140, margin: "0 auto", display: "flex", gap: 56, alignItems: "center" }}>
        <div style={{ flex: 1 }}>
          <h2 style={{ fontSize: 38, color: INK, letterSpacing: -0.6, margin: 0 }}>Check coverage before you buy</h2>
          <p style={{ fontSize: 16, color: GRAY, lineHeight: 1.55, margin: "16px 0 28px", maxWidth: 420 }}>
            See what's live, when it was last refreshed, and how complete each field is. Tap any county for parcel counts and field-by-field coverage, then buy it or open it in the app.
          </p>
          <button onClick={onBrowse} style={{ border: "none", background: INK, color: "#fff", fontSize: 16, fontWeight: 600, padding: "15px 28px", borderRadius: 99, cursor: "pointer", fontFamily: "inherit" }}>View coverage</button>
        </div>
        <CoveragePreviewGraphic />
      </div>
    </div>
  );
}

function Difference() {
  const items = [
    ["2,170+ supported counties", "136M+ parcel records live today, with county-level counts before you buy.", "map"],
    ["One clean schema", "The same standardized fields in every supported county, so your pipeline never breaks.", "layers"],
    ["Refreshed and ready", "We pull from thousands of county sources and standardize them, so you skip the cleanup.", "list"],
  ];
  const ico = (k) => {
    const c = { fill: "none", stroke: GREEN_DK, strokeWidth: 2.2, strokeLinecap: "round", strokeLinejoin: "round" };
    if (k === "map") return <g {...c}><path d="M9 7l8-3 10 4 8-3v22l-8 3-10-4-8 3V7z" /><path d="M17 4v22M27 8v22" /></g>;
    if (k === "layers") return <g {...c}><path d="M18 4l14 7-14 7L4 11l14-7z" /><path d="M4 18l14 7 14-7M4 25l14 7 14-7" /></g>;
    return <g {...c}><path d="M11 9h20M11 18h20M11 27h20" /><circle cx="5" cy="9" r="2" fill={CORAL} stroke="none" /><circle cx="5" cy="18" r="2" fill={GREEN_DK} stroke="none" /><circle cx="5" cy="27" r="2" fill={GREEN_DK} stroke="none" /></g>;
  };
  return (
    <div className="landai-section" style={{ background: PAPER, padding: "76px 48px", borderTop: `1px solid ${BORDER}` }}>
      <h2 style={{ textAlign: "center", fontSize: 34, color: INK, letterSpacing: -0.5, margin: "0 0 52px" }}>Why buy from LandAI</h2>
      <div className="landai-grid-3" style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 40, maxWidth: 1040, margin: "0 auto" }}>
        {items.map(([t, d, k], i) => (
          <div key={i} style={{ textAlign: "center" }}>
            <div style={{ width: 56, height: 56, margin: "0 auto 18px", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <svg width="44" height="44" viewBox="0 0 36 36">{ico(k)}</svg>
            </div>
            <div style={{ fontSize: 21, color: INK, fontFamily: SERIF }}>{t}</div>
            <div style={{ fontSize: 15, color: GRAY, lineHeight: 1.5, marginTop: 8, maxWidth: 280, marginInline: "auto" }}>{d}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ContactForm() {
  const [inquiry, setInquiry] = useState("sales");
  const [form, setForm] = useState({ name: "", email: "", phone: "", organization: "", title: "", subject: "", message: "", website: "" });
  const [status, setStatus] = useState("idle");
  const [error, setError] = useState("");
  const setField = (key) => (event) => {
    const value = event.target.value;
    setForm(current => ({ ...current, [key]: value }));
    setError("");
  };
  const validEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim());
  const canSubmit = form.name.trim() && validEmail && form.message.trim() && status !== "sending";
  const inputStyle = {
    width: "100%",
    border: `1.5px solid ${BORDER}`,
    borderRadius: 10,
    background: "#fbfcfb",
    color: INK,
    fontSize: 15,
    fontFamily: "inherit",
    outline: "none",
    boxSizing: "border-box",
  };
  const field = (key, label, req, tall, type = "text") => (
    <div style={{ marginBottom: 18 }}>
      <div style={{ fontSize: 13, fontWeight: 700, color: INK, marginBottom: 7 }}>{label}{req && <span style={{ color: CORAL }}> *</span>}</div>
      {tall ? (
        <textarea value={form[key]} onChange={setField(key)} rows={5} required={req} style={{ ...inputStyle, minHeight: 112, padding: "13px 15px", resize: "vertical" }} />
      ) : (
        <input value={form[key]} onChange={setField(key)} type={type} required={req} style={{ ...inputStyle, height: 48, padding: "0 15px" }} />
      )}
    </div>
  );
  const submit = async (event) => {
    event.preventDefault();
    if (!canSubmit) {
      setError(validEmail ? "Please fill out the required fields." : "Please enter a valid email address.");
      return;
    }
    setStatus("sending");
    setError("");
    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          source: "data-store-landing",
          inquiry,
          name: form.name,
          email: form.email,
          phone: form.phone,
          company: form.organization,
          title: form.title,
          subject: form.subject || "Data Store inquiry",
          message: form.message,
          page: window.location.href,
          website: form.website,
        }),
      });
      const contentType = response.headers.get("content-type") || "";
      if (!contentType.includes("application/json")) {
        throw new Error("Email endpoint is not available on this local server.");
      }
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) throw new Error(payload.error || "Message could not be sent.");
      setStatus("sent");
    } catch (err) {
      setStatus("idle");
      setError(`${err.message || "Message could not be sent."} You can also email john@landai.app directly.`);
    }
  };
  return (
    <div className="landai-section" style={{ background: PAPER, padding: "20px 48px 84px" }}>
      <div style={{ width: 60, height: 1, background: BORDER, margin: "0 auto 48px" }} />
      <h2 style={{ textAlign: "center", fontSize: 34, color: INK, letterSpacing: -0.5, margin: "0 0 12px" }}>Not sure what you need? Ask before you buy.</h2>
      <p style={{ textAlign: "center", fontSize: 16, color: GRAY, maxWidth: 560, margin: "0 auto 40px", lineHeight: 1.5 }}>Tell us what you're working on and we'll point you to the right county, format, or plan.</p>
      <form onSubmit={submit} className="landai-contact-card" style={{ maxWidth: 560, margin: "0 auto", border: `1.5px solid ${BORDER}`, borderRadius: 18, padding: 36, background: "#fff", boxShadow: "0 20px 50px rgba(16,40,30,0.06)" }}>
        {status === "sent" ? (
          <div style={{ textAlign: "center", padding: "24px 4px" }}>
            <div style={{ width: 58, height: 58, borderRadius: 99, background: "#e7efe9", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 18px" }}>
              <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="#1C7A5B" strokeWidth="2.7" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
            </div>
            <h3 style={{ fontSize: 27, fontWeight: 700, color: INK, margin: "0 0 8px", fontFamily: SERIF }}>Message sent.</h3>
            <p style={{ fontSize: 15, color: GRAY, lineHeight: 1.55, margin: "0 auto 22px", maxWidth: 380 }}>Thanks, {form.name.split(" ")[0] || "there"}. We'll reply to {form.email} soon.</p>
            <button type="button" onClick={() => { setStatus("idle"); setForm({ name: "", email: "", phone: "", organization: "", title: "", subject: "", message: "", website: "" }); }} style={{ border: `1.5px solid ${INK}`, background: "transparent", color: INK, fontSize: 15, fontWeight: 700, padding: "12px 26px", borderRadius: 99, cursor: "pointer", fontFamily: "inherit" }}>Send another</button>
          </div>
        ) : (
          <>
        <div style={{ fontSize: 13, fontWeight: 700, color: INK, marginBottom: 12 }}>What kind of inquiry is this?</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 24 }}>
          {[["support", "Help / Customer Support"], ["sales", "Sales Inquiry"]].map(([k, l]) => (
            <div key={k} onClick={() => setInquiry(k)} style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer" }}>
              <span style={{ width: 18, height: 18, borderRadius: 99, border: inquiry === k ? `6px solid ${GREEN}` : `2px solid #c2c9c5`, boxSizing: "border-box" }} />
              <span style={{ fontSize: 15, fontWeight: 600, color: inquiry === k ? GREEN : INK }}>{l}</span>
            </div>
          ))}
        </div>
        <input value={form.website} onChange={setField("website")} tabIndex={-1} autoComplete="off" aria-hidden="true" style={{ position: "absolute", left: -9999, opacity: 0 }} />
        {field("name", "Your name", true)}
        {field("email", "Your email", true, false, "email")}
        {field("phone", "Your phone number", false, false, "tel")}
        {field("organization", "Your organization", false)}
        {field("title", "Your title", false)}
        {field("subject", "What is this about?", false)}
        {field("message", "What are you looking to accomplish?", true, true)}
        {error && <div style={{ color: "#a83f32", background: "#fff0ed", border: "1px solid #f0c8bf", borderRadius: 10, padding: "10px 12px", fontSize: 13.5, lineHeight: 1.45, marginBottom: 14 }}>{error}</div>}
        <div className="landai-contact-actions" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8 }}>
          <span style={{ fontSize: 13, color: GRAY }}>* required</span>
          <button type="submit" disabled={!canSubmit} style={{ border: "none", background: canSubmit ? GREEN_DK : "#bcbcb4", color: "#fff", fontSize: 15, fontWeight: 700, padding: "13px 30px", borderRadius: 11, cursor: canSubmit ? "pointer" : "default", fontFamily: "inherit" }}>{status === "sending" ? "Sending..." : "Send message"}</button>
        </div>
          </>
        )}
      </form>
    </div>
  );
}

function SecondaryCTA() {
  const goMobile = () => window.__landaiNav ? window.__landaiNav("mobile") : (location.href = "/");
  const goApi = () => window.__landaiNav ? window.__landaiNav("api") : (location.href = "/api");
  return (
    <div className="landai-section" style={{ background: MINT, padding: "56px 48px" }}>
      <div style={{ maxWidth: 760, margin: "0 auto" }}>
        <div style={{ marginBottom: 28 }}>
          <div style={{ fontSize: 26, color: INK, letterSpacing: -0.4, fontFamily: SERIF }}>Just looking up a parcel or two?</div>
          <div style={{ fontSize: 16, color: GRAY, marginTop: 6 }}>The <span onClick={goMobile} style={{ color: GREEN, fontWeight: 600, cursor: "pointer" }}>LandAI mobile app</span> is probably what you want.</div>
        </div>
        <div>
          <div style={{ fontSize: 26, color: INK, letterSpacing: -0.4, fontFamily: SERIF }}>Need the whole country or scheduled refreshes?</div>
          <div style={{ fontSize: 16, color: GRAY, marginTop: 6 }}>Talk to our team about <span onClick={goApi} style={{ color: GREEN, fontWeight: 600, cursor: "pointer" }}>bulk &amp; API</span>.</div>
        </div>
      </div>
    </div>
  );
}

function FinalCTA({ onBrowse }) {
  return (
    <div className="landai-section landai-final-cta" style={{ background: PAPER, padding: "80px 48px", textAlign: "center", borderTop: `1px solid ${BORDER}` }}>
      <h2 style={{ fontSize: 40, color: INK, letterSpacing: -0.8, margin: "0 0 28px" }}>Parcel data, ready when you are.</h2>
      <button onClick={onBrowse} style={{ border: "none", background: INK, color: "#fff", fontSize: 16, fontWeight: 600, padding: "17px 40px", borderRadius: 99, cursor: "pointer", fontFamily: "inherit" }}>Shop the data store</button>
    </div>
  );
}

function Footer() {
  const cols = [
    ["Product", [["Mobile App", "mobile"], ["Data Store", "store"], ["Web app", "web"], ["Get the app", "app"]]],
    ["For", [["Hunters", "mobile"], ["Real estate", "mobile"], ["Landowners", "mobile"], ["Investors", "mobile"]]],
    ["Company", [["About", "about"], ["Contact", "contact"], ["Privacy", "privacy"], ["Terms", null]]],
  ];
  const go = (t) => {
    if (t === "mobile") return window.__landaiNav ? window.__landaiNav("mobile") : (location.href = "/");
    if (t === "store") return window.__landaiNav ? window.__landaiNav("store") : (location.href = "/data-store");
    if (t === "contact") return window.__landaiNav ? window.__landaiNav("contact") : (location.href = "/contact");
    if (t === "about") return window.__landaiNav ? window.__landaiNav("about") : (location.href = "/about");
    if (t === "privacy") return location.href = "/privacy";
    if (t === "web") return openUrl(WEB_APP_URL);
    if (t === "app") return window.__landaiGetApp && window.__landaiGetApp();
  };
  const mono = "'JetBrains Mono', monospace";
  return (
    <div className="landai-footer" style={{ background: PAPER, padding: "60px 64px 34px", borderTop: `1px solid ${BORDER}` }}>
      <div className="landai-footer-main" style={{ display: "flex", gap: 60 }}>
        <div style={{ flex: 1.4 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ width: 40, height: 40, borderRadius: 11, background: "#fff", border: `1px solid ${BORDER}`, display: "flex", alignItems: "center", justifyContent: "center" }}>
              <svg width="24" height="24" viewBox="0 0 36 36">
                <path d="M18 5 L31 12 L18 19 L5 12 Z" fill="#2E7D5B" />
                <path d="M5 18 L18 25 L31 18" fill="none" stroke="#2E7D5B" strokeWidth="2.4" strokeLinejoin="round" />
                <path d="M5 24 L18 31 L31 24" fill="none" stroke="#9bbfae" strokeWidth="2.4" strokeLinejoin="round" />
              </svg>
            </div>
            <span style={{ fontSize: 22, fontWeight: 700, color: INK, letterSpacing: -0.4 }}>LandAI</span>
          </div>
          <div style={{ color: GRAY, fontSize: 16, lineHeight: 1.5, marginTop: 22, maxWidth: 300 }}>
            Property intelligence for the people who actually walk the land.
          </div>
        </div>
        {cols.map(([h, items], i) => (
          <div key={i} style={{ flex: 1 }}>
            <div style={{ color: "#9aa099", fontSize: 12, fontWeight: 600, letterSpacing: 1.6, textTransform: "uppercase", marginBottom: 22, fontFamily: mono }}>{h}</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              {items.map(([label, t], j) => <span key={j} onClick={t ? () => go(t) : undefined} style={{ color: INK, fontSize: 16.5, cursor: t ? "pointer" : "default" }}>{label}</span>)}
            </div>
          </div>
        ))}
      </div>
      <div className="landai-footer-bottom" style={{ marginTop: 56, paddingTop: 24, borderTop: `1px solid ${BORDER}`, display: "flex", justifyContent: "space-between", alignItems: "center", fontFamily: mono, fontSize: 13, letterSpacing: 1.5, color: "#9aa099" }}>
        <span>© 2026 LANDAI</span>
        <span>BUILT IN NORTH CAROLINA</span>
      </div>
    </div>
  );
}

// ---------- BROWSE / PURCHASE SCREEN ----------
const STATES = ["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","District of Columbia","Florida","Georgia","Guam","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Carolina","North Dakota","Northern Mariana Islands","Ohio","Oklahoma","Oregon","Pennsylvania","Puerto Rico","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","U.S. Virgin Islands","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"];

const STATS = [
  ["2,170", "Supported Counties"],
  ["136M", "Parcel Records"],
  ["133M", "Site Addresses"],
  ["116M", "Mailing Addresses"],
  ["121M", "Owner Names"],
];

function StatCard({ n, label, last }) {
  return (
    <div style={{ flex: 1, background: GREEN_DK, padding: "22px 14px", textAlign: "center", display: "flex", flexDirection: "column", gap: 7 }}>
      <div style={{ fontSize: 28, fontWeight: 800, color: "#fff", letterSpacing: -0.8 }}>{n}</div>
      <div style={{ fontSize: 13, color: "#9aa3b2", lineHeight: 1.3, fontWeight: 500 }}>{label}</div>
    </div>
  );
}

function DocButton({ children, onClick }) {
  return (
    <div onClick={onClick} style={{ flex: 1, background: GREEN_DK, color: "#fff", borderRadius: 8, padding: "16px 14px", textAlign: "center", fontSize: 14, fontWeight: 700, lineHeight: 1.3, cursor: "pointer" }}>{children}</div>
  );
}

const DATA_STORE_COUNTY_GEOJSON_URL = "https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json";
const DATA_STORE_COVERAGE_API_BASE = "https://us-central1-landai-476914.cloudfunctions.net/get_parcel";
const DATA_STORE_PUBLIC_COUNTIES_PATH = "/api/public/counties/all";
const DATA_STORE_AUTH_COUNTIES_PATH = "/api/counties/all";
const DATA_STORE_PUBLIC_FIELD_COVERAGE_PATH = countyFips => `/api/public/counties/${countyFips}/field-coverage`;
const DATA_STORE_COVERAGE_SOURCE_ID = "landai-store-coverage-counties";
const DATA_STORE_COVERAGE_FILL_LAYER_ID = "landai-store-coverage-counties-fill";
const DATA_STORE_COVERAGE_LINE_LAYER_ID = "landai-store-coverage-counties-line";
const DATA_STORE_COVERAGE_LABEL_LAYER_ID = "landai-store-coverage-counties-label";
const DATA_STORE_SELECTED_FILL_LAYER_ID = "landai-store-selected-county-fill";
const DATA_STORE_SELECTED_LINE_LAYER_ID = "landai-store-selected-county-line";
const DATA_STORE_STATE_OUTLINE_SOURCE_ID = "landai-store-selected-state-outline";
const DATA_STORE_STATE_OUTLINE_LAYER_ID = "landai-store-selected-state-outline-line";
const DATA_STORE_STATE_CLICK_ZOOM = 5.35;
const SUPPORTED_COUNTY_COMPLETE_COLOR = "#34C759";
const SUPPORTED_COUNTY_COMPLETE_OUTLINE_COLOR = "#166534";
const SUPPORTED_COUNTY_PREMIUM_COLOR = "#FF9500";
const SUPPORTED_COUNTY_PREMIUM_OUTLINE_COLOR = "#C76E00";
const SUPPORTED_COUNTY_COMPLETE_THRESHOLD_PCT = 40;
const SUPPORTED_COUNTY_SITE_COMPLETE_THRESHOLD_PCT = 5;
const SUPPORTED_COUNTY_PARTIAL_THRESHOLD_PCT = 10;
const DATA_STORE_FALLBACK_SUPPORTED_COUNTY_GEOIDS = ["01097", "37081", "37119", "16081", "56039", "12086"];

let dataStoreCoverageGeojsonPromise = null;
const dataStoreCountyFieldCoveragePromises = new Map();

function dataStoreFirstSymbolLayerId(map) {
  try {
    const layers = map.getStyle().layers || [];
    const symbol = layers.find(layer => layer.type === "symbol");
    return symbol && symbol.id;
  } catch (_) {
    return undefined;
  }
}

function normalizeCountyCoverageStatus(value) {
  const normalized = String(value || "").trim().toLowerCase();
  if (["complete", "partial", "limited", "unknown", "premium"].includes(normalized)) return normalized;
  if (normalized === "incomplete") return "limited";
  return "";
}

function countyCoverageNumber(value) {
  const numeric = Number(value);
  return Number.isFinite(numeric) ? numeric : 0;
}

function countyCoveragePercent(count, total) {
  if (!Number.isFinite(count) || !Number.isFinite(total) || total <= 0) return 0;
  return Math.round((count / total) * 10000) / 100;
}

function clampCountyCoveragePercent(value) {
  const numeric = Number(value);
  if (!Number.isFinite(numeric)) return 0;
  return Math.max(0, Math.min(100, numeric));
}

function countyCoverageStatusFromDetail(detail, supportedOverride = false) {
  const fieldCoverage = detail && detail.field_coverage && typeof detail.field_coverage === "object"
    ? detail.field_coverage
    : {};
  const explicitStatus = normalizeCountyCoverageStatus(fieldCoverage.status || (detail && detail.coverage_status));
  if (explicitStatus) return explicitStatus;
  if (supportedOverride) return "complete";

  const activeParcelCount = countyCoverageNumber(fieldCoverage.active_parcel_count || (detail && detail.active_parcel_count) || (detail && detail.parcel_count));
  if (fieldCoverage.coverage_unknown === true || activeParcelCount <= 0) return "unknown";

  const ownerNameCount = countyCoverageNumber(fieldCoverage.owner_name_count);
  const mailingAddressCount = countyCoverageNumber(fieldCoverage.mailing_address_count);
  const siteAddressCount = countyCoverageNumber(fieldCoverage.site_address_count);
  const ownerNamePct = countyCoverageNumber(fieldCoverage.owner_name_pct)
    || countyCoveragePercent(ownerNameCount, activeParcelCount);
  const mailingAddressPct = countyCoverageNumber(fieldCoverage.mailing_address_pct)
    || countyCoveragePercent(mailingAddressCount, activeParcelCount);
  const siteAddressPct = countyCoverageNumber(fieldCoverage.site_address_pct)
    || countyCoveragePercent(siteAddressCount, activeParcelCount);

  const ownerValue = clampCountyCoveragePercent(ownerNamePct);
  const mailingValue = clampCountyCoveragePercent(mailingAddressPct);
  const siteValue = clampCountyCoveragePercent(siteAddressPct);

  if (
    ownerValue >= SUPPORTED_COUNTY_COMPLETE_THRESHOLD_PCT
    && mailingValue >= SUPPORTED_COUNTY_COMPLETE_THRESHOLD_PCT
    && siteValue >= SUPPORTED_COUNTY_SITE_COMPLETE_THRESHOLD_PCT
  ) return "complete";
  if (Math.max(ownerValue, mailingValue, siteValue) >= SUPPORTED_COUNTY_PARTIAL_THRESHOLD_PCT) return "partial";
  return "limited";
}

function countyFipsFromFeature(feature) {
  const raw = feature && (feature.id || feature.properties?.GEOID || feature.properties?.geoid || feature.properties?.FIPS || feature.properties?.fips);
  const fips = String(raw || "").trim();
  return fips ? fips.padStart(5, "0") : "";
}

function displayCountyNameForFeature(feature, stateName) {
  const props = feature?.properties || {};
  const rawName = props.COUNTY_NAME || props.NAME || props.name || "";
  if (!stateName) return rawName;
  const matched = countyNameForSlug(stateName, rawName);
  return matched || rawName;
}

function escapeDataStoreMapHtml(value) {
  return String(value || "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

function dataStoreCountyTooltipHtml(countyName) {
  return `<div style="font-family:'Hanken Grotesk',system-ui,sans-serif;font-size:13px;font-weight:800;line-height:1.2;color:#111820;white-space:nowrap;">${escapeDataStoreMapHtml(countyName)}</div>`;
}

function dataStoreSearchKey(value) {
  return String(value || "")
    .trim()
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .toLowerCase()
    .replace(/&/g, " and ")
    .replace(/u\.s\./g, "us")
    .replace(/[^a-z0-9]+/g, " ")
    .trim()
    .replace(/\s+/g, " ");
}

function dataStoreCountyBaseName(countyName) {
  return String(countyName || "")
    .replace(/\s+(county|parish|borough|municipality|census area|municipio)$/i, "")
    .trim();
}

function dataStoreSearchLabelForCounty(countyName, stateName) {
  const stateCode = (stateCodeForName(stateName) || "").toUpperCase();
  return stateCode ? `${countyName}, ${stateCode}` : countyName;
}

function dataStoreSuggestionScore(key, haystacks) {
  let best = 0;
  haystacks.forEach(value => {
    const haystack = dataStoreSearchKey(value);
    if (!haystack) return;
    if (haystack === key) best = Math.max(best, 100);
    else if (haystack.startsWith(key)) best = Math.max(best, 82);
    else if (haystack.includes(key)) best = Math.max(best, 64);
  });
  return best;
}

function dataStoreLocalSearchSuggestions(query, limit = 8) {
  const key = dataStoreSearchKey(query);
  if (!key) return [];

  const results = [];
  STATES.forEach((stateName, stateIndex) => {
    const stateCode = stateCodeForName(stateName);
    const score = dataStoreSuggestionScore(key, [stateName, stateCode]);
    if (score) {
      results.push({
        type: "state",
        label: stateName,
        detail: "State",
        stateName,
        score,
        rank: stateIndex,
      });
    }
  });

  Object.entries(COUNTIES_BY_STATE).forEach(([stateName, counties], stateIndex) => {
    const stateCode = stateCodeForName(stateName);
    counties.forEach((countyName, countyIndex) => {
      const baseName = dataStoreCountyBaseName(countyName);
      const score = dataStoreSuggestionScore(key, [
        countyName,
        baseName,
        `${countyName} ${stateName}`,
        `${baseName} ${stateName}`,
        `${countyName} ${stateCode}`,
        `${baseName} ${stateCode}`,
        `${stateName} ${countyName}`,
        `${stateCode} ${baseName}`,
      ]);
      if (score) {
        results.push({
          type: "county",
          label: dataStoreSearchLabelForCounty(countyName, stateName),
          detail: stateName,
          stateName,
          countyName,
          score,
          rank: 100 + stateIndex * 1000 + countyIndex,
        });
      }
    });
  });

  return results
    .sort((a, b) => (b.score - a.score) || (a.rank - b.rank) || a.label.localeCompare(b.label))
    .slice(0, limit);
}

function dataStoreBestLocalSearchResult(query) {
  const key = dataStoreSearchKey(query);
  if (key.length < 2) return null;
  const suggestions = dataStoreLocalSearchSuggestions(query, 1);
  const best = suggestions[0];
  if (!best) return null;
  if (best.score >= 100) return best;
  return key.length >= 3 && best.score >= 82 ? best : null;
}

function dataStorePointInRing(point, ring) {
  if (!Array.isArray(ring) || ring.length < 4) return false;
  const x = Number(point[0]);
  const y = Number(point[1]);
  let inside = false;
  for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
    const xi = Number(ring[i]?.[0]);
    const yi = Number(ring[i]?.[1]);
    const xj = Number(ring[j]?.[0]);
    const yj = Number(ring[j]?.[1]);
    if (![xi, yi, xj, yj].every(Number.isFinite)) continue;
    const intersects = ((yi > y) !== (yj > y)) && (x < ((xj - xi) * (y - yi)) / (yj - yi || Number.EPSILON) + xi);
    if (intersects) inside = !inside;
  }
  return inside;
}

function dataStorePointInPolygon(point, rings) {
  if (!Array.isArray(rings) || !rings.length) return false;
  if (!dataStorePointInRing(point, rings[0])) return false;
  for (let i = 1; i < rings.length; i += 1) {
    if (dataStorePointInRing(point, rings[i])) return false;
  }
  return true;
}

function dataStoreFeatureContainsPoint(feature, point) {
  const geometry = feature?.geometry;
  if (!geometry) return false;
  if (geometry.type === "Polygon") return dataStorePointInPolygon(point, geometry.coordinates);
  if (geometry.type === "MultiPolygon") {
    return (geometry.coordinates || []).some(polygon => dataStorePointInPolygon(point, polygon));
  }
  return false;
}

function dataStoreVisitCoordinates(coordinates, visit) {
  if (!Array.isArray(coordinates)) return;
  if (typeof coordinates[0] === "number" && typeof coordinates[1] === "number") {
    visit(coordinates);
    return;
  }
  coordinates.forEach(part => dataStoreVisitCoordinates(part, visit));
}

function dataStoreFeatureBounds(feature) {
  let minLng = Infinity;
  let minLat = Infinity;
  let maxLng = -Infinity;
  let maxLat = -Infinity;
  dataStoreVisitCoordinates(feature?.geometry?.coordinates, ([lng, lat]) => {
    const x = Number(lng);
    const y = Number(lat);
    if (!Number.isFinite(x) || !Number.isFinite(y)) return;
    minLng = Math.min(minLng, x);
    minLat = Math.min(minLat, y);
    maxLng = Math.max(maxLng, x);
    maxLat = Math.max(maxLat, y);
  });
  if (![minLng, minLat, maxLng, maxLat].every(Number.isFinite)) return null;
  return [[minLng, minLat], [maxLng, maxLat]];
}

function dataStoreLongitudeBounds(longitudes) {
  const normalized = (longitudes || [])
    .map(value => Number(value))
    .filter(Number.isFinite)
    .map(value => ((value % 360) + 360) % 360)
    .sort((a, b) => a - b);
  if (!normalized.length) return null;
  if (normalized.length === 1) {
    const lng = normalized[0] > 180 ? normalized[0] - 360 : normalized[0];
    return [lng, lng];
  }

  let largestGap = -Infinity;
  let gapIndex = 0;
  for (let i = 0; i < normalized.length; i += 1) {
    const current = normalized[i];
    const next = i === normalized.length - 1 ? normalized[0] + 360 : normalized[i + 1];
    const gap = next - current;
    if (gap > largestGap) {
      largestGap = gap;
      gapIndex = i;
    }
  }

  const start = normalized[(gapIndex + 1) % normalized.length];
  const span = Math.max(0, 360 - largestGap);
  const west = start > 180 ? start - 360 : start;
  return [west, west + span];
}

function dataStoreMergedBounds(features) {
  const longitudes = [];
  let minLat = Infinity;
  let maxLat = -Infinity;
  (features || []).forEach(feature => {
    dataStoreVisitCoordinates(feature?.geometry?.coordinates, ([lng, lat]) => {
      const x = Number(lng);
      const y = Number(lat);
      if (!Number.isFinite(x) || !Number.isFinite(y)) return;
      longitudes.push(x);
      minLat = Math.min(minLat, y);
      maxLat = Math.max(maxLat, y);
    });
  });
  const lngBounds = dataStoreLongitudeBounds(longitudes);
  if (!lngBounds || ![minLat, maxLat].every(Number.isFinite)) return null;
  return [[lngBounds[0], minLat], [lngBounds[1], maxLat]];
}

function dataStoreStateFeatures(geojson, stateName) {
  const wanted = slugify(stateName);
  if (!wanted) return [];
  return (geojson?.features || []).filter(feature => {
    const fips = countyFipsFromFeature(feature);
    const featureStateName = stateNameForCountyFips(fips) || feature?.properties?.STATE_NAME || "";
    return slugify(featureStateName) === wanted;
  });
}

function dataStoreStateBounds(geojson, stateName) {
  const features = dataStoreStateFeatures(geojson, stateName);
  return dataStoreMergedBounds(features);
}

function dataStoreCoordinateKey(coord) {
  const lng = Number(coord?.[0]);
  const lat = Number(coord?.[1]);
  if (!Number.isFinite(lng) || !Number.isFinite(lat)) return "";
  return `${lng.toFixed(6)},${lat.toFixed(6)}`;
}

function dataStoreAddBoundaryRingSegments(ring, segments) {
  if (!Array.isArray(ring) || ring.length < 2) return;
  for (let i = 0; i < ring.length; i += 1) {
    const a = ring[i];
    const b = ring[(i + 1) % ring.length];
    const aKey = dataStoreCoordinateKey(a);
    const bKey = dataStoreCoordinateKey(b);
    if (!aKey || !bKey || aKey === bKey) continue;
    const key = aKey < bKey ? `${aKey}|${bKey}` : `${bKey}|${aKey}`;
    const existing = segments.get(key);
    if (existing) existing.count += 1;
    else segments.set(key, { count: 1, coordinates: [[Number(a[0]), Number(a[1])], [Number(b[0]), Number(b[1])]] });
  }
}

function dataStoreAddBoundaryGeometrySegments(geometry, segments) {
  if (geometry?.type === "Polygon") {
    (geometry.coordinates || []).forEach(ring => dataStoreAddBoundaryRingSegments(ring, segments));
  } else if (geometry?.type === "MultiPolygon") {
    (geometry.coordinates || []).forEach(polygon => {
      (polygon || []).forEach(ring => dataStoreAddBoundaryRingSegments(ring, segments));
    });
  }
}

function dataStoreStateOutlineGeoJSON(geojson, stateName) {
  const segments = new Map();
  dataStoreStateFeatures(geojson, stateName).forEach(feature => dataStoreAddBoundaryGeometrySegments(feature?.geometry, segments));
  return {
    type: "FeatureCollection",
    features: Array.from(segments.values())
      .filter(segment => segment.count === 1)
      .map((segment, index) => ({
        type: "Feature",
        id: `state-outline-${index}`,
        properties: { STATE_NAME: stateName },
        geometry: { type: "LineString", coordinates: segment.coordinates },
      })),
  };
}

function dataStoreSetStateOutlineOnMap(map, geojson, stateName) {
  if (!map || !map.getStyle) return;
  const outline = dataStoreStateOutlineGeoJSON(geojson, stateName);
  if (map.getSource(DATA_STORE_STATE_OUTLINE_SOURCE_ID)) {
    map.getSource(DATA_STORE_STATE_OUTLINE_SOURCE_ID).setData(outline);
  } else {
    map.addSource(DATA_STORE_STATE_OUTLINE_SOURCE_ID, {
      type: "geojson",
      data: outline,
      tolerance: 0.2,
    });
  }
  if (!map.getLayer(DATA_STORE_STATE_OUTLINE_LAYER_ID)) {
    const before = map.getLayer(DATA_STORE_COVERAGE_LABEL_LAYER_ID) ? DATA_STORE_COVERAGE_LABEL_LAYER_ID : undefined;
    map.addLayer({
      id: DATA_STORE_STATE_OUTLINE_LAYER_ID,
      type: "line",
      source: DATA_STORE_STATE_OUTLINE_SOURCE_ID,
      layout: {
        "line-cap": "round",
        "line-join": "round",
      },
      paint: {
        "line-color": "#050505",
        "line-opacity": 0.92,
        "line-width": ["interpolate", ["linear"], ["zoom"], 2, 1.6, 5, 2.4, 8, 3.8, 11, 5],
        "line-blur": 0.15,
      },
    }, before);
  }
}

function dataStoreFeatureSvgPath(feature, size = 40, padding = 7) {
  const bounds = dataStoreFeatureBounds(feature);
  if (!bounds) return "";
  const [[minLng, minLat], [maxLng, maxLat]] = bounds;
  const lngSpan = Math.max(maxLng - minLng, 1e-9);
  const latSpan = Math.max(maxLat - minLat, 1e-9);
  const usable = Math.max(size - padding * 2, 1);
  const pointPath = ([lng, lat]) => {
    const x = padding + ((Number(lng) - minLng) / lngSpan) * usable;
    const y = size - padding - ((Number(lat) - minLat) / latSpan) * usable;
    return `${Number.isFinite(x) ? x.toFixed(1) : padding} ${Number.isFinite(y) ? y.toFixed(1) : padding}`;
  };
  const ringPath = ring => {
    if (!Array.isArray(ring) || ring.length < 3) return "";
    const points = ring.map(pointPath).join(" L ");
    return points ? `M ${points} Z` : "";
  };
  const polygonPath = polygon => (Array.isArray(polygon) ? polygon.map(ringPath).filter(Boolean).join(" ") : "");
  const geometry = feature?.geometry;
  if (geometry?.type === "Polygon") return polygonPath(geometry.coordinates);
  if (geometry?.type === "MultiPolygon") return (geometry.coordinates || []).map(polygonPath).filter(Boolean).join(" ");
  return "";
}

function dataStoreFeatureMatchesCounty(feature, countyName, stateName) {
  const fips = countyFipsFromFeature(feature);
  const featureStateName = stateNameForCountyFips(fips) || feature?.properties?.STATE_NAME || "";
  if (stateName && slugify(featureStateName) !== slugify(stateName)) return false;
  const featureCountyName = displayCountyNameForFeature(feature, featureStateName);
  return countySlug(featureCountyName) === countySlug(countyName) || slugify(featureCountyName) === slugify(countyName);
}

async function dataStoreFeatureForCounty(countyName, stateName) {
  const geojson = await loadDataStoreCoverageGeoJSON();
  return (geojson?.features || []).find(feature => dataStoreFeatureMatchesCounty(feature, countyName, stateName)) || null;
}

function dataStoreSelectedFilterForFeature(feature) {
  const fips = countyFipsFromFeature(feature);
  return fips ? ["==", ["get", "GEOID"], fips] : ["==", ["get", "GEOID"], "__none__"];
}

function dataStoreSetSelectedCountyOnMap(map, feature) {
  if (!map || !feature) return;
  const filter = dataStoreSelectedFilterForFeature(feature);
  [DATA_STORE_SELECTED_FILL_LAYER_ID, DATA_STORE_SELECTED_LINE_LAYER_ID].forEach(layerId => {
    if (map.getLayer(layerId)) map.setFilter(layerId, filter);
  });
}

function dataStoreFitMapToFeature(map, feature, duration = 850) {
  const bounds = dataStoreFeatureBounds(feature);
  if (!map || !bounds) return;
  map.fitBounds(bounds, {
    duration,
    maxZoom: 10.4,
    padding: { top: 96, right: 80, bottom: 76, left: 80 },
  });
}

async function dataStoreFitMapToState(map, stateName, duration = 850) {
  if (!map || !stateName) return false;
  const geojson = await loadDataStoreCoverageGeoJSON();
  const bounds = dataStoreStateBounds(geojson, stateName);
  if (!bounds) return false;
  map.fitBounds(bounds, {
    duration,
    maxZoom: 7.35,
    padding: { top: 116, right: 86, bottom: 66, left: 86 },
  });
  return true;
}

function dataStoreCountySearchResultForFeature(feature) {
  const fips = countyFipsFromFeature(feature);
  const stateName = stateNameForCountyFips(fips) || feature?.properties?.STATE_NAME || "";
  const countyName = displayCountyNameForFeature(feature, stateName);
  if (!stateName || !countyName) return null;
  return {
    type: "county",
    label: dataStoreSearchLabelForCounty(countyName, stateName),
    detail: stateName,
    stateName,
    countyName,
  };
}

function dataStoreMetadataText(value) {
  return String(value || "").trim();
}

function dataStoreMetadataCount(value) {
  const numeric = Number(value);
  return Number.isFinite(numeric) && numeric > 0 ? Math.round(numeric) : 0;
}

function dataStoreCountyMetadataFromFeature(feature) {
  const props = feature?.properties || {};
  return {
    parcelCount: dataStoreMetadataCount(props.LANDAI_ACTIVE_PARCEL_COUNT || props.LANDAI_PARCEL_COUNT),
    sourceUpdatedAt: dataStoreMetadataText(props.LANDAI_SOURCE_UPDATED_AT),
    sourceDataAsOf: dataStoreMetadataText(props.LANDAI_SOURCE_DATA_AS_OF),
    sourceDataAsOfPrecision: dataStoreMetadataText(props.LANDAI_SOURCE_DATA_AS_OF_PRECISION),
    sourceDataAsOfLabel: dataStoreMetadataText(props.LANDAI_SOURCE_DATA_AS_OF_LABEL),
    latestIngestedAt: dataStoreMetadataText(props.LANDAI_LATEST_INGESTED_AT),
  };
}

function dataStoreFormattedDateOnly(value) {
  const raw = dataStoreMetadataText(value);
  if (!raw) return "";
  if (/^\d{11,}$/.test(raw)) {
    const parsed = Number(raw);
    if (Number.isFinite(parsed)) return new Date(parsed).toLocaleDateString(undefined, { timeZone: "UTC" });
  }
  if (/^\d{10}$/.test(raw)) {
    const parsed = Number(raw) * 1000;
    if (Number.isFinite(parsed)) return new Date(parsed).toLocaleDateString(undefined, { timeZone: "UTC" });
  }
  const dateOnly = raw.match(/^(\d{4})-(\d{2})-(\d{2})/);
  if (dateOnly) {
    const parsed = Date.parse(`${dateOnly[1]}-${dateOnly[2]}-${dateOnly[3]}T00:00:00Z`);
    if (!Number.isNaN(parsed)) return new Date(parsed).toLocaleDateString(undefined, { timeZone: "UTC" });
  }
  const parsed = Date.parse(raw);
  if (!Number.isNaN(parsed)) return new Date(parsed).toLocaleDateString();
  return raw;
}

function dataStoreFormattedSourceVintage(value, precision) {
  const raw = dataStoreMetadataText(value);
  const cleanPrecision = dataStoreMetadataText(precision).toLowerCase();
  if (!raw) return "";
  if (cleanPrecision === "quarter") {
    const match = raw.match(/^(\d{4})[-\s]?Q([1-4])$/i) || raw.match(/^Q([1-4])\s*(\d{4})$/i);
    if (match) {
      const year = match[1].length === 4 ? match[1] : match[2];
      const quarter = match[1].length === 4 ? match[2] : match[1];
      return `Q${quarter} ${year}`;
    }
  }
  if (cleanPrecision === "month" && /^\d{4}-\d{2}$/.test(raw)) {
    const parsed = Date.parse(`${raw}-01T00:00:00Z`);
    if (!Number.isNaN(parsed)) {
      return new Date(parsed).toLocaleDateString(undefined, { month: "long", year: "numeric", timeZone: "UTC" });
    }
  }
  if (cleanPrecision === "year" && /^\d{4}$/.test(raw)) return raw;
  return dataStoreFormattedDateOnly(raw);
}

function dataStoreDateFromLabel(value) {
  const raw = dataStoreMetadataText(value);
  if (!raw) return "";
  const isoDate = raw.match(/\b\d{4}-\d{2}-\d{2}\b/);
  if (isoDate) return dataStoreFormattedDateOnly(isoDate[0]);
  const slashDate = raw.match(/\b\d{1,2}\/\d{1,2}\/\d{2,4}\b/);
  if (slashDate) return dataStoreFormattedDateOnly(slashDate[0]);
  const year = raw.match(/\b(19|20)\d{2}\b/);
  return year ? year[0] : "";
}

function dataStoreCountyDataDateLabel(meta, loading = false) {
  if (loading) return "Loading...";
  if (!meta) return "Unknown";
  if (meta.sourceUpdatedAt) return dataStoreFormattedDateOnly(meta.sourceUpdatedAt);
  if (meta.sourceDataAsOf) return dataStoreFormattedSourceVintage(meta.sourceDataAsOf, meta.sourceDataAsOfPrecision);
  if (meta.sourceDataAsOfLabel) {
    const labelDate = dataStoreDateFromLabel(meta.sourceDataAsOfLabel);
    if (labelDate) return labelDate;
  }
  if (meta.latestIngestedAt) return dataStoreFormattedDateOnly(meta.latestIngestedAt);
  return "Unknown";
}

function dataStoreCountyParcelCountLabel(meta, loading = false) {
  if (loading) return "Loading...";
  if (meta?.parcelCount) return meta.parcelCount.toLocaleString();
  return "Unknown";
}

function dataStoreCountyIsSupported(feature) {
  const props = feature?.properties || {};
  return props.LANDAI_MAP_CLASS === "landai" || props.LANDAI_SUPPORTED === true;
}

async function dataStoreCountySearchResultForLngLat(lng, lat) {
  const geojson = await loadDataStoreCoverageGeoJSON();
  const point = [Number(lng), Number(lat)];
  if (!point.every(Number.isFinite)) return null;
  const feature = (geojson?.features || []).find(candidate => dataStoreFeatureContainsPoint(candidate, point));
  return feature ? dataStoreCountySearchResultForFeature(feature) : null;
}

async function dataStoreMapboxGeocodeFeatures(query, options = {}) {
  const token = String(window.MAPBOX_ACCESS_TOKEN || "").trim();
  if (!token) throw new Error("Missing Mapbox token");

  const params = new URLSearchParams({
    access_token: token,
    country: "us",
    limit: String(options.limit || 5),
    types: options.types || "place,locality,neighborhood,address,poi,postcode,district,region",
  });
  const url = `https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(query)}.json?${params.toString()}`;
  const response = await fetch(url);
  if (!response.ok) throw new Error(`Mapbox geocoding ${response.status}`);
  const payload = await response.json();
  return Array.isArray(payload?.features) ? payload.features : [];
}

function dataStoreMapboxRegionName(feature) {
  const region = (feature?.context || []).find(item => String(item?.id || "").startsWith("region."));
  return region?.text || "";
}

function dataStoreMapboxPlaceTypeLabel(feature) {
  const types = Array.isArray(feature?.place_type) ? feature.place_type : [];
  if (types.includes("place") || types.includes("locality")) return "City";
  if (types.includes("neighborhood")) return "Neighborhood";
  if (types.includes("district")) return "Area";
  if (types.includes("region")) return "State";
  if (types.includes("postcode")) return "ZIP";
  if (types.includes("address")) return "Address";
  return "Place";
}

async function dataStoreMapboxPlaceSuggestions(query, limit = 5) {
  const key = dataStoreSearchKey(query);
  if (key.length < 3) return [];
  const features = await dataStoreMapboxGeocodeFeatures(query, {
    limit,
    types: "place,locality,neighborhood,district,region",
  });
  return features.map((feature, index) => {
    const center = Array.isArray(feature?.center) ? feature.center : [];
    const regionName = dataStoreMapboxRegionName(feature);
    const typeLabel = dataStoreMapboxPlaceTypeLabel(feature);
    const label = feature?.text || feature?.place_name || "";
    if (!label || center.length < 2) return null;
    return {
      type: "place",
      id: feature?.id || `${label}-${center.join(",")}-${index}`,
      label,
      detail: regionName ? `${typeLabel}, ${regionName}` : typeLabel,
      placeName: feature?.place_name || label,
      center,
    };
  }).filter(Boolean);
}

async function dataStoreMapboxCountySearch(query) {
  const features = await dataStoreMapboxGeocodeFeatures(query);
  for (const feature of features) {
    const center = Array.isArray(feature?.center) ? feature.center : null;
    if (!center || center.length < 2) continue;
    const match = await dataStoreCountySearchResultForLngLat(center[0], center[1]);
    if (match) return match;
  }
  return null;
}

function stateNameForCountyFips(fips) {
  return STATE_FIPS_TO_NAME[String(fips || "").slice(0, 2)] || "";
}

function buildDataStoreCoverageGeoJSON(countyGeojson, registry) {
  const detailsByFips = registry.detailsByFips || new Map();
  const supportedGeoids = registry.supportedGeoids || new Set();
  const features = Array.isArray(countyGeojson?.features)
    ? countyGeojson.features.map(feature => {
      const fips = countyFipsFromFeature(feature);
      if (!fips || !feature.geometry) return null;

      const isSupportedByList = supportedGeoids.has(fips);
      const detail = detailsByFips.get(fips) || (isSupportedByList ? { county_fips: fips, coverage_status: "complete" } : null);
      const coverageStatus = detail ? countyCoverageStatusFromDetail(detail, isSupportedByList) : "premium";
      const mapClass = coverageStatus === "complete" ? "landai" : "premium";
      const countyName = (detail && detail.county_name) || feature.properties?.COUNTY_NAME || feature.properties?.NAME || "";
      const stateName = stateNameForCountyFips(fips);
      const fieldCoverage = detail && detail.field_coverage && typeof detail.field_coverage === "object" ? detail.field_coverage : {};
      const sourceUpdatedAt = dataStoreMetadataText((detail && detail.source_updated_at) || fieldCoverage.source_updated_at);
      const sourceDataAsOf = dataStoreMetadataText((detail && detail.source_data_as_of) || fieldCoverage.source_data_as_of);
      const sourceDataAsOfPrecision = dataStoreMetadataText((detail && detail.source_data_as_of_precision) || fieldCoverage.source_data_as_of_precision);
      const sourceDataAsOfLabel = dataStoreMetadataText((detail && detail.source_data_as_of_label) || fieldCoverage.source_data_as_of_label);
      const latestIngestedAt = dataStoreMetadataText((detail && detail.latest_ingested_at) || fieldCoverage.latest_ingested_at);
      const coverageRefreshedAt = dataStoreMetadataText((detail && detail.coverage_refreshed_at) || fieldCoverage.refreshed_at);
      const activeParcelCount = dataStoreMetadataCount(fieldCoverage.active_parcel_count || (detail && detail.active_parcel_count) || (detail && detail.parcel_count));

      return {
        ...feature,
        id: fips,
        properties: {
          ...(feature.properties || {}),
          GEOID: fips,
          STATE_FIPS: fips.slice(0, 2),
          STATE_NAME: stateName,
          COUNTY_NAME: countyName,
          LANDAI_MAP_CLASS: mapClass,
          LANDAI_COVERAGE_STATUS: mapClass === "landai" ? "complete" : "premium",
          LANDAI_RAW_STATUS: coverageStatus,
          LANDAI_SUPPORTED: mapClass === "landai",
          LANDAI_ACTIVE_PARCEL_COUNT: activeParcelCount,
          LANDAI_PARCEL_COUNT: activeParcelCount,
          LANDAI_SOURCE_UPDATED_AT: sourceUpdatedAt,
          LANDAI_SOURCE_DATA_AS_OF: sourceDataAsOf,
          LANDAI_SOURCE_DATA_AS_OF_PRECISION: sourceDataAsOfPrecision,
          LANDAI_SOURCE_DATA_AS_OF_LABEL: sourceDataAsOfLabel,
          LANDAI_LATEST_INGESTED_AT: latestIngestedAt,
          LANDAI_COVERAGE_REFRESHED_AT: coverageRefreshedAt,
        },
      };
    }).filter(Boolean)
    : [];
  return { type: "FeatureCollection", features };
}

function loadDataStoreCoverageGeoJSON() {
  if (dataStoreCoverageGeojsonPromise) return dataStoreCoverageGeojsonPromise;
  const apiBase = String(window.LANDAI_COVERAGE_API_BASE || window.LANDAI_API_BASE_URL || DATA_STORE_COVERAGE_API_BASE).replace(/\/$/, "");
  dataStoreCoverageGeojsonPromise = Promise.all([
    fetch(DATA_STORE_COUNTY_GEOJSON_URL).then(res => {
      if (!res.ok) throw new Error(`County geometry ${res.status}`);
      return res.json();
    }),
    fetch(`${apiBase}${DATA_STORE_PUBLIC_COUNTIES_PATH}`)
      .then(res => {
        if (!res.ok) throw new Error(`Public county registry ${res.status}`);
        return res.json();
      })
      .catch(publicErr => {
        console.warn("[data-store-map] Public county registry unavailable; trying authenticated county registry", publicErr);
        return fetch(`${apiBase}${DATA_STORE_AUTH_COUNTIES_PATH}`)
          .then(res => {
            if (!res.ok) throw new Error(`County registry ${res.status}`);
            return res.json();
          })
          .catch(authErr => {
            console.warn("[data-store-map] County registry unavailable; loading static supported-county catalog", authErr);
            return fetch("/supported-counties.json")
              .then(res => {
                if (!res.ok) throw new Error(`Static supported counties ${res.status}`);
                return res.json();
              })
              .catch(staticErr => {
                console.warn("[data-store-map] Static supported-county catalog unavailable; using minimal fallback", staticErr);
                return { geoids: DATA_STORE_FALLBACK_SUPPORTED_COUNTY_GEOIDS };
              });
          });
      }),
  ]).then(([countyGeojson, registryData]) => {
    const countyDetails = Array.isArray(registryData.counties) ? registryData.counties : [];
    const detailsByFips = new Map(
      countyDetails
        .map(county => [String(county?.county_fips || "").trim().padStart(5, "0"), county])
        .filter(([fips]) => fips && fips !== "00000"),
    );
    const supportedGeoids = new Set(
      (Array.isArray(registryData.geoids) ? registryData.geoids : [])
        .map(fips => String(fips || "").trim().padStart(5, "0"))
        .filter(fips => fips && fips !== "00000"),
    );
    return buildDataStoreCoverageGeoJSON(countyGeojson, { detailsByFips, supportedGeoids });
  }).catch(err => {
    dataStoreCoverageGeojsonPromise = null;
    throw err;
  });
  return dataStoreCoverageGeojsonPromise;
}

function loadDataStoreCountyFieldCoverage(countyFips) {
  const fips = String(countyFips || "").replace(/\D/g, "").padStart(5, "0");
  if (!/^\d{5}$/.test(fips)) return Promise.resolve(null);
  if (dataStoreCountyFieldCoveragePromises.has(fips)) return dataStoreCountyFieldCoveragePromises.get(fips);
  const apiBase = String(window.LANDAI_COVERAGE_API_BASE || window.LANDAI_API_BASE_URL || DATA_STORE_COVERAGE_API_BASE).replace(/\/$/, "");
  const promise = fetch(`${apiBase}${DATA_STORE_PUBLIC_FIELD_COVERAGE_PATH(fips)}`)
    .then(res => {
      if (res.status === 404) return null;
      if (!res.ok) throw new Error(`County field coverage ${res.status}`);
      return res.json();
    })
    .then(payload => {
      const fields = Array.isArray(payload?.fields) ? payload.fields : [];
      return { ...(payload || {}), county_fips: fips, fields };
    })
    .catch(err => {
      dataStoreCountyFieldCoveragePromises.delete(fips);
      throw err;
    });
  dataStoreCountyFieldCoveragePromises.set(fips, promise);
  return promise;
}

function useDataStoreCountyData(countyName, stateName) {
  const [countyMeta, setCountyMeta] = useState(null);
  const [countyMetaLoading, setCountyMetaLoading] = useState(true);
  const [fieldCoverage, setFieldCoverage] = useState(null);
  const [fieldCoverageLoading, setFieldCoverageLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;
    setCountyMetaLoading(true);
    setFieldCoverageLoading(true);
    setCountyMeta(null);
    setFieldCoverage(null);
    dataStoreFeatureForCounty(countyName, stateName)
      .then(feature => {
        if (cancelled) return null;
        setCountyMeta(feature ? dataStoreCountyMetadataFromFeature(feature) : null);
        const fips = countyFipsFromFeature(feature);
        if (!fips) return null;
        return loadDataStoreCountyFieldCoverage(fips);
      })
      .then(coverage => {
        if (!cancelled) setFieldCoverage(coverage || null);
      })
      .catch(err => {
        if (!cancelled) {
          setCountyMeta(null);
          setFieldCoverage(null);
        }
        console.warn("[data-store-map] County field metadata unavailable", err);
      })
      .finally(() => {
        if (!cancelled) {
          setCountyMetaLoading(false);
          setFieldCoverageLoading(false);
        }
      });
    return () => {
      cancelled = true;
    };
  }, [countyName, stateName]);

  return { countyMeta, countyMetaLoading, fieldCoverage, fieldCoverageLoading };
}

function useSupportedCountiesInState(stateName, currentCounty) {
  const [state, setState] = useState({ loading: true, counties: [] });

  useEffect(() => {
    let cancelled = false;
    setState({ loading: true, counties: [] });
    loadDataStoreCoverageGeoJSON()
      .then(geojson => {
        if (cancelled) return;
        const currentSlug = countySlug(currentCounty);
        const seen = new Set();
        const counties = [];
        (geojson?.features || []).forEach(feature => {
          const fips = countyFipsFromFeature(feature);
          const featureStateName = stateNameForCountyFips(fips) || feature?.properties?.STATE_NAME || "";
          if (slugify(featureStateName) !== slugify(stateName)) return;
          if (!dataStoreCountyIsSupported(feature)) return;
          const name = displayCountyNameForFeature(feature, stateName);
          const slug = countySlug(name);
          if (!name || !slug || slug === currentSlug || seen.has(slug)) return;
          seen.add(slug);
          counties.push(name);
        });
        counties.sort((a, b) => a.localeCompare(b));
        setState({ loading: false, counties });
      })
      .catch(err => {
        if (!cancelled) setState({ loading: false, counties: [] });
        console.warn("[data-store-state] Supported county list unavailable", err);
      });
    return () => {
      cancelled = true;
    };
  }, [stateName, currentCounty]);

  return state;
}

function addDataStoreCoverageOverlay(map) {
  return loadDataStoreCoverageGeoJSON().then(geojson => {
    if (!map || !map.getStyle) return;
    const before = dataStoreFirstSymbolLayerId(map);
    if (map.getSource(DATA_STORE_COVERAGE_SOURCE_ID)) {
      map.getSource(DATA_STORE_COVERAGE_SOURCE_ID).setData(geojson);
      return geojson;
    }

    map.addSource(DATA_STORE_COVERAGE_SOURCE_ID, {
      type: "geojson",
      data: geojson,
      tolerance: 0.55,
    });

    map.addLayer({
      id: DATA_STORE_COVERAGE_FILL_LAYER_ID,
      type: "fill",
      source: DATA_STORE_COVERAGE_SOURCE_ID,
      paint: {
        "fill-color": [
          "case",
          ["==", ["get", "LANDAI_MAP_CLASS"], "landai"],
          SUPPORTED_COUNTY_COMPLETE_COLOR,
          SUPPORTED_COUNTY_PREMIUM_COLOR,
        ],
        "fill-opacity": [
          "case",
          ["==", ["get", "LANDAI_MAP_CLASS"], "landai"],
          0.68,
          0.46,
        ],
      },
    }, before || undefined);

    map.addLayer({
      id: DATA_STORE_COVERAGE_LINE_LAYER_ID,
      type: "line",
      source: DATA_STORE_COVERAGE_SOURCE_ID,
      paint: {
        "line-color": [
          "case",
          ["==", ["get", "LANDAI_MAP_CLASS"], "landai"],
          SUPPORTED_COUNTY_COMPLETE_OUTLINE_COLOR,
          SUPPORTED_COUNTY_PREMIUM_OUTLINE_COLOR,
        ],
        "line-opacity": 0.76,
        "line-width": ["interpolate", ["linear"], ["zoom"], 2, 0.24, 5, 0.52, 8, 0.9, 11, 1.3],
      },
    }, before || undefined);

    map.addLayer({
      id: DATA_STORE_SELECTED_FILL_LAYER_ID,
      type: "fill",
      source: DATA_STORE_COVERAGE_SOURCE_ID,
      filter: ["==", ["get", "GEOID"], "__none__"],
      paint: {
        "fill-color": "#2E6BF0",
        "fill-opacity": 0.26,
      },
    }, before || undefined);

    map.addLayer({
      id: DATA_STORE_SELECTED_LINE_LAYER_ID,
      type: "line",
      source: DATA_STORE_COVERAGE_SOURCE_ID,
      filter: ["==", ["get", "GEOID"], "__none__"],
      paint: {
        "line-color": "#0E47D9",
        "line-opacity": 0.95,
        "line-width": ["interpolate", ["linear"], ["zoom"], 4, 2.4, 8, 3.6, 12, 5],
      },
    }, before || undefined);

    map.addLayer({
      id: DATA_STORE_COVERAGE_LABEL_LAYER_ID,
      type: "symbol",
      source: DATA_STORE_COVERAGE_SOURCE_ID,
      minzoom: 5.6,
      layout: {
        "text-field": ["get", "COUNTY_NAME"],
        "text-size": ["interpolate", ["linear"], ["zoom"], 6, 9.5, 9, 11.5, 12, 13],
        "text-padding": 3,
        "text-optional": true,
      },
      paint: {
        "text-color": "#1b2a24",
        "text-halo-color": "#ffffff",
        "text-halo-width": 1.15,
        "text-opacity": ["interpolate", ["linear"], ["zoom"], 5.6, 0, 6.5, 0.92],
      },
    }, before || undefined);
    return geojson;
  });
}

function BrowseMapboxMap({ onCounty, selectedCounty }) {
  const mapNode = useRef(null);
  const mapRef = useRef(null);
  const onCountyRef = useRef(onCounty);
  const selectedCountyRef = useRef(selectedCounty || null);
  const stateDrilldownRef = useRef("");
  const [status, setStatus] = useState("loading");

  useEffect(() => {
    onCountyRef.current = onCounty;
  }, [onCounty]);

  useEffect(() => {
    selectedCountyRef.current = selectedCounty || null;
  }, [selectedCounty?.countyName, selectedCounty?.stateName]);

  useEffect(() => {
    const map = mapRef.current;
    if (!map || status !== "ready") return undefined;

    if (!selectedCounty) {
      stateDrilldownRef.current = "";
      [DATA_STORE_SELECTED_FILL_LAYER_ID, DATA_STORE_SELECTED_LINE_LAYER_ID].forEach(layerId => {
        if (map.getLayer(layerId)) map.setFilter(layerId, ["==", ["get", "GEOID"], "__none__"]);
      });
      map.fitBounds(
        [
          [-125.25, 24.35],
          [-66.5, 49.85],
        ],
        { duration: 650, padding: { top: 108, right: 38, bottom: 34, left: 38 } },
      );
      return undefined;
    }

    let cancelled = false;
    dataStoreFeatureForCounty(selectedCounty.countyName, selectedCounty.stateName)
      .then(feature => {
        if (cancelled || !feature) return;
        dataStoreSetSelectedCountyOnMap(map, feature);
        dataStoreFitMapToFeature(map, feature);
      })
      .catch(err => console.warn("[data-store-map] Selected county zoom failed", err));

    return () => {
      cancelled = true;
    };
  }, [status, selectedCounty?.countyName, selectedCounty?.stateName]);

  useEffect(() => {
    const node = mapNode.current;
    if (!node || mapRef.current) return undefined;

    const mapboxgl = window.mapboxgl;
    if (!mapboxgl) {
      setStatus("missing-script");
      return undefined;
    }

    const token = String(window.MAPBOX_ACCESS_TOKEN || "").trim();
    if (!token) {
      setStatus("missing-token");
      return undefined;
    }

    mapboxgl.accessToken = token;

    const style = String(window.LANDAI_MAPBOX_STYLE || "").trim() || "mapbox://styles/mapbox/light-v11";
    if (typeof mapboxgl.supported === "function" && !mapboxgl.supported()) {
      setStatus("webgl-error");
      return undefined;
    }

    let map;
    try {
      map = new mapboxgl.Map({
        container: node,
        style,
        center: [-98.6, 39.6],
        zoom: 3.45,
        minZoom: 2.2,
        maxZoom: 15,
        attributionControl: true,
        cooperativeGestures: false,
        scrollZoom: true,
      });
    } catch (err) {
      setStatus("webgl-error");
      console.warn("[data-store-map] Mapbox initialization failed", err);
      return undefined;
    }
    mapRef.current = map;
    const countyHoverPopup = new mapboxgl.Popup({
      closeButton: false,
      closeOnClick: false,
      maxWidth: "240px",
      offset: 12,
    });

    map.addControl(new mapboxgl.NavigationControl({ showCompass: false }), "bottom-right");
    map.addControl(new mapboxgl.ScaleControl({ maxWidth: 120, unit: "imperial" }), "bottom-left");

    const resize = () => {
      try { map.resize(); }
      catch (_) { /* noop */ }
    };

    map.on("load", () => {
      map.fitBounds(
        [
          [-125.25, 24.35],
          [-66.5, 49.85],
        ],
        { duration: 0, padding: { top: 108, right: 38, bottom: 34, left: 38 } },
      );

      addDataStoreCoverageOverlay(map)
        .then(geojson => {
          const features = geojson?.features || [];
          node.dataset.coverageSupportedCount = String(features.filter(feature => feature?.properties?.LANDAI_MAP_CLASS === "landai").length);
          node.dataset.coveragePremiumCount = String(features.filter(feature => feature?.properties?.LANDAI_MAP_CLASS !== "landai").length);
          node.dataset.coverageOverlayReady = "1";
          setStatus("ready");
        })
        .catch(err => {
          node.dataset.coverageOverlayReady = "error";
          setStatus("coverage-error");
          console.warn("[data-store-map] County coverage overlay failed", err);
        });

      resize();
      setTimeout(resize, 150);
      setTimeout(resize, 450);
    });

    map.on("mouseenter", DATA_STORE_COVERAGE_FILL_LAYER_ID, () => {
      map.getCanvas().style.cursor = "pointer";
    });

    map.on("mousemove", DATA_STORE_COVERAGE_FILL_LAYER_ID, event => {
      const feature = event.features && event.features[0];
      if (!feature) return;
      const fips = countyFipsFromFeature(feature);
      const stateName = stateNameForCountyFips(fips);
      const countyName = displayCountyNameForFeature(feature, stateName);
      if (!countyName) return;
      countyHoverPopup
        .setLngLat(event.lngLat)
        .setHTML(dataStoreCountyTooltipHtml(countyName))
        .addTo(map);
    });

    map.on("mouseleave", DATA_STORE_COVERAGE_FILL_LAYER_ID, () => {
      map.getCanvas().style.cursor = "";
      countyHoverPopup.remove();
    });

    map.on("click", DATA_STORE_COVERAGE_FILL_LAYER_ID, event => {
      const feature = event.features && event.features[0];
      if (!feature) return;
      const fips = countyFipsFromFeature(feature);
      const stateName = stateNameForCountyFips(fips) || feature?.properties?.STATE_NAME || "";
      const countyName = displayCountyNameForFeature(feature, stateName);
      const shouldZoomToState = !selectedCountyRef.current
        && stateName
        && map.getZoom() < DATA_STORE_STATE_CLICK_ZOOM
        && stateDrilldownRef.current !== stateName;
      if (shouldZoomToState) {
        stateDrilldownRef.current = stateName;
        countyHoverPopup.remove();
        dataStoreFitMapToState(map, stateName)
          .then(didFit => {
            if (!didFit) stateDrilldownRef.current = "";
          })
          .catch(err => {
            stateDrilldownRef.current = "";
            console.warn("[data-store-map] State zoom failed", err);
          });
        return;
      }
      if (stateName && countyName && onCountyRef.current) {
        stateDrilldownRef.current = stateName;
        dataStoreSetSelectedCountyOnMap(map, feature);
        dataStoreFitMapToFeature(map, feature);
        onCountyRef.current(countyName, stateName);
      }
    });

    return () => {
      mapRef.current = null;
      countyHoverPopup.remove();
      map.remove();
    };
  }, []);

  return (
    <div style={{ position: "absolute", inset: 0, background: "#e9edee" }}>
      <div ref={mapNode} style={{ position: "absolute", inset: 0 }} />
      {status !== "ready" && (
        <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", textAlign: "center", padding: 28, background: "rgba(233,237,238,0.86)", backdropFilter: "blur(2px)", color: GRAY, fontSize: 13, lineHeight: 1.55, fontFamily: "'JetBrains Mono', monospace" }}>
          {status === "missing-token" ? (
            <span>Mapbox needs a public access token.<br />Set <strong style={{ color: INK }}>MAPBOX_ACCESS_TOKEN</strong> for this environment.</span>
          ) : status === "missing-script" ? (
            <span>Mapbox GL did not load.</span>
          ) : status === "webgl-error" ? (
            <span>Map needs WebGL to display.</span>
          ) : status === "coverage-error" ? (
            <span>County coverage could not load.<br />Please refresh the page.</span>
          ) : (
            <div style={{ minWidth: 230, borderRadius: 8, background: "#fff", boxShadow: "0 18px 42px rgba(16,40,30,0.16)", padding: "18px 20px", display: "flex", alignItems: "center", justifyContent: "center", gap: 11 }}>
              <span style={{ width: 10, height: 10, borderRadius: 99, background: SUPPORTED_COUNTY_COMPLETE_COLOR, boxShadow: "0 0 0 6px rgba(52,199,89,0.16)" }} />
              <span>Loading county coverage...</span>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function BrowseCountyPanel({ countyName, stateName, onBack, onCounty, onAdd }) {
  const { countyMeta, countyMetaLoading, fieldCoverage, fieldCoverageLoading } = useDataStoreCountyData(countyName, stateName);
  const { loading: otherCountiesLoading, counties: otherSupportedCounties } = useSupportedCountiesInState(stateName, countyName);
  const info = countyInfo(countyName);
  const parcelCount = dataStoreCountyParcelCountLabel(countyMeta, countyMetaLoading);
  const dataDate = dataStoreCountyDataDateLabel(countyMeta, countyMetaLoading);
  const stats = [["Parcels", parcelCount], ["Data date", dataDate]];
  const base = info.price;

  return (
    <>
      <div onClick={onBack} style={{ display: "inline-flex", alignItems: "center", gap: 7, color: GREEN, fontSize: 14, fontWeight: 700, cursor: "pointer", marginBottom: 16 }}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={GREEN} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6" /></svg>
        Back to all counties
      </div>
      <h1 style={{ fontSize: 32, fontWeight: 800, color: INK, letterSpacing: -1, margin: 0 }}>{countyName}, {stateName}</h1>

      <div className="landai-county-stats" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px 40px", marginTop: 22 }}>
        {stats.map(([label, val], i) => (
          <div key={i}>
            <div style={{ fontSize: 22, fontWeight: 800, color: GREEN_DK, letterSpacing: -0.4, fontFamily: "'JetBrains Mono', monospace" }}>{val}</div>
            <div style={{ fontSize: 12.5, color: GRAY, marginTop: 2, fontWeight: 600 }}>{label}</div>
          </div>
        ))}
      </div>

      <div className="landai-product-card" style={{ marginTop: 30, background: GREEN_DK, borderRadius: 16, padding: "24px 24px 26px", color: "#fff" }}>
        <div style={{ fontSize: 18, fontWeight: 700, marginBottom: 16 }}>County parcel package</div>
        <div style={{ display: "flex", gap: 11, alignItems: "flex-start", marginBottom: 18 }}>
          <span style={{ width: 20, height: 20, borderRadius: 99, background: "#fff", display: "flex", alignItems: "center", justifyContent: "center", boxSizing: "border-box", marginTop: 1, flexShrink: 0 }}>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={GREEN_DK} strokeWidth="3.4" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
          </span>
          <div>
            <span style={{ fontSize: 15, fontWeight: 700 }}>LandAI parcel schema included</span>
            <div style={{ fontSize: 13, color: "rgba(255,255,255,0.6)", marginTop: 4 }}>One standardized set of parcel fields, with completeness shown below.</div>
          </div>
        </div>

        <div style={{ fontSize: 13, fontWeight: 700, color: "rgba(255,255,255,0.75)", marginBottom: 6 }}>Export formats included</div>
        <div style={{ fontSize: 13, color: "rgba(255,255,255,0.6)", lineHeight: 1.45, marginBottom: 10 }}>Every county purchase includes all download formats.</div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 20 }}>
          {INCLUDED_EXPORT_FORMATS.map(format => <IncludedFormatChip key={format} label={format} />)}
        </div>

        <button onClick={() => onAdd && onAdd(countyName, base, info.parcels.toLocaleString(), { format: INCLUDED_FORMAT_LABEL })} style={{ width: "100%", border: "none", background: GREEN, color: "#fff", fontSize: 16, fontWeight: 800, padding: "16px 0", borderRadius: 12, cursor: "pointer", fontFamily: "inherit", letterSpacing: 0.2 }}>
          Add {countyName} to cart — ${base}
        </button>
      </div>

      <FieldCoverageSection fieldCoverage={fieldCoverage} loading={fieldCoverageLoading} />

      <div style={{ marginTop: 30, background: "#dde8f3", borderRadius: 14, padding: "18px 22px" }}>
        <div style={{ fontSize: 15, fontWeight: 700, color: "#23476e" }}>Need more than a few counties?</div>
        <div style={{ fontSize: 14, color: "#4a6a8e", marginTop: 4 }}>Grab the whole state, or reach out about nationwide bulk &amp; API access.</div>
      </div>

      <div style={{ marginTop: 36 }}>
        <h3 style={{ fontSize: 18, fontWeight: 700, color: INK, margin: "0 0 16px" }}>Other counties in {stateName}</h3>
        {otherCountiesLoading ? (
          <div style={{ fontSize: 14, color: GRAY }}>Loading supported counties...</div>
        ) : otherSupportedCounties.length ? (
          <div className="landai-other-counties" style={{ columns: 2, columnGap: 40 }}>
            {otherSupportedCounties.map((county, i) => (
              <div key={i} onClick={() => onCounty(county, stateName)} style={{ breakInside: "avoid", padding: "8px 0", fontSize: 14, fontWeight: 600, color: GREEN_DK, cursor: "pointer" }}>{county}</div>
            ))}
          </div>
        ) : (
          <div style={{ fontSize: 14, color: GRAY }}>No other supported counties in {stateName} yet.</div>
        )}
      </div>
    </>
  );
}

function BrowseStore({ onHome, onBrowse, onState, onCounty, onSupport, onCart, onAdd, cartCount, initialCounty }) {
  const [q, setQ] = useState("");
  const [searchOpen, setSearchOpen] = useState(false);
  const [searchBusy, setSearchBusy] = useState(false);
  const [searchMessage, setSearchMessage] = useState("");
  const [selectedCounty, setSelectedCounty] = useState(initialCounty || null);
  const [placeSuggestions, setPlaceSuggestions] = useState([]);
  const [placesBusy, setPlacesBusy] = useState(false);
  const localSuggestions = dataStoreLocalSearchSuggestions(q, 5);
  const localSuggestionKeys = new Set(localSuggestions.map(item => dataStoreSearchKey(`${item.label} ${item.detail}`)));
  const searchSuggestions = [
    ...localSuggestions,
    ...placeSuggestions.filter(item => !localSuggestionKeys.has(dataStoreSearchKey(`${item.label} ${item.detail}`))),
  ].slice(0, 8);

  useEffect(() => {
    setSelectedCounty(initialCounty || null);
    if (initialCounty) setQ(dataStoreSearchLabelForCounty(initialCounty.countyName, initialCounty.stateName));
  }, [initialCounty?.countyName, initialCounty?.stateName]);

  useEffect(() => {
    const query = q.trim();
    if (dataStoreSearchKey(query).length < 3) {
      setPlaceSuggestions([]);
      setPlacesBusy(false);
      return undefined;
    }

    let cancelled = false;
    const timer = window.setTimeout(() => {
      setPlacesBusy(true);
      dataStoreMapboxPlaceSuggestions(query, 5)
        .then(suggestions => {
          if (!cancelled) setPlaceSuggestions(suggestions);
        })
        .catch(err => {
          if (!cancelled) setPlaceSuggestions([]);
          console.warn("[data-store-map] Place suggestions failed", err);
        })
        .finally(() => {
          if (!cancelled) setPlacesBusy(false);
        });
    }, 260);

    return () => {
      cancelled = true;
      window.clearTimeout(timer);
    };
  }, [q]);

  const selectCounty = (countyName, stateName) => {
    const next = { countyName, stateName };
    setSelectedCounty(next);
    setSearchOpen(false);
    setSearchMessage("");
    setQ(dataStoreSearchLabelForCounty(countyName, stateName));
    onCounty(countyName, stateName);
  };

  const clearCountySelection = () => {
    const nextStateName = selectedCounty?.stateName;
    setSelectedCounty(null);
    setSearchOpen(false);
    setSearchMessage("");
    setQ("");
    if (nextStateName) onState(nextStateName);
    else onBrowse();
  };

  const openSearchResult = async (result) => {
    if (!result) return;
    setQ(result.label);
    setSearchOpen(false);
    setSearchMessage("");
    if (result.type === "state") {
      onState(result.stateName);
      return;
    }
    if (result.type === "county") {
      selectCounty(result.countyName, result.stateName);
      return;
    }
    if (result.type === "place") {
      setSearchBusy(true);
      try {
        const countyResult = await dataStoreCountySearchResultForLngLat(result.center[0], result.center[1]);
        if (countyResult) {
          selectCounty(countyResult.countyName, countyResult.stateName);
          return;
        }
        setSearchMessage("No matching county found");
        setSearchOpen(true);
      } catch (err) {
        console.warn("[data-store-map] Place search failed", err);
        setSearchMessage("Search unavailable");
        setSearchOpen(true);
      } finally {
        setSearchBusy(false);
      }
    }
  };

  const handleSearchSubmit = async (event) => {
    event.preventDefault();
    const query = q.trim();
    if (!query || searchBusy) return;

    const localResult = dataStoreBestLocalSearchResult(query);
    if (localResult) {
      openSearchResult(localResult);
      return;
    }

    setSearchBusy(true);
    setSearchMessage("");
    try {
      const mapboxResult = await dataStoreMapboxCountySearch(query);
      if (mapboxResult) {
        setSearchBusy(false);
        openSearchResult(mapboxResult);
        return;
      }
      setSearchMessage("No matching county found");
      setSearchOpen(true);
    } catch (err) {
      console.warn("[data-store-map] Search failed", err);
      setSearchMessage("Search unavailable");
      setSearchOpen(true);
    } finally {
      setSearchBusy(false);
    }
  };

  const handleSearchChange = (event) => {
    setQ(event.target.value);
    setSearchMessage("");
    setPlaceSuggestions([]);
    setSearchOpen(true);
  };

  return (
    <div className="landai-store-shell" style={{ width: W, height: STORE_PAGE_HEIGHT, margin: "0 auto", background: PAPER, fontFamily: "'Hanken Grotesk', system-ui, sans-serif", overflow: "hidden", boxShadow: "0 40px 120px rgba(16,40,30,0.18)", display: "flex", flexDirection: "column" }}>
      <Nav onHome={onHome} onBrowse={onBrowse} />
      <div className="landai-store-split" style={{ display: "flex", alignItems: "stretch", flex: 1, minHeight: 0 }}>
        {/* LEFT column — scrolls */}
        <div className="landai-store-left" style={{ width: "min(720px, 100%)", flexShrink: 0, padding: selectedCounty ? "30px 44px 64px" : "40px 44px 64px", boxSizing: "border-box", overflowY: "auto", height: "100%" }}>
          {selectedCounty ? (
            <BrowseCountyPanel
              countyName={selectedCounty.countyName}
              stateName={selectedCounty.stateName}
              onBack={clearCountySelection}
              onCounty={selectCounty}
              onAdd={onAdd}
            />
          ) : (
            <>
              <div onClick={onHome} style={{ display: "inline-flex", alignItems: "center", gap: 7, color: GREEN, fontSize: 14, fontWeight: 700, cursor: "pointer", marginBottom: 22 }}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={GREEN} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6" /></svg>
                Back to overview
              </div>
              <h1 style={{ fontSize: 38, fontWeight: 800, color: INK, letterSpacing: -1, margin: 0 }}>The LandAI Data Store</h1>
              <div style={{ fontSize: 18, color: GRAY, marginTop: 8 }}>Buy U.S. parcel data by the county or the whole state.</div>
              <p style={{ fontSize: 15, color: GRAY, lineHeight: 1.6, marginTop: 22 }}>
                We cover 2,170+ supported counties and 136M+ parcel records, available three ways: <span style={{ color: GREEN, fontWeight: 600 }}>bulk licenses</span>, an <span style={{ color: GREEN, fontWeight: 600 }}>API</span>, and this <strong style={{ color: INK }}>self-serve store</strong>. Grab a single county file or license an entire state right here.
              </p>
              {/* stat cards */}
              <div className="landai-stat-strip" style={{ display: "flex", gap: 8, marginTop: 24, borderRadius: 10, overflow: "hidden" }}>
                {STATS.map(([n, l], i) => <StatCard key={i} n={n} label={l} last={i === STATS.length - 1} />)}
              </div>
              <p style={{ fontSize: 15, color: GRAY, lineHeight: 1.6, marginTop: 24 }}>
                Tap a county on the map, or find one in the list or search bar, to see which fields are available, then pay by card or ACH under our <span style={{ color: GREEN, fontWeight: 600 }}>standard store license</span>.
              </p>

              <div style={{ marginTop: 40 }}>
                <h3 style={{ fontSize: 20, fontWeight: 700, color: INK, margin: "0 0 10px" }}>Data documentation</h3>
                <p style={{ fontSize: 15, color: GRAY, lineHeight: 1.6, margin: 0 }}>
                  We gather and refresh county records from across the country and fit them into one consistent schema. Check the field dictionary, coverage report, and FAQs before you buy.
                </p>
                <div className="landai-doc-buttons" style={{ display: "flex", gap: 12, marginTop: 22 }}>
                  <DocButton onClick={() => onSupport("schema")}>Parcel Schema / Data Dictionary</DocButton>
                  <DocButton onClick={() => onSupport("coverage")}>Detailed Coverage Report</DocButton>
                  <DocButton onClick={() => onSupport("faqs")}>Parcel Data FAQs</DocButton>
                </div>
              </div>

              <div style={{ marginTop: 36, background: MINT, borderRadius: 14, padding: "22px 24px" }}>
                <h3 style={{ fontSize: 18, fontWeight: 700, color: GREEN_DK, margin: "0 0 8px" }}>Need the whole country?</h3>
                <p style={{ fontSize: 15, color: GRAY, lineHeight: 1.6, margin: 0 }}>
                  For nationwide bulk data, API access, or more than 3 states at once, email our team at <span style={{ color: GREEN, fontWeight: 600 }}>parcels@landai.app</span> and we'll set you up.
                </p>
              </div>

              <div style={{ marginTop: 44 }}>
                <h3 style={{ fontSize: 22, fontWeight: 700, color: INK, margin: "0 0 8px" }}>Parcel data by state</h3>
                <p style={{ fontSize: 15, color: GRAY, lineHeight: 1.5, margin: "0 0 22px" }}>Jump straight to a state or county from the map and search bar, or pick a state to see all of its counties.</p>
                <div className="landai-state-list" style={{ columns: 2, columnGap: 40 }}>
                  {STATES.map((s, i) => (
                    <div key={i} onClick={() => onState(s)} style={{ breakInside: "avoid", padding: "13px 0", borderBottom: `1px solid ${BORDER}`, fontSize: 16, fontWeight: 700, color: GREEN_DK, cursor: "pointer" }}>{s}</div>
                  ))}
                </div>
              </div>
            </>
          )}
        </div>

        {/* RIGHT column — fixed map */}
        <div className="landai-store-map" style={{ flex: 1, height: "100%", background: "#e9edee", position: "relative" }}>
          <BrowseMapboxMap onCounty={selectCounty} selectedCounty={selectedCounty} />
          {/* top controls */}
          <div className="landai-map-controls" style={{ position: "absolute", top: 22, left: 24, right: 24, display: "flex", alignItems: "flex-start", gap: 16, zIndex: 2 }}>
            <div className="landai-map-search" style={{ position: "relative", flex: 1, maxWidth: 360 }}>
              <form onSubmit={handleSearchSubmit} style={{ background: "#fff", borderRadius: 12, padding: "0 16px", minHeight: 48, display: "flex", alignItems: "center", gap: 10, boxShadow: "0 6px 20px rgba(16,40,30,0.15)", border: searchOpen && q ? `1px solid ${GREEN}` : "1px solid rgba(255,255,255,0.72)", boxSizing: "border-box" }}>
                <button type="submit" aria-label="Search map" disabled={searchBusy} style={{ border: "none", background: "transparent", padding: 0, width: 18, height: 18, display: "flex", alignItems: "center", justifyContent: "center", cursor: searchBusy ? "default" : "pointer", flexShrink: 0 }}>
                  {searchBusy ? (
                    <span style={{ width: 9, height: 9, borderRadius: 99, background: GREEN, boxShadow: "0 0 0 5px rgba(46,107,240,0.14)" }} />
                  ) : (
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#8a948f" strokeWidth="2.4"><circle cx="11" cy="11" r="7" /><path d="m20 20-3-3" /></svg>
                  )}
                </button>
                <input value={q} onChange={handleSearchChange} onFocus={() => setSearchOpen(true)} onBlur={() => window.setTimeout(() => setSearchOpen(false), 140)} placeholder="Find a city, state, or county" autoComplete="off" style={{ border: "none", outline: "none", fontSize: 15, color: INK, fontFamily: "inherit", width: "100%", background: "transparent", minWidth: 0 }} />
              </form>
              <div className="landai-map-legend" style={{ marginTop: 8, width: "fit-content", maxWidth: "100%", background: "#fff", borderRadius: 10, padding: "9px 12px", display: "flex", gap: 13, alignItems: "center", flexWrap: "wrap", boxShadow: "0 6px 20px rgba(16,40,30,0.15)", border: "1px solid rgba(255,255,255,0.72)", fontSize: 12.5, color: INK, fontWeight: 700 }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6, whiteSpace: "nowrap" }}><span style={{ width: 12, height: 12, borderRadius: 3, background: SUPPORTED_COUNTY_COMPLETE_COLOR }} />LandAI supported</span>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6, whiteSpace: "nowrap" }}><span style={{ width: 12, height: 12, borderRadius: 3, background: SUPPORTED_COUNTY_PREMIUM_COLOR }} />No data</span>
              </div>
              {searchOpen && q.trim() && (searchSuggestions.length > 0 || placesBusy || searchMessage) && (
                <div style={{ position: "absolute", top: "calc(100% + 8px)", left: 0, right: 0, background: "#fff", borderRadius: 8, overflow: "hidden", boxShadow: "0 18px 42px rgba(16,40,30,0.2)", border: `1px solid ${BORDER}`, zIndex: 30 }}>
                  {searchSuggestions.map((item, i) => (
                    <button key={`${item.type}-${item.id || item.stateName}-${item.countyName || item.label}`} type="button" onMouseDown={(event) => { event.preventDefault(); openSearchResult(item); }} style={{ width: "100%", border: "none", borderBottom: i < searchSuggestions.length - 1 || placesBusy || searchMessage ? `1px solid ${BORDER}` : "none", background: "#fff", padding: "11px 14px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, cursor: "pointer", fontFamily: "inherit", textAlign: "left" }}>
                      <span style={{ fontSize: 14, fontWeight: 800, color: INK, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{item.label}</span>
                      <span style={{ fontSize: 12, fontWeight: 700, color: "#8a948f", flexShrink: 0 }}>{item.detail}</span>
                    </button>
                  ))}
                  {placesBusy && <div style={{ padding: "11px 14px", fontSize: 13, fontWeight: 700, color: GRAY }}>Searching places...</div>}
                  {searchMessage && <div style={{ padding: "11px 14px", fontSize: 13, fontWeight: 700, color: GRAY }}>{searchMessage}</div>}
                </div>
              )}
            </div>
            <div onClick={onCart} style={{ position: "relative", width: 44, height: 44, borderRadius: 12, background: "#fff", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 6px 20px rgba(16,40,30,0.15)", cursor: "pointer" }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={GREEN_DK} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="9" cy="21" r="1" /><circle cx="20" cy="21" r="1" /><path d="M1 1h4l2.7 13.4a2 2 0 0 0 2 1.6h9.7a2 2 0 0 0 2-1.6L23 6H6" /></svg>
              {cartCount > 0 && <span style={{ position: "absolute", top: -5, right: -5, minWidth: 18, height: 18, padding: "0 5px", borderRadius: 99, background: GREEN, color: "#fff", fontSize: 11, fontWeight: 700, display: "flex", alignItems: "center", justifyContent: "center" }}>{cartCount}</span>}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- STATE DETAIL VIEW ----------
const FALLBACK_COUNTIES_BY_STATE = {
  "North Carolina": ["Alamance County"]
};
const COUNTIES_BY_STATE = window.LANDAI_COUNTIES_BY_STATE || FALLBACK_COUNTIES_BY_STATE;

const STATE_CODES = {
  "Alabama": "al",
  "Alaska": "ak",
  "Arizona": "az",
  "Arkansas": "ar",
  "California": "ca",
  "Colorado": "co",
  "Connecticut": "ct",
  "Delaware": "de",
  "District of Columbia": "dc",
  "Florida": "fl",
  "Georgia": "ga",
  "Guam": "gu",
  "Hawaii": "hi",
  "Idaho": "id",
  "Illinois": "il",
  "Indiana": "in",
  "Iowa": "ia",
  "Kansas": "ks",
  "Kentucky": "ky",
  "Louisiana": "la",
  "Maine": "me",
  "Maryland": "md",
  "Massachusetts": "ma",
  "Michigan": "mi",
  "Minnesota": "mn",
  "Mississippi": "ms",
  "Missouri": "mo",
  "Montana": "mt",
  "Nebraska": "ne",
  "Nevada": "nv",
  "New Hampshire": "nh",
  "New Jersey": "nj",
  "New Mexico": "nm",
  "New York": "ny",
  "North Carolina": "nc",
  "North Dakota": "nd",
  "Northern Mariana Islands": "mp",
  "Ohio": "oh",
  "Oklahoma": "ok",
  "Oregon": "or",
  "Pennsylvania": "pa",
  "Puerto Rico": "pr",
  "Rhode Island": "ri",
  "South Carolina": "sc",
  "South Dakota": "sd",
  "Tennessee": "tn",
  "Texas": "tx",
  "U.S. Virgin Islands": "vi",
  "Utah": "ut",
  "Vermont": "vt",
  "Virginia": "va",
  "Washington": "wa",
  "West Virginia": "wv",
  "Wisconsin": "wi",
  "Wyoming": "wy"
};
const CODE_TO_STATE = Object.fromEntries(Object.entries(STATE_CODES).map(([name, code]) => [code, name]));
const STATE_FIPS_TO_NAME = {
  "01": "Alabama",
  "02": "Alaska",
  "04": "Arizona",
  "05": "Arkansas",
  "06": "California",
  "08": "Colorado",
  "09": "Connecticut",
  "10": "Delaware",
  "11": "District of Columbia",
  "12": "Florida",
  "13": "Georgia",
  "15": "Hawaii",
  "16": "Idaho",
  "17": "Illinois",
  "18": "Indiana",
  "19": "Iowa",
  "20": "Kansas",
  "21": "Kentucky",
  "22": "Louisiana",
  "23": "Maine",
  "24": "Maryland",
  "25": "Massachusetts",
  "26": "Michigan",
  "27": "Minnesota",
  "28": "Mississippi",
  "29": "Missouri",
  "30": "Montana",
  "31": "Nebraska",
  "32": "Nevada",
  "33": "New Hampshire",
  "34": "New Jersey",
  "35": "New Mexico",
  "36": "New York",
  "37": "North Carolina",
  "38": "North Dakota",
  "39": "Ohio",
  "40": "Oklahoma",
  "41": "Oregon",
  "42": "Pennsylvania",
  "44": "Rhode Island",
  "45": "South Carolina",
  "46": "South Dakota",
  "47": "Tennessee",
  "48": "Texas",
  "49": "Utah",
  "50": "Vermont",
  "51": "Virginia",
  "53": "Washington",
  "54": "West Virginia",
  "55": "Wisconsin",
  "56": "Wyoming"
};
const SUPPORT_DOCS = new Set(["start", "schema", "coverage", "license", "faqs"]);
const STORE_BASE = "/data-store";

function safeDecode(value) {
  try { return decodeURIComponent(value); }
  catch { return value; }
}

function slugify(value) {
  return String(value || "")
    .trim()
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .toLowerCase()
    .replace(/&/g, " and ")
    .replace(/u\.s\./g, "us")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

function titleFromSlug(slug) {
  return String(slug || "")
    .split("-")
    .filter(Boolean)
    .map(part => part.charAt(0).toUpperCase() + part.slice(1))
    .join(" ");
}

function countiesForState(stateName) {
  return COUNTIES_BY_STATE[stateName] || [];
}

function stateCodeForName(stateName) {
  return STATE_CODES[stateName] || "";
}

function stateNameForSlug(slug) {
  const clean = slugify(slug);
  return CODE_TO_STATE[clean] || STATES.find(state => slugify(state) === clean) || "";
}

function countyNameForSlug(stateName, slug) {
  const clean = slugify(slug);
  return countiesForState(stateName).find(county => countySlug(county) === clean || slugify(county) === clean) || titleFromSlug(clean);
}

function countySlug(countyName) {
  const shortened = String(countyName || "")
    .replace(/\s+(county|parish|borough|municipality|census area|municipio)$/i, "")
    .trim();
  return slugify(shortened || countyName);
}

function normalizeDoc(doc) {
  return SUPPORT_DOCS.has(doc) ? doc : "schema";
}

function normalizeStoreRoute(route, fallback = {}) {
  return {
    view: route.view || fallback.view || "landing",
    stateName: route.stateName || fallback.stateName || "North Carolina",
    countyName: route.countyName || fallback.countyName || "Alamance",
    supportDoc: normalizeDoc(route.supportDoc || fallback.supportDoc || "schema")
  };
}

function dataStorePath(view, stateName, countyName, supportDoc) {
  if (view === "browse") return `${STORE_BASE}/browse`;
  if (view === "cart") return `${STORE_BASE}/cart`;
  if (view === "checkoutSuccess") return `${STORE_BASE}/checkout/success`;
  if (view === "support") return `${STORE_BASE}/docs/${normalizeDoc(supportDoc)}`;

  const stateCode = stateCodeForName(stateName) || slugify(stateName) || "nc";
  if (view === "state") return `${STORE_BASE}/${stateCode}`;
  if (view === "coverage") return `${STORE_BASE}/${stateCode}/coverage`;
  if (view === "browseCounty") return `${STORE_BASE}/${stateCode}/${countySlug(countyName) || "alamance"}`;
  if (view === "county") return `${STORE_BASE}/${stateCode}/${countySlug(countyName) || "alamance"}`;
  return STORE_BASE;
}

function readDataStoreRoute() {
  const parts = window.location.pathname.split("/").filter(Boolean).map(safeDecode);
  const storeIndex = parts.findIndex(part => ["data-store", "datastore", "date-store"].includes(slugify(part)));
  if (storeIndex < 0) return normalizeStoreRoute({});

  const segments = parts.slice(storeIndex + 1).map(slugify);
  const [first, second] = segments;
  if (!first) return normalizeStoreRoute({});
  if (first === "browse") return normalizeStoreRoute({ view: "browse" });
  if (first === "cart") return normalizeStoreRoute({ view: "cart" });
  if (first === "checkout" && second === "success") return normalizeStoreRoute({ view: "checkoutSuccess" });
  if (first === "docs" || first === "support") return normalizeStoreRoute({ view: "support", supportDoc: normalizeDoc(second) });

  const stateName = stateNameForSlug(first);
  if (!stateName) return normalizeStoreRoute({ view: "browse" });
  if (second === "coverage") return normalizeStoreRoute({ view: "coverage", stateName });
  if (second) return normalizeStoreRoute({ view: "browseCounty", stateName, countyName: countyNameForSlug(stateName, second) });
  return normalizeStoreRoute({ view: "state", stateName });
}

function hashStr(s) { let h = 0; for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0; return h; }
function countyInfo(name) {
  const h = hashStr(name);
  const parcels = 6000 + (h % 410000);
  const mo = String(1 + (h % 6)).padStart(2, "0");
  const da = String(1 + (h % 27)).padStart(2, "0");
  return { parcels, date: `2026-${mo}-${da}`, price: COUNTY_STORE_PRICE };
}

function CountyIcon({ feature }) {
  const path = dataStoreFeatureSvgPath(feature);
  return (
    <svg width="40" height="40" viewBox="0 0 40 40" style={{ flexShrink: 0 }}>
      <rect width="40" height="40" rx="9" fill="#e7efe9" />
      <path d="M -2 26 Q 10 21 20 26 T 44 24" stroke="#cdebd3" strokeWidth="3" fill="none" />
      {path ? (
        <path d={path} fill={GREEN} fillOpacity="0.17" fillRule="evenodd" stroke={GREEN} strokeWidth="1.4" strokeLinejoin="round" />
      ) : (
        <g stroke={GREEN} strokeWidth="1.4" fill={GREEN} fillOpacity="0.14"><path d="M 10 10 L 23 9 L 24 21 L 11 22 Z" /></g>
      )}
    </svg>
  );
}

function CountyRow({ name, feature, loading, onOpen, onAdd }) {
  const info = countyInfo(name);
  const meta = feature ? dataStoreCountyMetadataFromFeature(feature) : null;
  const supported = dataStoreCountyIsSupported(feature);
  const purchasable = !loading && supported;
  const parcelLabel = supported ? dataStoreCountyParcelCountLabel(meta, loading) : "";
  const dataDate = supported ? dataStoreCountyDataDateLabel(meta, loading) : "";
  const detailParts = [];
  if (loading) detailParts.push("Loading coverage...");
  else if (!supported) detailParts.push("Not supported");
  else {
    detailParts.push(`${parcelLabel} parcels`);
    if (dataDate && dataDate !== "Unknown") detailParts.push(`data date ${dataDate}`);
    else detailParts.push("data date unknown");
  }
  const records = meta?.parcelCount ? meta.parcelCount.toLocaleString() : info.parcels.toLocaleString();
  const rowColor = purchasable ? GREEN_DK : "#7d8581";
  const muted = !purchasable;
  return (
    <div className="landai-county-row" onClick={purchasable ? onOpen : undefined} style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 0", borderBottom: `1px solid ${BORDER}`, cursor: purchasable ? "pointer" : "default", opacity: muted ? 0.72 : 1 }}>
      <div style={{ filter: muted ? "grayscale(1)" : "none", opacity: muted ? 0.55 : 1 }}><CountyIcon feature={feature} /></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 16, fontWeight: 700, color: rowColor, letterSpacing: -0.2 }}>{name}</div>
        <div style={{ fontSize: 12.5, color: GRAY, marginTop: 2, fontFamily: "'JetBrains Mono', monospace" }}>{detailParts.join(" · ")}</div>
      </div>
      <div className="landai-county-row-actions" style={{ display: "flex", alignItems: "center", gap: 12, flexShrink: 0 }}>
        <span style={{ fontSize: 15, fontWeight: 700, color: purchasable ? INK : "#a7aaa5" }}>{loading ? "..." : purchasable ? `$${info.price}` : "$--"}</span>
        <button disabled={!purchasable} onClick={e => { e.stopPropagation(); if (purchasable && onAdd) onAdd(name, info.price, records); }} style={{ border: `1.5px solid ${purchasable ? GREEN : "#b8bbb6"}`, background: purchasable ? "#fff" : "#eeeeea", color: purchasable ? GREEN : "#a0a49f", fontWeight: 700, fontSize: 13, padding: "8px 16px", borderRadius: 99, cursor: purchasable ? "pointer" : "not-allowed", fontFamily: "inherit" }}>Add</button>
      </div>
    </div>
  );
}

function StateMapboxMap({ stateName, onCounty }) {
  const mapNode = useRef(null);
  const mapRef = useRef(null);
  const stateNameRef = useRef(stateName);
  const onCountyRef = useRef(onCounty);
  const [status, setStatus] = useState("loading");

  useEffect(() => {
    stateNameRef.current = stateName;
  }, [stateName]);

  useEffect(() => {
    onCountyRef.current = onCounty;
  }, [onCounty]);

  useEffect(() => {
    const map = mapRef.current;
    if (!map || status !== "ready") return undefined;
    let cancelled = false;
    loadDataStoreCoverageGeoJSON()
      .then(geojson => {
        if (cancelled) return false;
        dataStoreSetStateOutlineOnMap(map, geojson, stateName);
        return dataStoreFitMapToState(map, stateName, 650);
      })
      .then(didFit => {
        if (!cancelled && !didFit) console.warn("[data-store-state-map] State bounds unavailable", stateName);
      })
      .catch(err => console.warn("[data-store-state-map] State zoom failed", err));
    return () => {
      cancelled = true;
    };
  }, [stateName, status]);

  useEffect(() => {
    const node = mapNode.current;
    if (!node || mapRef.current) return undefined;

    const mapboxgl = window.mapboxgl;
    if (!mapboxgl) {
      setStatus("missing-script");
      return undefined;
    }

    const token = String(window.MAPBOX_ACCESS_TOKEN || "").trim();
    if (!token) {
      setStatus("missing-token");
      return undefined;
    }

    mapboxgl.accessToken = token;

    const style = String(window.LANDAI_MAPBOX_STYLE || "").trim() || "mapbox://styles/mapbox/light-v11";
    if (typeof mapboxgl.supported === "function" && !mapboxgl.supported()) {
      setStatus("webgl-error");
      return undefined;
    }

    let map;
    try {
      map = new mapboxgl.Map({
        container: node,
        style,
        center: [-98.6, 39.6],
        zoom: 3.4,
        minZoom: 2.2,
        maxZoom: 15,
        attributionControl: true,
        cooperativeGestures: false,
        scrollZoom: true,
      });
    } catch (err) {
      setStatus("webgl-error");
      console.warn("[data-store-state-map] Mapbox initialization failed", err);
      return undefined;
    }

    mapRef.current = map;
    const countyHoverPopup = new mapboxgl.Popup({
      closeButton: false,
      closeOnClick: false,
      maxWidth: "240px",
      offset: 12,
    });

    map.addControl(new mapboxgl.NavigationControl({ showCompass: false }), "bottom-right");
    map.addControl(new mapboxgl.ScaleControl({ maxWidth: 120, unit: "imperial" }), "bottom-left");

    const resize = () => {
      try { map.resize(); }
      catch (_) { /* noop */ }
    };

    map.on("load", () => {
      addDataStoreCoverageOverlay(map)
        .then(geojson => {
          dataStoreSetStateOutlineOnMap(map, geojson, stateNameRef.current);
          node.dataset.coverageOverlayReady = "1";
          setStatus("ready");
          dataStoreFitMapToState(map, stateNameRef.current, 0);
        })
        .catch(err => {
          node.dataset.coverageOverlayReady = "error";
          setStatus("coverage-error");
          console.warn("[data-store-state-map] County coverage overlay failed", err);
        });

      resize();
      setTimeout(resize, 150);
      setTimeout(resize, 450);
    });

    map.on("mouseenter", DATA_STORE_COVERAGE_FILL_LAYER_ID, () => {
      map.getCanvas().style.cursor = "pointer";
    });

    map.on("mousemove", DATA_STORE_COVERAGE_FILL_LAYER_ID, event => {
      const feature = event.features && event.features[0];
      if (!feature) return;
      const fips = countyFipsFromFeature(feature);
      const featureStateName = stateNameForCountyFips(fips) || feature?.properties?.STATE_NAME || "";
      if (slugify(featureStateName) !== slugify(stateNameRef.current)) {
        countyHoverPopup.remove();
        return;
      }
      const countyName = displayCountyNameForFeature(feature, featureStateName);
      if (!countyName) return;
      countyHoverPopup
        .setLngLat(event.lngLat)
        .setHTML(dataStoreCountyTooltipHtml(countyName))
        .addTo(map);
    });

    map.on("mouseleave", DATA_STORE_COVERAGE_FILL_LAYER_ID, () => {
      map.getCanvas().style.cursor = "";
      countyHoverPopup.remove();
    });

    map.on("click", DATA_STORE_COVERAGE_FILL_LAYER_ID, event => {
      const feature = event.features && event.features[0];
      if (!feature) return;
      const fips = countyFipsFromFeature(feature);
      const featureStateName = stateNameForCountyFips(fips) || feature?.properties?.STATE_NAME || "";
      if (slugify(featureStateName) !== slugify(stateNameRef.current)) return;
      if (!dataStoreCountyIsSupported(feature)) return;
      const countyName = displayCountyNameForFeature(feature, featureStateName);
      if (!countyName || !onCountyRef.current) return;
      countyHoverPopup.remove();
      dataStoreSetSelectedCountyOnMap(map, feature);
      dataStoreFitMapToFeature(map, feature);
      onCountyRef.current(countyName, featureStateName);
    });

    return () => {
      mapRef.current = null;
      countyHoverPopup.remove();
      map.remove();
    };
  }, []);

  return (
    <div style={{ position: "absolute", inset: 0, background: "#e9edee" }}>
      <div ref={mapNode} style={{ position: "absolute", inset: 0 }} />
      {status !== "ready" && (
        <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", textAlign: "center", padding: 28, background: "rgba(233,237,238,0.86)", backdropFilter: "blur(2px)", color: GRAY, fontSize: 13, lineHeight: 1.55, fontFamily: "'JetBrains Mono', monospace" }}>
          {status === "missing-token" ? (
            <span>Mapbox needs a public access token.<br />Set <strong style={{ color: INK }}>MAPBOX_ACCESS_TOKEN</strong> for this environment.</span>
          ) : status === "missing-script" ? (
            <span>Mapbox GL did not load.</span>
          ) : status === "webgl-error" ? (
            <span>Map needs WebGL to display.</span>
          ) : status === "coverage-error" ? (
            <span>County coverage could not load.<br />Please refresh the page.</span>
          ) : (
            <div style={{ minWidth: 230, borderRadius: 8, background: "#fff", boxShadow: "0 18px 42px rgba(16,40,30,0.16)", padding: "18px 20px", display: "flex", alignItems: "center", justifyContent: "center", gap: 11 }}>
              <span style={{ width: 10, height: 10, borderRadius: 99, background: SUPPORTED_COUNTY_COMPLETE_COLOR, boxShadow: "0 0 0 6px rgba(52,199,89,0.16)" }} />
              <span>Loading {stateName} map...</span>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function MapControls({ q, setQ, onCart, cartCount }) {
  return (
    <div className="landai-map-controls" style={{ position: "absolute", top: 22, left: 24, right: 24, display: "flex", alignItems: "center", gap: 16, zIndex: 2 }}>
      <div className="landai-map-search" style={{ flex: 1, maxWidth: 340, background: "#fff", borderRadius: 12, padding: "13px 18px", display: "flex", alignItems: "center", gap: 10, boxShadow: "0 6px 20px rgba(16,40,30,0.15)" }}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#8a948f" strokeWidth="2.4"><circle cx="11" cy="11" r="7" /><path d="m20 20-3-3" /></svg>
        <input value={q} onChange={e => setQ(e.target.value)} placeholder="Find a state or county" style={{ border: "none", outline: "none", fontSize: 15, color: INK, fontFamily: "inherit", width: "100%", background: "transparent" }} />
      </div>
      <div className="landai-map-legend" style={{ display: "flex", gap: 14, alignItems: "center", fontSize: 13, color: INK, fontWeight: 600, background: "#fff", borderRadius: 10, padding: "9px 12px", boxShadow: "0 6px 20px rgba(16,40,30,0.15)" }}>
        <span style={{ display: "flex", alignItems: "center", gap: 6 }}><span style={{ width: 12, height: 12, borderRadius: 3, background: SUPPORTED_COUNTY_COMPLETE_COLOR }} />LandAI supported</span>
        <span style={{ display: "flex", alignItems: "center", gap: 6 }}><span style={{ width: 12, height: 12, borderRadius: 3, background: SUPPORTED_COUNTY_PREMIUM_COLOR }} />No data</span>
      </div>
      <div onClick={onCart} style={{ position: "relative", width: 44, height: 44, borderRadius: 12, background: "#fff", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 6px 20px rgba(16,40,30,0.15)", cursor: "pointer" }}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={GREEN_DK} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="9" cy="21" r="1" /><circle cx="20" cy="21" r="1" /><path d="M1 1h4l2.7 13.4a2 2 0 0 0 2 1.6h9.7a2 2 0 0 0 2-1.6L23 6H6" /></svg>
        {cartCount > 0 && <span style={{ position: "absolute", top: -5, right: -5, minWidth: 18, height: 18, padding: "0 5px", borderRadius: 99, background: GREEN, color: "#fff", fontSize: 11, fontWeight: 700, display: "flex", alignItems: "center", justifyContent: "center" }}>{cartCount}</span>}
      </div>
    </div>
  );
}

function StateView({ stateName, onHome, onBrowse, onBack, onCounty, onCoverage, onBuy, onAdd, onCart, cartCount }) {
  const [q, setQ] = useState("");
  const [countyFilter, setCountyFilter] = useState("all");
  const [countySort, setCountySort] = useState("supported");
  const counties = countiesForState(stateName);
  const [stateCoverage, setStateCoverage] = useState({ loading: true, featuresBySlug: new Map(), stats: null });

  useEffect(() => {
    let cancelled = false;
    setStateCoverage({ loading: true, featuresBySlug: new Map(), stats: null });
    loadDataStoreCoverageGeoJSON()
      .then(geojson => {
        if (cancelled) return;
        const featuresBySlug = new Map();
        (geojson?.features || []).forEach(feature => {
          const fips = countyFipsFromFeature(feature);
          const featureStateName = stateNameForCountyFips(fips) || feature?.properties?.STATE_NAME || "";
          if (slugify(featureStateName) !== slugify(stateName)) return;
          const countyName = displayCountyNameForFeature(feature, stateName);
          if (countyName) featuresBySlug.set(countySlug(countyName), feature);
        });

        let parcelTotal = 0;
        let supportedCount = 0;
        let latestDate = "";
        let latestTime = 0;
        counties.forEach(county => {
          const feature = featuresBySlug.get(countySlug(county));
          if (!feature) return;
          const meta = dataStoreCountyMetadataFromFeature(feature);
          parcelTotal += meta.parcelCount || 0;
          if (dataStoreCountyIsSupported(feature)) supportedCount += 1;
          const dateLabel = dataStoreCountyDataDateLabel(meta, false);
          const parsed = Date.parse(dateLabel);
          if (!Number.isNaN(parsed) && parsed > latestTime) {
            latestTime = parsed;
            latestDate = dateLabel;
          }
        });

        const totalCount = counties.length || featuresBySlug.size;
        const stats = [
          ["Parcels", parcelTotal ? parcelTotal.toLocaleString() : "Unknown"],
          ["Counties online", `${supportedCount} / ${totalCount}`],
          ["Latest data date", latestDate || "Unknown"],
          ["Not supported", Math.max(totalCount - supportedCount, 0).toLocaleString()],
        ];
        setStateCoverage({ loading: false, featuresBySlug, stats });
      })
      .catch(err => {
        console.warn("[data-store-state] State coverage unavailable", err);
        if (!cancelled) setStateCoverage({ loading: false, featuresBySlug: new Map(), stats: null });
      });
    return () => {
      cancelled = true;
    };
  }, [stateName]);

  const stats = stateCoverage.stats || [
    ["Parcels", "Loading..."],
    ["Counties online", `Loading... / ${counties.length || "..."}`],
    ["Latest data date", "Loading..."],
    ["Not supported", "Loading..."],
  ];
  const countyRows = counties.map(county => {
    const feature = stateCoverage.featuresBySlug.get(countySlug(county));
    const supported = dataStoreCountyIsSupported(feature);
    return { county, feature, supported };
  });
  const supportedRows = countyRows.filter(row => row.supported);
  const unsupportedRows = stateCoverage.loading ? [] : countyRows.filter(row => !row.supported);
  const statewidePrice = supportedRows.length * STATE_STORE_PRICE_PER_SUPPORTED_COUNTY;
  const stateBuyDisabled = stateCoverage.loading || supportedRows.length === 0;
  const visibleCountyRows = countyRows
    .filter(row => {
      if (stateCoverage.loading) return true;
      if (countyFilter === "supported") return row.supported;
      if (countyFilter === "unsupported") return !row.supported;
      return true;
    })
    .sort((a, b) => {
      if (countySort === "supported" && !stateCoverage.loading) {
        if (a.supported !== b.supported) return a.supported ? -1 : 1;
      }
      return a.county.localeCompare(b.county);
    });
  return (
    <div className="landai-store-shell" style={{ width: W, height: STORE_PAGE_HEIGHT, margin: "0 auto", background: PAPER, fontFamily: "'Hanken Grotesk', system-ui, sans-serif", overflow: "hidden", boxShadow: "0 40px 120px rgba(16,40,30,0.18)", display: "flex", flexDirection: "column" }}>
      <Nav onHome={onHome} onBrowse={onBrowse} />
      <div className="landai-store-split" style={{ display: "flex", alignItems: "stretch", flex: 1, minHeight: 0 }}>
        <div className="landai-store-left" style={{ width: "min(720px, 100%)", flexShrink: 0, padding: "34px 44px 64px", boxSizing: "border-box", overflowY: "auto", height: "100%" }}>
          <div onClick={onBack} style={{ display: "inline-flex", alignItems: "center", gap: 7, color: GREEN, fontSize: 14, fontWeight: 700, cursor: "pointer", marginBottom: 18 }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={GREEN} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6" /></svg>
            Back to data store
          </div>
          <h1 style={{ fontSize: 34, fontWeight: 800, color: INK, letterSpacing: -1, margin: 0 }}>{stateName} Parcel Data</h1>
          <div className="landai-state-stats" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "18px 40px", marginTop: 24 }}>
            {stats.map(([label, val], i) => (
              <div key={i}>
                <div style={{ fontSize: 26, fontWeight: 800, color: GREEN_DK, letterSpacing: -0.6, fontFamily: "'JetBrains Mono', monospace" }}>{val}</div>
                <div style={{ fontSize: 13, color: GRAY, marginTop: 2, fontWeight: 600 }}>{label}</div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 30, background: CREAM, borderRadius: 14, padding: "20px 22px" }}>
            <div style={{ fontSize: 17, fontWeight: 700, color: GREEN_DK, marginBottom: 4 }}>Statewide data</div>
            <div style={{ fontSize: 14, color: GRAY, marginBottom: 16 }}>Get every supported county in {stateName} in a single purchase, refreshed on a rolling schedule.</div>
            <div className="landai-state-actions" style={{ display: "flex", gap: 12 }}>
              <button disabled={stateBuyDisabled} onClick={onBuy} style={{ border: "none", background: stateBuyDisabled ? "#a7aaa5" : CORAL, color: "#fff", fontSize: 14, fontWeight: 700, padding: "13px 24px", borderRadius: 10, cursor: stateBuyDisabled ? "not-allowed" : "pointer", fontFamily: "inherit", letterSpacing: 0.3 }}>
                {stateCoverage.loading ? "Loading state price..." : supportedRows.length ? `Buy the entire state - ${formatStoreCurrency(statewidePrice)}` : "State not available"}
              </button>
              <button onClick={onCoverage} style={{ border: `1.5px solid ${GREEN_DK}`, background: "#fff", color: GREEN_DK, fontSize: 14, fontWeight: 700, padding: "13px 24px", borderRadius: 10, cursor: "pointer", fontFamily: "inherit" }}>Coverage report</button>
            </div>
          </div>
          <div style={{ marginTop: 36 }}>
            <h2 style={{ fontSize: 22, fontWeight: 700, color: INK, margin: "0 0 6px" }}>Data by county</h2>
            <p style={{ fontSize: 14, color: GRAY, lineHeight: 1.5, margin: "0 0 12px" }}>Tap a supported county to see its fields, review coverage, and add it to your cart. Each county is a one-time purchase under our standard store license.</p>
            <div className="landai-county-list-toolbar" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap", margin: "0 0 10px", padding: "12px 0", borderTop: `1px solid ${BORDER}`, borderBottom: `1px solid ${BORDER}` }}>
              <div style={{ fontSize: 12.5, color: GRAY, fontFamily: "'JetBrains Mono', monospace" }}>
                {stateCoverage.loading ? "Loading county coverage..." : `${supportedRows.length.toLocaleString()} supported · ${unsupportedRows.length.toLocaleString()} not supported`}
              </div>
              <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                <label style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 13, color: GRAY, fontWeight: 700 }}>
                  Show
                  <select value={countyFilter} onChange={e => setCountyFilter(e.target.value)} style={{ border: `1px solid ${BORDER}`, borderRadius: 8, background: "#fff", color: INK, padding: "7px 9px", fontFamily: "inherit", fontSize: 13, fontWeight: 700 }}>
                    <option value="all">All counties</option>
                    <option value="supported">Supported only</option>
                    <option value="unsupported">Not supported</option>
                  </select>
                </label>
                <label style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 13, color: GRAY, fontWeight: 700 }}>
                  Sort
                  <select value={countySort} onChange={e => setCountySort(e.target.value)} style={{ border: `1px solid ${BORDER}`, borderRadius: 8, background: "#fff", color: INK, padding: "7px 9px", fontFamily: "inherit", fontSize: 13, fontWeight: 700 }}>
                    <option value="supported">Supported first</option>
                    <option value="name">Name A-Z</option>
                  </select>
                </label>
              </div>
            </div>
            <div>
              {visibleCountyRows.map(({ county, feature }) => <CountyRow key={county} name={county} feature={feature} loading={stateCoverage.loading} onOpen={() => onCounty(county)} onAdd={onAdd} />)}
            </div>
          </div>
        </div>
        <div className="landai-state-map" style={{ flex: 1, height: "100%", background: "#e9edee", position: "relative" }}>
          <StateMapboxMap stateName={stateName} onCounty={onCounty} />
          <MapControls q={q} setQ={setQ} onCart={onCart} cartCount={cartCount} />
        </div>
      </div>
    </div>
  );
}

// ---------- COUNTY DETAIL / CHECKOUT VIEW ----------
const FIELD_SECTION_ORDER = ["Overview", "Location", "Mailing Address", "Land", "Value", "Building", "Legal", "Additional Details", "Links"];

function FieldRow({ name, pct }) {
  const cleanPct = Math.max(0, Math.min(100, Math.round(Number(pct || 0))));
  const low = cleanPct < 50;
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "7px 0", borderBottom: "1px solid #eef1ee", breakInside: "avoid" }}>
      <span style={{ fontSize: 12.5, fontFamily: "'JetBrains Mono', monospace", color: cleanPct < 30 ? "#a7afaa" : INK }}>{name}</span>
      <span style={{ fontSize: 11, fontWeight: 700, color: low ? "#c2862f" : GREEN, fontFamily: "'JetBrains Mono', monospace" }}>{cleanPct}%</span>
    </div>
  );
}

function fieldCoverageGroups(fieldCoverage) {
  const fields = Array.isArray(fieldCoverage?.fields) ? fieldCoverage.fields : [];
  const groups = new Map();
  fields.forEach(field => {
    const section = String(field?.section || "Other").trim() || "Other";
    const label = String(field?.label || field?.id || "").trim();
    if (!label) return;
    const pct = Number(field?.pct);
    if (!Number.isFinite(pct)) return;
    if (!groups.has(section)) groups.set(section, []);
    groups.get(section).push({ label, pct });
  });
  return Array.from(groups.entries())
    .sort(([a], [b]) => {
      const ai = FIELD_SECTION_ORDER.indexOf(a);
      const bi = FIELD_SECTION_ORDER.indexOf(b);
      return (ai === -1 ? 999 : ai) - (bi === -1 ? 999 : bi) || a.localeCompare(b);
    })
    .map(([section, rows]) => ({ section, rows }));
}

function FieldCoverageSection({ fieldCoverage, loading }) {
  const groups = fieldCoverageGroups(fieldCoverage);
  const fieldCount = groups.reduce((sum, group) => sum + group.rows.length, 0);
  const parcelCount = Number(fieldCoverage?.active_parcel_count || 0);
  const parcelText = parcelCount > 0 ? ` across ${parcelCount.toLocaleString()} active parcels` : "";

  return (
    <div style={{ marginTop: 36 }}>
      <h2 style={{ fontSize: 20, fontWeight: 700, color: INK, margin: "0 0 4px" }}>Fields included</h2>
      {loading ? (
        <>
          <p style={{ fontSize: 13.5, color: GRAY, margin: "0 0 14px" }}>Loading real field coverage for this county...</p>
          <div style={{ borderRadius: 8, background: "#f4f7f5", padding: "16px 18px", color: GRAY, fontSize: 13.5 }}>Checking the latest county cache.</div>
        </>
      ) : fieldCount ? (
        <>
          <p style={{ fontSize: 13.5, color: GRAY, margin: "0 0 14px" }}>{fieldCount} parcel detail fields with real completeness{parcelText}.</p>
          <div className="landai-field-columns" style={{ columns: 2, columnGap: 40 }}>
            {groups.map(group => (
              <div key={group.section} style={{ breakInside: "avoid", marginBottom: 16 }}>
                <div style={{ fontSize: 12, color: GREEN_DK, fontWeight: 800, textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 4 }}>{group.section}</div>
                {group.rows.map(row => <FieldRow key={`${group.section}-${row.label}`} name={row.label} pct={row.pct} />)}
              </div>
            ))}
          </div>
        </>
      ) : (
        <>
          <p style={{ fontSize: 13.5, color: GRAY, margin: "0 0 14px" }}>Field coverage has not been generated for this county yet.</p>
          <div style={{ borderRadius: 8, background: "#f4f7f5", padding: "16px 18px", color: GRAY, fontSize: 13.5 }}>The nightly coverage refresh will populate this when county parcel data is available.</div>
        </>
      )}
    </div>
  );
}

function IncludedFormatChip({ label }) {
  return (
    <span style={{ border: "1.5px solid rgba(255,255,255,0.30)", background: "rgba(255,255,255,0.10)", color: "#fff", fontSize: 13, fontWeight: 700, padding: "9px 14px", borderRadius: 9, fontFamily: "inherit" }}>{label}</span>
  );
}

function CountyMap() {
  // zoomed county — purple parcel fill
  const shape = "M 120 90 L 540 80 L 560 150 L 552 250 L 430 280 L 300 300 L 150 290 L 110 200 Z";
  const dots = [];
  for (let i = 0; i < 900; i++) {
    const x = 110 + (Math.sin(i * 12.9) * 0.5 + 0.5) * 450;
    const y = 80 + (Math.cos(i * 7.7) * 0.5 + 0.5) * 220;
    dots.push(<rect key={i} x={x.toFixed(1)} y={y.toFixed(1)} width="6" height="5" fill="#6f9bf0" opacity="0.5" />);
  }
  return (
    <svg viewBox="0 0 680 400" style={{ width: "100%", height: "100%", display: "block" }} preserveAspectRatio="xMidYMid slice">
      <rect width="680" height="400" fill="#e9edee" />
      <defs><clipPath id="cty-clip"><path d={shape} /></clipPath></defs>
      <path d={shape} fill="#dCe6fb" />
      <g clipPath="url(#cty-clip)">{dots}</g>
      <g clipPath="url(#cty-clip)" stroke="#a8c4f6" strokeWidth="0.6" fill="none" opacity="0.7">
        <path d={Array.from({ length: 40 }, (_, i) => `M ${110 + i * 12} 70 L ${110 + i * 12 + Math.sin(i) * 4} 310`).join(" ")} />
        <path d={Array.from({ length: 20 }, (_, i) => `M 100 ${75 + i * 12} L 575 ${75 + i * 12 + Math.cos(i) * 4}`).join(" ")} />
      </g>
      <path d={shape} fill="none" stroke="#2E6BF0" strokeWidth="2.2" />
    </svg>
  );
}

function CountyView({ countyName, stateName, onHome, onBrowse, onBack, onCounty, onAdd, onCart, cartCount }) {
  const [q, setQ] = useState("");
  const { countyMeta, countyMetaLoading, fieldCoverage, fieldCoverageLoading } = useDataStoreCountyData(countyName, stateName);
  const { loading: otherCountiesLoading, counties: otherSupportedCounties } = useSupportedCountiesInState(stateName, countyName);
  const info = countyInfo(countyName);
  const stats = [
    ["Parcels", dataStoreCountyParcelCountLabel(countyMeta, countyMetaLoading)],
    ["Data date", dataStoreCountyDataDateLabel(countyMeta, countyMetaLoading)],
  ];
  const base = info.price;
  const stateAbbr = (stateCodeForName(stateName) || "").toUpperCase();

  return (
    <div className="landai-store-shell" style={{ width: W, height: STORE_PAGE_HEIGHT, margin: "0 auto", background: PAPER, fontFamily: "'Hanken Grotesk', system-ui, sans-serif", overflow: "hidden", boxShadow: "0 40px 120px rgba(16,40,30,0.18)", display: "flex", flexDirection: "column" }}>
      <Nav onHome={onHome} onBrowse={onBrowse} />
      <div className="landai-store-split" style={{ display: "flex", alignItems: "stretch", flex: 1, minHeight: 0 }}>
        {/* LEFT — scrolls */}
        <div className="landai-store-left" style={{ width: "min(720px, 100%)", flexShrink: 0, padding: "30px 44px 64px", boxSizing: "border-box", overflowY: "auto", height: "100%" }}>
          <div onClick={onBack} style={{ display: "inline-flex", alignItems: "center", gap: 7, color: GREEN, fontSize: 14, fontWeight: 700, cursor: "pointer", marginBottom: 16 }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={GREEN} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6" /></svg>
            {stateName} Parcel Data
          </div>
          <h1 style={{ fontSize: 32, fontWeight: 800, color: INK, letterSpacing: -1, margin: 0 }}>{countyName}, {stateName}</h1>

          {/* stats */}
          <div className="landai-county-stats" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px 40px", marginTop: 22 }}>
            {stats.map(([label, val], i) => (
              <div key={i}>
                <div style={{ fontSize: 22, fontWeight: 800, color: GREEN_DK, letterSpacing: -0.4, fontFamily: "'JetBrains Mono', monospace" }}>{val}</div>
                <div style={{ fontSize: 12.5, color: GRAY, marginTop: 2, fontWeight: 600 }}>{label}</div>
              </div>
            ))}
          </div>

          {/* product package card */}
          <div className="landai-product-card" style={{ marginTop: 30, background: GREEN_DK, borderRadius: 16, padding: "24px 24px 26px", color: "#fff" }}>
            <div style={{ fontSize: 18, fontWeight: 700, marginBottom: 16 }}>County parcel package</div>
            <div style={{ display: "flex", gap: 11, alignItems: "flex-start", marginBottom: 18 }}>
              <span style={{ width: 20, height: 20, borderRadius: 99, background: "#fff", display: "flex", alignItems: "center", justifyContent: "center", boxSizing: "border-box", marginTop: 1, flexShrink: 0 }}>
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={GREEN_DK} strokeWidth="3.4" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
              </span>
              <div>
                <span style={{ fontSize: 15, fontWeight: 700 }}>LandAI parcel schema included</span>
                <div style={{ fontSize: 13, color: "rgba(255,255,255,0.6)", marginTop: 4 }}>One standardized set of parcel fields, with completeness shown below.</div>
              </div>
            </div>
            {/* format */}
            <div style={{ fontSize: 13, fontWeight: 700, color: "rgba(255,255,255,0.75)", marginBottom: 6 }}>Export formats included</div>
            <div style={{ fontSize: 13, color: "rgba(255,255,255,0.6)", lineHeight: 1.45, marginBottom: 10 }}>Every county purchase includes all download formats.</div>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 20 }}>
              {INCLUDED_EXPORT_FORMATS.map(f => <IncludedFormatChip key={f} label={f} />)}
            </div>
            {/* primary CTA */}
            <button onClick={() => onAdd(countyName, base, info.parcels.toLocaleString(), { format: INCLUDED_FORMAT_LABEL })} style={{ width: "100%", border: "none", background: GREEN, color: "#fff", fontSize: 16, fontWeight: 800, padding: "16px 0", borderRadius: 12, cursor: "pointer", fontFamily: "inherit", letterSpacing: 0.2 }}>
              Add {countyName} to cart — ${base}
            </button>
          </div>

          <FieldCoverageSection fieldCoverage={fieldCoverage} loading={fieldCoverageLoading} />

          {/* nationwide callout */}
          <div style={{ marginTop: 30, background: "#dde8f3", borderRadius: 14, padding: "18px 22px" }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: "#23476e" }}>Need more than a few counties?</div>
            <div style={{ fontSize: 14, color: "#4a6a8e", marginTop: 4 }}>Grab the whole state, or reach out about nationwide bulk &amp; API access.</div>
          </div>

          {/* other counties */}
          <div style={{ marginTop: 36 }}>
            <h3 style={{ fontSize: 18, fontWeight: 700, color: INK, margin: "0 0 16px" }}>Other counties in {stateName}</h3>
            {otherCountiesLoading ? (
              <div style={{ fontSize: 14, color: GRAY }}>Loading supported counties...</div>
            ) : otherSupportedCounties.length ? (
              <div className="landai-other-counties" style={{ columns: 2, columnGap: 40 }}>
                {otherSupportedCounties.map((c, i) => (
                  <div key={i} onClick={() => onCounty(c, stateName)} style={{ breakInside: "avoid", padding: "8px 0", fontSize: 14, fontWeight: 600, color: GREEN_DK, cursor: "pointer" }}>{c}</div>
                ))}
              </div>
            ) : (
              <div style={{ fontSize: 14, color: GRAY }}>No other supported counties in {stateName} yet.</div>
            )}
          </div>
        </div>

        {/* RIGHT — county map */}
        <div className="landai-county-map" style={{ flex: 1, height: "100%", background: "#e9edee", position: "relative" }}>
          <CountyMap />
          <MapControls q={q} setQ={setQ} onCart={onCart} cartCount={cartCount} />
          <div style={{ position: "absolute", left: "40%", top: "44%", background: "#2E6BF0", color: "#fff", fontSize: 13, fontWeight: 600, padding: "7px 12px", borderRadius: 8, boxShadow: "0 6px 18px rgba(0,0,0,0.25)" }}>{countyName}, {stateAbbr}</div>
          <div style={{ position: "absolute", bottom: 10, right: 16, fontSize: 11, color: "#9aa39e" }}>Sources: LandAI, Esri, USGS, OpenStreetMap contributors</div>
        </div>
      </div>
    </div>
  );
}

// ---------- SUPPORT / DOCS VIEW ----------
const PARCEL_DICTIONARY_GROUPS = [
  ["Overview", [
    ["owner_name", "Land Owner name", "string", "Combined owner name shown at the top of the parcel detail panel."],
    ["site_address", "Address", "string", "Primary physical/situs address shown at the top of the parcel detail panel."],
    ["parcel_id", "Parcel ID", "string", "County assessor parcel identifier or APN."],
    ["source_updated_at", "Last updated", "date", "Date or data vintage reported by the county/state source for this parcel record."],
    ["ingested_at", "Ingested", "timestamp", "When LandAI most recently loaded this parcel row into our database."],
  ]],
  ["Location", [
    ["location_street_address", "Street Address", "string", "Standardized physical street address for the parcel."],
    ["location_city", "City", "string", "Physical address city or locality."],
    ["location_state", "State", "string", "Physical address state."],
    ["location_zip", "Zip Code", "string", "Physical address ZIP Code."],
    ["location_county", "County", "string", "County name associated with the parcel."],
  ]],
  ["Mailing Address", [
    ["mailing_street_address", "Street Address", "string", "Owner mailing street address from the county source."],
    ["mailing_city", "City", "string", "Owner mailing city."],
    ["mailing_state", "State", "string", "Owner mailing state."],
    ["mailing_zip", "Zip Code", "string", "Owner mailing ZIP Code."],
    ["owner_occupied", "Owner Occupied", "boolean", "Whether the owner mailing address appears to match the parcel address."],
  ]],
  ["Land", [
    ["deeded_acres", "Deeded Acres", "number", "Acreage reported by the county record when available."],
    ["calculated_acres", "Calculated Acres", "number", "Acreage calculated from LandAI parcel geometry."],
    ["land_use", "Land Use", "string", "Human-readable land-use or property-use description."],
    ["land_use_code", "Land Use Code", "string", "Raw land-use code from the county source."],
    ["zoning", "Zoning", "string", "Zoning code or zoning description when the county publishes it."],
    ["property_class", "Property Class", "string", "County property class, class code, or building use classification."],
  ]],
  ["Value", [
    ["sale_price", "Sale Price", "currency", "Most recent sale or transfer price when available."],
    ["transfer_date", "Transfer Date", "date", "Most recent sale, transfer, or recording date."],
    ["assessed_total_value", "Assessed Total Value", "currency", "Total assessed value reported by the county."],
    ["market_total_value", "Market Total Value", "currency", "Total market value reported by the county."],
    ["market_improvement_value", "Market Improvement Value", "currency", "Market value assigned to improvements or structures."],
    ["market_land_value", "Market Land Value", "currency", "Market value assigned to the land."],
    ["tax_amount", "Tax Amount", "currency", "Most recent tax amount when published by the county source."],
    ["tax_year", "Tax Year", "integer", "Tax year associated with the tax or assessment values."],
  ]],
  ["Building", [
    ["building_sqft", "Sq Ft", "number", "Building area or total structure square footage."],
    ["year_built", "Year Built", "integer", "Year the primary building was built."],
    ["bedrooms", "Bedrooms", "number", "Bedroom count for residential records when available."],
    ["baths_total", "Baths Total", "number", "Total bathroom count for residential records when available."],
    ["stories", "Stories", "number", "Number of stories reported for the primary structure."],
    ["building_count", "Building Count", "integer", "Count of buildings or structures associated with the parcel."],
  ]],
  ["Legal", [
    ["legal_description", "Legal Description", "string", "Legal description text from the county record."],
    ["account_type", "Account Type", "string", "County account, roll, or property account type when provided."],
    ["assesspro_id", "AssessPro ID", "string", "AssessPro identifier for counties that publish it."],
  ]],
  ["Additional Details", [
    ["school_district", "School District", "string", "School district associated with the parcel."],
    ["land_cover", "Land Cover", "string", "Land cover classification when enrichment is available."],
    ["crop_cover", "Crop Cover", "string", "Crop cover classification when enrichment is available."],
    ["elevation", "Elevation", "number", "Elevation associated with the parcel location."],
    ["adjacent_acreage", "Adjacent Acreage (Same Owner)", "number", "Nearby acreage held by the same owner where available."],
    ["census_place", "Census Place", "string", "Census place or incorporated area for the parcel."],
    ["section_township_range", "Section-Township-Range", "string", "Public land survey section-township-range reference where available."],
    ["census_tract", "Census Tract", "string", "Census tract identifier associated with the parcel."],
    ["census_block", "Census Block", "string", "Census block identifier associated with the parcel."],
  ]],
  ["Links", [
    ["tax_assessment_link", "Tax Assessment", "url", "County tax assessment or property-card link when the source provides one."],
  ]],
];

const FAQS = [
  ["How accurate are the parcel boundaries?", "Boundaries come straight from county and city assessor offices, then we line them up into one consistent national geometry. They match the official tax record, but they're not a substitute for a recorded survey. Every county page shows its refresh date and coverage."],
  ["How often is the data refreshed?", "Most counties update on a rolling 30-90 day cycle, and busy counties more often. The exact data date is on every county page, and if you buy a whole state we re-deliver it as counties update."],
  ["What formats can I download?", "Every county purchase includes FileGDB, Shapefile, GeoPackage, GeoJSON, and CSV. The fields stay the same across formats, so nothing breaks when you move between tools."],
  ["Is owner and contact info always available?", "Owner of record shows up on about 99% of parcels. Mailing addresses and second owners depend on the county — the Data Dictionary lists coverage field by field, so you know what you're getting before you pay."],
  ["What does the standard license allow?", "Use it, analyze it, and build it into your own apps. Reselling or publicly republishing the raw data needs a separate license — get in touch and we'll sort out bulk or redistribution terms."],
  ["Can I get the whole country or scheduled delivery?", "Yes. The store is built for a handful of counties or a few states. For nationwide coverage, API access, or scheduled refreshes, reach out and we'll set up a bulk license."],
  ["Do you offer an API?", "Yes. API access is available for bulk and enterprise plans with live parcel and tile endpoints. Reach out and we'll set up the right plan."],
];

function FaqItem({ q, a, open, onToggle }) {
  return (
    <div style={{ borderBottom: `1px solid ${BORDER}` }}>
      <div onClick={onToggle} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 20, padding: "22px 0", cursor: "pointer" }}>
        <span style={{ fontSize: 19, color: INK, fontFamily: SERIF }}>{q}</span>
        <span style={{ flexShrink: 0, fontSize: 24, color: GREEN, lineHeight: 1, transform: open ? "rotate(45deg)" : "none", transition: "transform .15s" }}>+</span>
      </div>
      {open && <div style={{ fontSize: 15.5, color: GRAY, lineHeight: 1.6, padding: "0 0 24px", maxWidth: 680 }}>{a}</div>}
    </div>
  );
}

function SupportShell({ doc, setDoc, onHome, onBrowse, children }) {
  const nav = [["start", "Getting started"], ["schema", "Data dictionary"], ["coverage", "Coverage report"], ["license", "Licensing"], ["faqs", "FAQs"]];
  return (
    <div className="landai-store-shell" style={{ width: W, height: STORE_PAGE_HEIGHT, margin: "0 auto", background: PAPER, fontFamily: "'Hanken Grotesk', system-ui, sans-serif", overflow: "hidden", boxShadow: "0 40px 120px rgba(16,40,30,0.18)", display: "flex", flexDirection: "column" }}>
      <Nav onHome={onHome} onBrowse={onBrowse} />
      <div className="landai-support-split" style={{ display: "flex", alignItems: "stretch", flex: 1, minHeight: 0 }}>
        {/* sidebar */}
        <div className="landai-support-sidebar" style={{ width: "min(264px, 42vw)", flexShrink: 0, borderRight: `1px solid ${BORDER}`, padding: "34px 22px", boxSizing: "border-box" }}>
          <div onClick={onBrowse} style={{ display: "inline-flex", alignItems: "center", gap: 7, color: GREEN, fontSize: 13.5, fontWeight: 700, cursor: "pointer", marginBottom: 24 }}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke={GREEN} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6" /></svg>
            Back to data store
          </div>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1.4, color: GRAY, textTransform: "uppercase", marginBottom: 14 }}>Support</div>
          <div className="landai-support-tabs" style={{ display: "flex", flexDirection: "column", gap: 3 }}>
            {nav.map(([k, l]) => (
              <div key={k} onClick={() => setDoc(k)} style={{ padding: "10px 14px", borderRadius: 9, fontSize: 15, fontWeight: 600, cursor: "pointer", color: doc === k ? "#fff" : INK, background: doc === k ? INK : "transparent" }}>{l}</div>
            ))}
          </div>
          <div style={{ marginTop: 30, padding: 16, background: CREAM, borderRadius: 12 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: INK }}>Still stuck?</div>
            <div style={{ fontSize: 13, color: GRAY, lineHeight: 1.4, margin: "6px 0 12px" }}>Our data team replies within one business day.</div>
            <button style={{ border: "none", background: GREEN, color: "#fff", fontSize: 13, fontWeight: 700, padding: "9px 16px", borderRadius: 8, cursor: "pointer", fontFamily: "inherit" }}>Contact support</button>
          </div>
        </div>
        {/* content scrolls */}
        <div className="landai-support-content" style={{ flex: 1, overflowY: "auto", height: "100%", padding: "44px 56px 80px" }}>
          {children}
        </div>
      </div>
    </div>
  );
}

function DataDictionaryDoc() {
  const [q, setQ] = useState("");
  const query = q.trim().toLowerCase();
  const total = PARCEL_DICTIONARY_GROUPS.reduce((s, g) => s + g[1].length, 0);
  const match = (f, group) => {
    if (!query) return true;
    return [group, f[0], f[1], f[2], f[3]].some(value => String(value || "").toLowerCase().includes(query));
  };
  return (
    <div style={{ maxWidth: 820 }}>
      <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: 1.4, color: GREEN, textTransform: "uppercase", marginBottom: 10, fontFamily: "'JetBrains Mono', monospace" }}>Reference</div>
      <h1 style={{ fontSize: 40, color: INK, letterSpacing: -0.8, margin: 0 }}>Parcel data dictionary</h1>
      <p style={{ fontSize: 16.5, color: GRAY, lineHeight: 1.6, margin: "14px 0 24px", maxWidth: 680 }}>
        These {total} fields mirror the LandAI web and mobile parcel detail panel. County pages show real completeness for each field; this dictionary defines the app label, export/API key, type, and meaning.
      </p>
      <div style={{ display: "flex", alignItems: "center", gap: 10, border: `1.5px solid ${BORDER}`, borderRadius: 10, padding: "12px 16px", background: "#fff", maxWidth: 420, marginBottom: 32 }}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#9aa39e" strokeWidth="2.4"><circle cx="11" cy="11" r="7" /><path d="m20 20-3-3" /></svg>
        <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search fields…" style={{ border: "none", outline: "none", fontSize: 15, color: INK, fontFamily: "inherit", width: "100%", background: "transparent" }} />
      </div>
      {PARCEL_DICTIONARY_GROUPS.map(([group, fields], gi) => {
        const shown = fields.filter(field => match(field, group));
        if (!shown.length) return null;
        return (
          <div key={gi} style={{ marginBottom: 34 }}>
            <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: 0.6, color: INK, textTransform: "uppercase", marginBottom: 6 }}>{group}</div>
            {/* header */}
            <div className="landai-doc-table">
              <div style={{ display: "flex", alignItems: "center", gap: 16, padding: "8px 0", borderBottom: `1.5px solid ${BORDER}`, fontSize: 11, fontWeight: 700, letterSpacing: 0.8, color: GRAY, textTransform: "uppercase" }}>
                <span style={{ width: 170 }}>App label</span>
                <span style={{ width: 190 }}>Export/API key</span>
                <span style={{ width: 64 }}>Type</span>
                <span style={{ flex: 1 }}>Description</span>
              </div>
              {shown.map((f, i) => (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: 16, padding: "12px 0", borderBottom: "1px solid #eeece2" }}>
                  <span style={{ width: 170, fontSize: 14, color: INK, fontWeight: 700 }}>{f[1]}</span>
                  <span style={{ width: 190, fontSize: 12.5, fontFamily: "'JetBrains Mono', monospace", color: INK, fontWeight: 600 }}>{f[0]}</span>
                  <span style={{ width: 64, fontSize: 12, fontFamily: "'JetBrains Mono', monospace", color: GREEN, fontWeight: 700 }}>{f[2]}</span>
                  <span style={{ flex: 1, fontSize: 14, color: GRAY, lineHeight: 1.4 }}>{f[3]}</span>
                </div>
              ))}
            </div>
          </div>
        );
      })}
      {query && !PARCEL_DICTIONARY_GROUPS.some(([group, fields]) => fields.some(field => match(field, group))) && (
        <div style={{ padding: "24px 0", color: GRAY, fontSize: 15 }}>No parcel fields match "{q}".</div>
      )}
    </div>
  );
}

function FaqDoc() {
  const [open, setOpen] = useState(0);
  return (
    <div style={{ maxWidth: 760 }}>
      <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: 1.4, color: GREEN, textTransform: "uppercase", marginBottom: 10, fontFamily: "'JetBrains Mono', monospace" }}>Help</div>
      <h1 style={{ fontSize: 40, color: INK, letterSpacing: -0.8, margin: 0 }}>Parcel data <span style={{ fontStyle: "italic", color: GREEN }}>FAQs</span></h1>
      <p style={{ fontSize: 16.5, color: GRAY, lineHeight: 1.6, margin: "14px 0 28px", maxWidth: 660 }}>
        The stuff people ask us most — coverage, accuracy, formats, and licensing. Still stuck? Reach the team from the sidebar.
      </p>
      <div>
        {FAQS.map(([q, a], i) => <FaqItem key={i} q={q} a={a} open={open === i} onToggle={() => setOpen(open === i ? -1 : i)} />)}
      </div>
    </div>
  );
}

function SimpleDoc({ title, eyebrow, body }) {
  return (
    <div style={{ maxWidth: 720 }}>
      <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: 1.4, color: GREEN, textTransform: "uppercase", marginBottom: 10, fontFamily: "'JetBrains Mono', monospace" }}>{eyebrow}</div>
      <h1 style={{ fontSize: 40, color: INK, letterSpacing: -0.8, margin: "0 0 18px" }}>{title}</h1>
      {body.map((p, i) => <p key={i} style={{ fontSize: 16.5, color: GRAY, lineHeight: 1.65, margin: "0 0 16px", maxWidth: 660 }}>{p}</p>)}
    </div>
  );
}

function SupportView({ doc, onHome, onBrowse, onDocChange }) {
  const d = normalizeDoc(doc);
  const setD = onDocChange || (() => {});
  let content;
  if (d === "schema") content = <DataDictionaryDoc />;
  else if (d === "faqs") content = <FaqDoc />;
  else if (d === "coverage") content = <SimpleDoc eyebrow="Reference" title="Coverage report" body={["We carry 136M+ parcel records across 2,170+ supported counties. How fresh it is varies by county — each county's page shows its parcel count, when it was last refreshed, and how complete each field is.", "The coverage map gives you the quick view: green counties are live and ready to download, amber counties are being onboarded. Buy a whole state and you always get the latest counties available at delivery."]} />;
  else if (d === "license") content = <SimpleDoc eyebrow="Legal" title="Standard store license" body={["The standard license lets you use, analyze, and build parcel data into your own apps and workflows. It's tied to the area you bought and doesn't expire.", "It does not allow reselling or publicly republishing the raw parcel data. If you need to redistribute it, build it into a product you sell, or publish it publicly, reach out and we'll write up a custom license.", "Each county purchase includes the fields and completeness shown on that county's store page at checkout."]} />;
  else content = <SimpleDoc eyebrow="Start here" title="Getting started" body={["New here? Start by finding your area — search or tap the coverage map, then open a county or a whole state to see what's available.", "On a county page you'll review parcel counts, data date, field coverage, and included export formats before checkout. Your download uses the same fields laid out in the Data Dictionary.", "Working across the country or need scheduled refreshes? See Licensing, or get in touch with our team."]} />;
  return <SupportShell doc={d} setDoc={setD} onHome={onHome} onBrowse={onBrowse}>{content}</SupportShell>;
}

// ---------- STATE COVERAGE REPORT ----------
const COV_COLS = [
  ["owner", "Owner"],
  ["site", "Site address"],
  ["mail", "Mailing address"],
  ["zoning", "Zoning"],
  ["bldg", "Building footprint"],
  ["value", "Assessed value"],
  ["sale", "Last sale"],
];
function covPct(county, key) {
  const h = hashStr(county + key);
  // realistic ranges per field
  const ranges = { owner: [95, 100], site: [88, 99], mail: [80, 99], zoning: [55, 92], bldg: [70, 95], value: [85, 99], sale: [60, 90] };
  const [lo, hi] = ranges[key];
  return lo + (h % (hi - lo + 1));
}
function CovCell({ pct }) {
  const low = pct < 70, mid = pct < 85;
  const color = low ? "#C0712E" : mid ? "#B89331" : GREEN;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 5, alignItems: "flex-end" }}>
      <span style={{ fontSize: 13, fontWeight: 700, color: color, fontFamily: "'JetBrains Mono', monospace" }}>{pct}%</span>
      <div style={{ width: 56, height: 5, borderRadius: 99, background: "#ece8dd", overflow: "hidden" }}>
        <div style={{ width: pct + "%", height: "100%", background: color }} />
      </div>
    </div>
  );
}

function CoverageReportView({ stateName, onHome, onBrowse, onBack, onCounty }) {
  const [q, setQ] = useState("");
  const counties = countiesForState(stateName);
  const shown = counties.filter(c => c.toLowerCase().includes(q.toLowerCase()));
  // statewide averages
  const avg = COV_COLS.map(([k]) => Math.round(counties.reduce((s, c) => s + covPct(c, k), 0) / counties.length));
  return (
    <div className="landai-store-shell" style={{ width: W, height: STORE_PAGE_HEIGHT, margin: "0 auto", background: PAPER, fontFamily: "'Hanken Grotesk', system-ui, sans-serif", overflow: "hidden", boxShadow: "0 40px 120px rgba(16,40,30,0.18)", display: "flex", flexDirection: "column" }}>
      <Nav onHome={onHome} onBrowse={onBrowse} />
      <div className="landai-coverage-page" style={{ flex: 1, minHeight: 0, overflowY: "auto", padding: "34px 56px 70px" }}>
        <div onClick={onBack} style={{ display: "inline-flex", alignItems: "center", gap: 7, color: GREEN, fontSize: 14, fontWeight: 700, cursor: "pointer", marginBottom: 16 }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={GREEN} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6" /></svg>
          {stateName} Parcel Data
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 30, flexWrap: "wrap" }}>
          <div>
            <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: 1.4, color: GREEN, textTransform: "uppercase", marginBottom: 8, fontFamily: "'JetBrains Mono', monospace" }}>Coverage report</div>
            <h1 style={{ fontSize: 36, color: INK, letterSpacing: -0.8, margin: 0 }}>{stateName} field coverage</h1>
            <p style={{ fontSize: 15.5, color: GRAY, lineHeight: 1.55, margin: "12px 0 0", maxWidth: 640 }}>How complete each field is, county by county, across {stateName}. The percentages show how many parcels actually carry a value for each one. Tap a county to buy it or dig into its full schema.</p>
          </div>
        </div>

        {/* statewide summary */}
        <div style={{ display: "flex", gap: 12, marginTop: 26, flexWrap: "wrap" }}>
          {COV_COLS.map(([k, label], i) => (
            <div key={k} style={{ flex: "1 1 120px", background: "#fff", border: `1px solid ${BORDER}`, borderRadius: 12, padding: "14px 16px" }}>
              <div style={{ fontSize: 22, fontWeight: 800, color: INK, fontFamily: "'JetBrains Mono', monospace", letterSpacing: -0.5 }}>{avg[i]}%</div>
              <div style={{ fontSize: 12, color: GRAY, marginTop: 3, fontWeight: 600 }}>{label}</div>
            </div>
          ))}
        </div>

        {/* search */}
        <div style={{ display: "flex", alignItems: "center", gap: 10, border: `1.5px solid ${BORDER}`, borderRadius: 10, padding: "11px 16px", background: "#fff", maxWidth: 320, margin: "28px 0 16px" }}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#9aa39e" strokeWidth="2.4"><circle cx="11" cy="11" r="7" /><path d="m20 20-3-3" /></svg>
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Filter counties…" style={{ border: "none", outline: "none", fontSize: 14.5, color: INK, fontFamily: "inherit", width: "100%", background: "transparent" }} />
        </div>

        {/* table */}
        <div className="landai-coverage-table" style={{ background: "#fff", border: `1px solid ${BORDER}`, borderRadius: 14, overflow: "hidden" }}>
          {/* header */}
          <div style={{ display: "flex", alignItems: "center", padding: "14px 22px", borderBottom: `1.5px solid ${BORDER}`, background: "#faf8f2" }}>
            <span style={{ flex: "0 0 220px", fontSize: 11, fontWeight: 700, letterSpacing: 0.8, color: GRAY, textTransform: "uppercase" }}>County</span>
            {COV_COLS.map(([k, label]) => (
              <span key={k} style={{ flex: 1, fontSize: 11, fontWeight: 700, letterSpacing: 0.6, color: GRAY, textTransform: "uppercase", textAlign: "right" }}>{label}</span>
            ))}
          </div>
          {shown.map((c, i) => (
            <div key={i} onClick={() => onCounty(c)} style={{ display: "flex", alignItems: "center", padding: "14px 22px", borderBottom: i < shown.length - 1 ? "1px solid #eeece2" : "none", cursor: "pointer" }}>
              <div style={{ flex: "0 0 220px" }}>
                <div style={{ fontSize: 15, fontWeight: 700, color: GREEN_DK, letterSpacing: -0.2 }}>{c}</div>
                <div style={{ fontSize: 11.5, color: GRAY, fontFamily: "'JetBrains Mono', monospace", marginTop: 1 }}>{countyInfo(c).parcels.toLocaleString()} parcels</div>
              </div>
              {COV_COLS.map(([k]) => (
                <div key={k} style={{ flex: 1, display: "flex", justifyContent: "flex-end" }}><CovCell pct={covPct(c, k)} /></div>
              ))}
            </div>
          ))}
        </div>
        <div style={{ fontSize: 12.5, color: GRAY, marginTop: 14, fontFamily: "'JetBrains Mono', monospace" }}>● ≥85% complete &nbsp;&nbsp; ● 70–84% &nbsp;&nbsp; ● &lt;70% — varies by county recorder</div>
      </div>
    </div>
  );
}

// ---------- CART / CHECKOUT ----------
function CartField({ label, sub, placeholder, select, options, value, onChange, type = "text" }) {
  const fieldStyle = { marginTop: 7, border: `1.5px solid ${BORDER}`, borderRadius: 10, height: 48, background: "#fff", display: "flex", alignItems: "center", padding: "0 16px", fontSize: 15, color: INK, fontFamily: "inherit", width: "100%", outline: "none" };
  return (
    <div style={{ marginBottom: 18 }}>
      <div style={{ fontSize: 14, fontWeight: 700, color: INK }}>{label}</div>
      {sub && <div style={{ fontSize: 12.5, color: GRAY, margin: "2px 0 6px" }}>{sub}</div>}
      {select ? (
        <select value={value || ""} onChange={e => onChange && onChange(e.target.value)} style={{ ...fieldStyle, appearance: "none", color: value ? INK : "#9aa39e" }}>
          <option value="">{placeholder}</option>
          {(options || []).map(option => <option key={option} value={option}>{option}</option>)}
        </select>
      ) : (
        <input type={type} value={value || ""} onChange={e => onChange && onChange(e.target.value)} placeholder={placeholder} style={{ ...fieldStyle, color: INK }} />
      )}
    </div>
  );
}

function PayTab({ icon, label, active, onClick }) {
  return (
    <div onClick={onClick} style={{ flex: 1, border: active ? `2px solid ${GREEN}` : `1.5px solid ${BORDER}`, borderRadius: 12, padding: "14px 12px", cursor: "pointer", background: "#fff", display: "flex", flexDirection: "column", gap: 8 }}>
      {icon}
      <span style={{ fontSize: 13.5, fontWeight: 700, color: active ? GREEN : INK }}>{label}</span>
    </div>
  );
}

function Checkbox({ checked, onToggle, children }) {
  return (
    <div onClick={onToggle} style={{ display: "flex", gap: 11, alignItems: "flex-start", cursor: "pointer", marginBottom: 12 }}>
      <span style={{ flexShrink: 0, width: 20, height: 20, borderRadius: 5, border: checked ? "none" : `2px solid #b9bdb5`, background: checked ? GREEN : "#fff", display: "flex", alignItems: "center", justifyContent: "center", marginTop: 1 }}>
        {checked && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3.4" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>}
      </span>
      <span style={{ fontSize: 14, color: INK, lineHeight: 1.45, fontWeight: 600 }}>{children}</span>
    </div>
  );
}

function LicenseHeading({ children }) {
  return <div style={{ color: INK, fontSize: 13, fontWeight: 900, letterSpacing: 0.5, textTransform: "uppercase", margin: "18px 0 6px" }}>{children}</div>;
}

function LandAiParcelDataLicense() {
  const highlightItems = [
    "We do our best to clean, check, and standardize the data, but it is offered as-is.",
    "Purchased data cannot be resold or redistributed as raw files. Derivative works are OK.",
    "We cannot offer refunds on purchased data.",
    "Attribution is appreciated where possible.",
  ];
  return (
    <div style={{ background: "#fff", border: `1px solid ${BORDER}`, borderRadius: 10, padding: 16, fontSize: 12.5, color: GRAY, lineHeight: 1.48, maxHeight: 230, overflowY: "auto", marginBottom: 18 }}>
      <strong style={{ color: INK }}>The highlights</strong> <span>(the full license below is what applies):</span>
      <ul style={{ margin: "8px 0 12px", paddingLeft: 18 }}>
        {highlightItems.map((item, index) => (
          <li key={item} style={index === 2 ? { color: INK, fontWeight: 800 } : null}>{item}</li>
        ))}
      </ul>

      <LicenseHeading>Data Store License Agreement</LicenseHeading>
      <p style={{ margin: "0 0 9px" }}>
        By placing an order for parcel data through the LandAI Data Store, the purchaser, customer, or organization named at checkout ("Licensee" or "you") accepts this Data Store License Agreement with LandAI ("LandAI", "Licensor", "we", or "us").
      </p>
      <p style={{ margin: "0 0 9px" }}>
        LandAI will provide Licensee with a one-time export of the selected parcel data package. Unless a separate written agreement says otherwise, the purchased export does not include automatic future updates.
      </p>

      <LicenseHeading>Terms and Conditions</LicenseHeading>
      <p style={{ margin: "0 0 9px" }}>
        Licensee receives only a limited right to use the purchased data. No ownership interest, copyright, trademark, database right, trade secret, or other proprietary right in the data is transferred to Licensee.
      </p>
      <p style={{ margin: "0 0 9px" }}>
        LandAI grants Licensee a nonexclusive, non-transferable license to use the purchased data for Licensee's internal business, analysis, mapping, research, application, and operational workflows during the license term.
      </p>
      <p style={{ margin: "0 0 9px" }}>
        Licensee may not resell, sublicense, publish, transfer, or otherwise make a substantial portion of the raw data available to a third party. Licensee may not create, offer, or sell a raw parcel-data product or service that competes with LandAI's data store, bulk data, or API products.
      </p>
      <p style={{ margin: "0 0 9px" }}>
        Licensee may not upload the raw data to, train, enrich, or use it with a public artificial intelligence large language model or other public third-party AI service, nor may Licensee use the raw data with any blockchain product or service. Licensee may use the data with its own private, proprietary AI systems.
      </p>
      <p style={{ margin: "0 0 9px" }}>
        Licensee may load the data into internal databases, GIS systems, search servers, analytics tools, geocoding systems, reverse-geocoding systems, and internal applications. Licensee may use the data to label other geometries, associate parcel attributes with buildings or coordinates, create derived analyses, and render parcel polygons in customer-facing maps if the implementation reasonably prevents users from extracting a substantial portion of the parcel geometries or raw records.
      </p>
      <p style={{ margin: "0 0 9px" }}>
        Licensee may create derivative works, analyses, reports, visualizations, models, scores, and aggregated outputs based on the data, so long as those outputs do not disclose or redistribute a substantial portion of the raw data.
      </p>
      <p style={{ margin: "0 0 9px" }}>
        Licensee will not remove, obscure, or alter any proprietary notices included with the data. Attribution to LandAI as a data source is appreciated, and should be included where reasonably practical for public-facing maps, pages, reports, or applications that use the purchased data.
      </p>

      <LicenseHeading>Limited Warranty</LicenseHeading>
      <p style={{ margin: "0 0 9px" }}>
        The data is provided "as is" and "as available", without warranty or support of any kind. LandAI does not warrant that the data is complete, current, accurate, error-free, fit for a particular purpose, or suitable for legal, surveying, title, tax, valuation, lending, emergency, or regulatory decisions. Licensee relies on the data at Licensee's own risk.
      </p>

      <LicenseHeading>Term and Termination</LicenseHeading>
      <p style={{ margin: "0 0 9px" }}>
        The license term begins on the purchase date and continues until the one-year anniversary of that date unless terminated earlier under this Agreement or extended in a separate written agreement. When the term ends, Licensee must stop using and delete the raw data unless LandAI has granted a renewal or replacement license.
      </p>
      <p style={{ margin: "0 0 9px" }}>
        LandAI may terminate this license if Licensee materially breaches these terms. Upon termination, Licensee must stop using and delete the raw data.
      </p>

      <LicenseHeading>No Refunds</LicenseHeading>
      <p style={{ margin: "0 0 9px" }}>
        All purchases are final. LandAI does not provide refunds, credits, or prorated billing for purchased data.
      </p>

      <LicenseHeading>Governing Law and Forum</LicenseHeading>
      <p style={{ margin: 0 }}>
        This Agreement is governed by the laws of the State of North Carolina, without regard to conflict-of-law rules. Any legal action to enforce this Agreement must be brought in the state or federal courts located in Wake County, North Carolina, unless applicable law requires otherwise. The prevailing party in an action to enforce this Agreement may recover reasonable legal fees and costs.
      </p>
    </div>
  );
}

function CartView({ cart, setCart, onHome, onBrowse, onBack }) {
  const [buyer, setBuyer] = useState({ name: "", email: "" });
  const [checks, setChecks] = useState({ license: false, sample: false, emails: false });
  const [checkoutBusy, setCheckoutBusy] = useState(false);
  const [checkoutError, setCheckoutError] = useState("");
  const total = cart.reduce((s, i) => s + i.price, 0);
  const remove = (idx) => setCart(c => c.filter((_, i) => i !== idx));
  const tog = (k) => setChecks(c => ({ ...c, [k]: !c[k] }));
  const setBuyerField = (key, value) => {
    setBuyer(current => ({ ...current, [key]: value }));
    setCheckoutError("");
  };
  const canCheckout = cart.length > 0 && checks.license && buyer.name.trim() && buyer.email.trim() && !checkoutBusy;
  const startCheckout = async () => {
    if (!cart.length) return;
    if (!buyer.name.trim() || !buyer.email.trim()) {
      setCheckoutError("Enter your name and email before checkout.");
      return;
    }
    if (!checks.license) {
      setCheckoutError("Accept the parcel data license before checkout.");
      return;
    }
    setCheckoutBusy(true);
    setCheckoutError("");
    try {
      const response = await fetch("/api/checkout-create-session", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          buyer,
          items: cart,
          licenseAccepted: checks.license,
          sampleAcknowledged: checks.sample,
          marketingOptIn: checks.emails,
        }),
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok || !payload.url) throw new Error(payload.error || "Checkout could not be started.");
      window.location.assign(payload.url);
    } catch (err) {
      setCheckoutError(err.message || "Checkout could not be started.");
      setCheckoutBusy(false);
    }
  };
  return (
    <div className="landai-store-shell" style={{ width: W, minHeight: STORE_PAGE_HEIGHT, margin: "0 auto", background: PAPER, fontFamily: "'Hanken Grotesk', system-ui, sans-serif", overflow: "hidden", boxShadow: "0 40px 120px rgba(16,40,30,0.18)", display: "flex", flexDirection: "column" }}>
      <Nav onHome={onHome} onBrowse={onBrowse} />
      <div className="landai-cart-split" style={{ display: "flex", alignItems: "stretch", flex: 1 }}>
        {/* LEFT — cart */}
        <div className="landai-cart-left" style={{ flex: 1, padding: "44px 56px" }}>
          <h1 style={{ fontSize: 34, color: INK, letterSpacing: -0.8, margin: 0 }}>Shopping cart</h1>
          <div onClick={onBack || onBrowse} style={{ display: "inline-flex", alignItems: "center", gap: 7, color: GREEN, fontSize: 14, fontWeight: 700, cursor: "pointer", margin: "12px 0 28px" }}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke={GREEN} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6" /></svg>
            Back to previous page
          </div>
          {cart.length === 0 ? (
            <div style={{ padding: "60px 0", color: GRAY, fontSize: 16 }}>Your cart is empty. <span onClick={onBrowse} style={{ color: GREEN, fontWeight: 700, cursor: "pointer" }}>Browse parcel data →</span></div>
          ) : (
            <div className="landai-cart-table">
              <div style={{ display: "flex", padding: "0 0 12px", borderBottom: `1.5px solid ${BORDER}`, fontSize: 12, fontWeight: 700, letterSpacing: 0.6, color: GRAY, textTransform: "uppercase" }}>
                <span style={{ flex: "0 0 170px" }}>Place</span>
                <span style={{ flex: 1 }}>Product</span>
                <span style={{ flex: "0 0 130px", textAlign: "right" }}>Record count</span>
                <span style={{ flex: "0 0 90px", textAlign: "right" }}>Price</span>
                <span style={{ flex: "0 0 40px" }} />
              </div>
              {cart.map((it, i) => (
                <div key={i} style={{ display: "flex", alignItems: "center", padding: "18px 0", borderBottom: `1px solid #eeece2` }}>
                  <span style={{ flex: "0 0 170px", fontSize: 15, fontWeight: 700, color: GREEN }}>{it.place}</span>
                  <span style={{ flex: 1, fontSize: 15, color: INK }}>{it.product}</span>
                  <span style={{ flex: "0 0 130px", textAlign: "right" }}>
                    <div style={{ fontSize: 14, color: INK, fontFamily: "'JetBrains Mono', monospace" }}>{it.records}</div>
                    <span style={{ display: "inline-block", marginTop: 4, background: "#e7efe9", color: "#2E7D5B", fontSize: 10, fontWeight: 700, letterSpacing: 0.4, padding: "3px 8px", borderRadius: 6 }}>PARCEL DATA</span>
                  </span>
                  <span style={{ flex: "0 0 90px", textAlign: "right", fontSize: 15, fontWeight: 700, color: INK }}>${it.price.toFixed(2)}</span>
                  <span style={{ flex: "0 0 40px", textAlign: "right" }}>
                    <svg onClick={() => remove(i)} width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="#b0473c" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ cursor: "pointer" }}><path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6" /></svg>
                  </span>
                </div>
              ))}
              <div style={{ display: "flex", alignItems: "center", padding: "18px 0", fontWeight: 800 }}>
                <span style={{ flex: 1, fontSize: 16, color: INK }}>Total</span>
                <span style={{ flex: "0 0 130px" }} />
                <span style={{ flex: "0 0 90px", textAlign: "right", fontSize: 17, color: INK }}>${total.toFixed(2)}</span>
                <span style={{ flex: "0 0 40px" }} />
              </div>
            </div>
          )}
        </div>

        {/* RIGHT — checkout */}
        <div className="landai-cart-right" style={{ flex: "0 0 480px", background: CREAM, padding: "44px 48px 56px", borderLeft: `1px solid ${BORDER}` }}>
          <h2 style={{ fontSize: 30, color: INK, letterSpacing: -0.6, margin: 0 }}>Check out</h2>
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 26, fontWeight: 700, color: INK, margin: "8px 0 26px" }}>${total.toFixed(2)}</div>

          <CartField label="Full name" sub="Used for your Stripe receipt and order record." placeholder="Name" value={buyer.name} onChange={value => setBuyerField("name", value)} />
          <CartField label="Email address" placeholder="Email address" type="email" value={buyer.email} onChange={value => setBuyerField("email", value)} />

          <div style={{ height: 1, background: BORDER, margin: "24px 0" }} />
          <div style={{ fontSize: 15, fontWeight: 700, color: INK, marginBottom: 4 }}>Payment details</div>
          <div style={{ fontSize: 13, color: GRAY, lineHeight: 1.5, marginBottom: 16 }}>Card and wallet payments are collected on Stripe's secure checkout page. LandAI never sees or stores card numbers.</div>
          <div style={{ background: "#fff", border: `1px solid ${BORDER}`, borderRadius: 12, padding: 16, display: "flex", gap: 12, alignItems: "flex-start", marginBottom: 18 }}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke={GREEN} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}><rect x="2" y="5" width="20" height="14" rx="2" /><path d="M2 10h20" /></svg>
            <div>
              <div style={{ fontSize: 14, fontWeight: 800, color: INK }}>Secure checkout by Stripe</div>
              <div style={{ fontSize: 12.5, color: GRAY, lineHeight: 1.45, marginTop: 2 }}>You'll review the final total and pay on Stripe, then return to LandAI.</div>
            </div>
          </div>

          <div style={{ fontSize: 14, fontWeight: 700, color: INK, margin: "20px 0 12px" }}>Our parcel data license agreement</div>
          <LandAiParcelDataLicense />
          <Checkbox checked={checks.license} onToggle={() => tog("license")}>I accept the <span style={{ color: GREEN, fontWeight: 800 }}>LandAI parcel data agreement</span> and <span style={{ color: GREEN, fontWeight: 800 }}>privacy policy</span></Checkbox>
          <Checkbox checked={checks.sample} onToggle={() => tog("sample")}>I have seen the sample file and coverage report on each county's store page</Checkbox>
          <Checkbox checked={checks.emails} onToggle={() => tog("emails")}>Sign me up for infrequent emails, including discounts on data updates</Checkbox>

          <div style={{ fontSize: 14, fontWeight: 700, color: INK, margin: "8px 0 6px" }}>How we deliver the data</div>
          <div style={{ fontSize: 13, color: GRAY, lineHeight: 1.5, marginBottom: 22 }}>After checkout, you'll land on a confirmation page with download links for your purchased data. We'll also email those links to you for future reference. Download links stay active for 45 days.</div>

          {checkoutError && <div style={{ margin: "0 0 14px", color: "#b0473c", fontSize: 13, lineHeight: 1.4, fontWeight: 700 }}>{checkoutError}</div>}
          <button disabled={!canCheckout} onClick={startCheckout} style={{ width: "100%", border: "none", background: canCheckout ? INK : "#bcbcb4", color: "#fff", fontSize: 16, fontWeight: 700, padding: "17px 0", borderRadius: 99, cursor: canCheckout ? "pointer" : "default", fontFamily: "'JetBrains Mono', monospace", letterSpacing: 1 }}>{checkoutBusy ? "STARTING CHECKOUT..." : "CONTINUE TO SECURE CHECKOUT"}</button>
        </div>
      </div>
    </div>
  );
}

function CheckoutSuccessView({ onHome, onBrowse }) {
  const sessionId = new URLSearchParams(window.location.search).get("session_id") || "";
  return (
    <div className="landai-store-shell" style={{ width: W, minHeight: STORE_PAGE_HEIGHT, margin: "0 auto", background: PAPER, fontFamily: "'Hanken Grotesk', system-ui, sans-serif", overflow: "hidden", boxShadow: "0 40px 120px rgba(16,40,30,0.18)", display: "flex", flexDirection: "column" }}>
      <Nav onHome={onHome} onBrowse={onBrowse} />
      <div style={{ flex: 1, display: "grid", placeItems: "center", padding: "60px 22px" }}>
        <div style={{ maxWidth: 620, width: "100%", background: "#fff", border: `1px solid ${BORDER}`, borderRadius: 18, padding: "38px 42px", boxShadow: "0 24px 60px rgba(16,40,30,0.10)" }}>
          <div style={{ width: 52, height: 52, borderRadius: 99, background: "#e7f7eb", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 20 }}>
            <svg width="27" height="27" viewBox="0 0 24 24" fill="none" stroke={SUPPORTED_COUNTY_COMPLETE_OUTLINE_COLOR} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
          </div>
          <div style={{ fontSize: 13, fontWeight: 800, letterSpacing: 1.3, color: GREEN, textTransform: "uppercase", fontFamily: "'JetBrains Mono', monospace", marginBottom: 8 }}>Payment received</div>
          <h1 style={{ margin: 0, color: INK, fontSize: 38, letterSpacing: -1 }}>Your LandAI data order is in.</h1>
          <p style={{ fontSize: 16, lineHeight: 1.6, color: GRAY, margin: "16px 0 0" }}>
            Stripe confirmed the payment and LandAI has been notified. We are wiring automated delivery next; for now our team will follow up with access details for the parcel data you purchased.
          </p>
          {sessionId && (
            <div style={{ marginTop: 22, border: `1px solid ${BORDER}`, borderRadius: 10, background: PAPER, padding: "12px 14px", color: GRAY, fontSize: 12, fontFamily: "'JetBrains Mono', monospace", overflowWrap: "anywhere" }}>
              Stripe session: {sessionId}
            </div>
          )}
          <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginTop: 28 }}>
            <button onClick={onBrowse} style={{ border: "none", background: INK, color: "#fff", fontSize: 15, fontWeight: 800, padding: "13px 22px", borderRadius: 99, cursor: "pointer", fontFamily: "inherit" }}>Back to data store</button>
            <button onClick={onHome} style={{ border: `1.5px solid ${INK}`, background: "#fff", color: INK, fontSize: 15, fontWeight: 800, padding: "13px 22px", borderRadius: 99, cursor: "pointer", fontFamily: "inherit" }}>LandAI home</button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- page ----------
function LandingView({ onBrowse }) {
  return (
    <div className="landai-page-shell" style={{ width: W, margin: "0 auto", background: PAPER, fontFamily: "'Hanken Grotesk', system-ui, sans-serif", overflow: "hidden", boxShadow: "0 40px 120px rgba(16,40,30,0.18)" }}>
      <Nav onBrowse={onBrowse} />
      <Hero onBrowse={onBrowse} />
      <ValueBand />
      <HowItWorks />
      <Coverage onBrowse={onBrowse} />
      <Difference />
      <ContactForm />
      <SecondaryCTA />
      <FinalCTA onBrowse={onBrowse} />
      <Footer />
    </div>
  );
}

function DataStore() {
  const initialRoute = readDataStoreRoute();
  const [view, setView] = useState(initialRoute.view);
  const [stateName, setStateName] = useState(initialRoute.stateName);
  const [countyName, setCountyName] = useState(initialRoute.countyName);
  const [supportDoc, setSupportDoc] = useState(initialRoute.supportDoc);
  const [cart, setCart] = useState(() => readStoredDataStoreCart());
  const [cartReturnRoute, setCartReturnRoute] = useState(initialRoute.view === "cart" ? normalizeStoreRoute({ view: "browse" }) : initialRoute);

  const applyDataRoute = (route, replace = false) => {
    const current = normalizeStoreRoute({ view, stateName, countyName, supportDoc });
    const next = normalizeStoreRoute(route, { view, stateName, countyName, supportDoc });
    if (next.view === "cart" && current.view !== "cart") {
      setCartReturnRoute(current);
    } else if (next.view !== "cart" && next.view !== "checkoutSuccess") {
      setCartReturnRoute(next);
    }
    setView(next.view);
    setStateName(next.stateName);
    setCountyName(next.countyName);
    setSupportDoc(next.supportDoc);
    const path = dataStorePath(next.view, next.stateName, next.countyName, next.supportDoc);
    if (window.location.pathname !== path) {
      window.history[replace ? "replaceState" : "pushState"]({ dataStoreView: next.view }, "", path);
    }
    window.scrollTo(0, 0);
  };

  useEffect(() => {
    const syncFromPath = () => {
      const next = readDataStoreRoute();
      setView(next.view);
      setStateName(next.stateName);
      setCountyName(next.countyName);
      setSupportDoc(next.supportDoc);
      if (next.view !== "cart" && next.view !== "checkoutSuccess") {
        setCartReturnRoute(next);
      }
    };

    const route = readDataStoreRoute();
    const canonicalPath = dataStorePath(route.view, route.stateName, route.countyName, route.supportDoc);
    if (window.location.pathname !== canonicalPath) {
      window.history.replaceState({ dataStoreView: route.view }, "", canonicalPath);
    }

    window.addEventListener("popstate", syncFromPath);
    return () => window.removeEventListener("popstate", syncFromPath);
  }, []);

  useEffect(() => {
    writeStoredDataStoreCart(cart);
  }, [cart]);

  useEffect(() => {
    const syncStoredCart = (event) => {
      if (event.key === DATA_STORE_CART_STORAGE_KEY) setCart(readStoredDataStoreCart());
    };
    window.addEventListener("storage", syncStoredCart);
    return () => window.removeEventListener("storage", syncStoredCart);
  }, []);

  useEffect(() => {
    if (view === "checkoutSuccess") setCart([]);
  }, [view]);

  const browse = () => applyDataRoute({ view: "browse" });
  const home = () => applyDataRoute({ view: "landing" });
  const openState = (s) => applyDataRoute({ view: "state", stateName: s });
  const openCounty = (c, s = stateName) => applyDataRoute({ view: "browseCounty", stateName: s, countyName: c });
  const openSupport = (d) => applyDataRoute({ view: "support", supportDoc: d });
  const openCoverage = () => applyDataRoute({ view: "coverage" });
  const backToState = () => applyDataRoute({ view: "state" });
  const backFromCart = () => applyDataRoute(cartReturnRoute && cartReturnRoute.view !== "cart" ? cartReturnRoute : { view: "browse" });
  const addItem = (item) => setCart(c => c.some(x => x.place === item.place && x.product === item.product) ? c : [...c, item]);
  const stateAbbr = (stateCodeForName(stateName) || "").toUpperCase();
  const buyState = async () => {
    let records = "Current coverage";
    let supportedCount = 0;
    try {
      const geojson = await loadDataStoreCoverageGeoJSON();
      const parcelTotal = (geojson?.features || []).reduce((sum, feature) => {
        const fips = countyFipsFromFeature(feature);
        const featureStateName = stateNameForCountyFips(fips) || feature?.properties?.STATE_NAME || "";
        if (slugify(featureStateName) !== slugify(stateName)) return sum;
        if (!dataStoreCountyIsSupported(feature)) return sum;
        supportedCount += 1;
        const meta = dataStoreCountyMetadataFromFeature(feature);
        return sum + (meta.parcelCount || 0);
      }, 0);
      if (parcelTotal > 0) records = parcelTotal.toLocaleString();
    } catch (err) {
      console.warn("[data-store-state] State cart record count unavailable", err);
    }
    if (supportedCount <= 0) {
      window.alert("Statewide data is not available for this state yet.");
      return;
    }
    addItem({
      type: "state",
      place: stateName,
      stateName,
      stateCode: stateAbbr,
      supportedCountyCount: supportedCount,
      product: "Statewide parcel data",
      records,
      price: supportedCount * STATE_STORE_PRICE_PER_SUPPORTED_COUNTY,
    });
    applyDataRoute({ view: "cart" });
  };
  const addCounty = (c, price, records, options = {}) => {
    const format = options.format || INCLUDED_FORMAT_LABEL;
    const addons = options.addons || {};
    addItem({
      type: "county",
      place: `${c}, ${stateAbbr}`.replace(", ,", ","),
      countyName: c,
      stateName,
      stateCode: stateAbbr,
      format,
      addons,
      apiAccess: options.apiAccess === true,
      product: `County parcel data · ${format}${options.apiAccess === true ? " · API request" : ""}`,
      records,
      price,
    });
    applyDataRoute({ view: "cart" });
  };
  const openCart = () => applyDataRoute({ view: "cart" });
  let content;
  if (view === "landing") content = <LandingView onBrowse={browse} onSupport={openSupport} />;
  else if (view === "state") content = <StateView stateName={stateName} onHome={home} onBrowse={browse} onBack={browse} onCounty={openCounty} onCoverage={openCoverage} onBuy={buyState} onAdd={addCounty} onCart={openCart} cartCount={cart.length} />;
  else if (view === "coverage") content = <CoverageReportView stateName={stateName} onHome={home} onBrowse={browse} onBack={backToState} onCounty={openCounty} />;
  else if (view === "county") content = <CountyView countyName={countyName} stateName={stateName} onHome={home} onBrowse={browse} onBack={backToState} onCounty={openCounty} onAdd={addCounty} onCart={openCart} cartCount={cart.length} />;
  else if (view === "support") content = <SupportView doc={supportDoc} onHome={home} onBrowse={browse} onBack={browse} onDocChange={openSupport} />;
  else if (view === "cart") content = <CartView cart={cart} setCart={setCart} onHome={home} onBrowse={browse} onBack={backFromCart} />;
  else if (view === "checkoutSuccess") content = <CheckoutSuccessView onHome={home} onBrowse={browse} />;
  else if (view === "browseCounty") content = <BrowseStore onHome={home} onBrowse={browse} onState={openState} onCounty={openCounty} onSupport={openSupport} onCart={openCart} onAdd={addCounty} cartCount={cart.length} initialCounty={{ countyName, stateName }} />;
  else content = <BrowseStore onHome={home} onBrowse={browse} onState={openState} onCounty={openCounty} onSupport={openSupport} onCart={openCart} onAdd={addCounty} cartCount={cart.length} />;

  return (
    <>
      <MobileStyles />
      {content}
    </>
  );
}

window.DataStore = DataStore;
})();
