// Coverage section — interactive US map + county list.
// Prefer live rollup from GCP get_parcel /api/counties/all (LandAI county_registry).
// Fallback: FALLBACK_* static guesses if the fetch fails.

const COVERAGE_API_BASE = (typeof window !== "undefined" && window.LANDAI_COVERAGE_API_BASE
  ? String(window.LANDAI_COVERAGE_API_BASE).replace(/\/$/, "")
  : "https://us-central1-landai-476914.cloudfunctions.net/get_parcel");

// US county-equivalent counts per state (Census administrative units; VA includes independent cities).
const STATE_COUNTY_TOTALS = {
  AL:67, AK:30, AZ:15, AR:75, CA:58, CO:64, CT:9, DE:3, DC:1, FL:67, GA:159, HI:5, ID:44, IL:102, IN:92, IA:99, KS:105, KY:120, LA:64, ME:16, MD:24, MA:14, MI:83, MN:87, MS:82, MO:115, MT:56, NE:93, NV:17, NH:10, NJ:21, NM:33, NY:62, NC:100, ND:53, OH:88, OK:77, OR:36, PA:67, RI:5, SC:46, SD:66, TN:95, TX:254, UT:29, VT:14, VA:133, WA:39, WV:55, WI:72, WY:23,
};
const WAITLIST_ZERO_STATES = new Set(["RI","VT","DC"]);

const FALLBACK_STATE_STATUS = {
  AL:"live", AK:"planned", AZ:"live", AR:"early", CA:"live", CO:"live", CT:"early",
  DE:"early", FL:"live", GA:"live", HI:"planned", ID:"early", IL:"live", IN:"live",
  IA:"early", KS:"early", KY:"live", LA:"early", ME:"planned", MD:"early", MA:"early",
  MI:"live", MN:"live", MS:"early", MO:"live", MT:"live", NE:"early", NV:"live",
  NH:"planned", NJ:"early", NM:"early", NY:"live", NC:"live", ND:"planned", OH:"live",
  OK:"live", OR:"live", PA:"live", RI:"waitlist", SC:"live", SD:"early", TN:"live",
  TX:"live", UT:"live", VT:"waitlist", VA:"live", WA:"live", WV:"early", WI:"live",
  WY:"early", DC:"waitlist",
};

function rollupStateStatus(enabledCountyCount, stateCode) {
  if (enabledCountyCount <= 0) {
    return WAITLIST_ZERO_STATES.has(stateCode) ? "waitlist" : "planned";
  }
  const total = STATE_COUNTY_TOTALS[stateCode];
  if (!total) return "early";
  const ratio = enabledCountyCount / total;
  return ratio >= 0.98 ? "live" : "early";
}

function shortenCountyLabel(name) {
  if (!name) return "";
  return String(name).replace(/\s+County\s*$/i, "").trim();
}

function formatCompactNumber(n) {
  if (!Number.isFinite(n) || n < 0) return "\u2014";
  try {
    return new Intl.NumberFormat("en-US", {
      notation: "compact",
      compactDisplay: "short",
      maximumFractionDigits: 1,
    }).format(Math.round(n));
  } catch (e) {
    if (n >= 1e6) return Math.round(n / 1e6) + "M";
    return String(Math.round(n));
  }
}

const STATE_NAMES = {
  AL:"Alabama",AK:"Alaska",AZ:"Arizona",AR:"Arkansas",CA:"California",CO:"Colorado",CT:"Connecticut",
  DE:"Delaware",FL:"Florida",GA:"Georgia",HI:"Hawaii",ID:"Idaho",IL:"Illinois",IN:"Indiana",
  IA:"Iowa",KS:"Kansas",KY:"Kentucky",LA:"Louisiana",ME:"Maine",MD:"Maryland",MA:"Massachusetts",
  MI:"Michigan",MN:"Minnesota",MS:"Mississippi",MO:"Missouri",MT:"Montana",NE:"Nebraska",NV:"Nevada",
  NH:"New Hampshire",NJ:"New Jersey",NM:"New Mexico",NY:"New York",NC:"North Carolina",ND:"North Dakota",
  OH:"Ohio",OK:"Oklahoma",OR:"Oregon",PA:"Pennsylvania",RI:"Rhode Island",SC:"South Carolina",
  SD:"South Dakota",TN:"Tennessee",TX:"Texas",UT:"Utah",VT:"Vermont",VA:"Virginia",WA:"Washington",
  WV:"West Virginia",WI:"Wisconsin",WY:"Wyoming",DC:"District of Columbia"
};

// Featured counties when API unavailable (marketing samples)
const FALLBACK_FEATURED_COUNTIES = {
  TX: ["Brazos","Harris","Travis","Bexar","Dallas","Tarrant","Williamson","Hays","Fort Bend","Denton","Collin","El Paso"],
  CA: ["Los Angeles","San Diego","Orange","Santa Clara","Riverside","Alameda","Sacramento","Fresno","Kern","Ventura"],
  FL: ["Miami-Dade","Broward","Palm Beach","Orange","Hillsborough","Pinellas","Duval","Lee","Polk","Brevard"],
  NY: ["New York","Kings","Queens","Bronx","Suffolk","Nassau","Westchester","Erie","Monroe","Onondaga"],
  CO: ["Denver","El Paso","Arapahoe","Jefferson","Adams","Larimer","Douglas","Boulder","Weld","Pueblo"],
  MT: ["Yellowstone","Missoula","Gallatin","Flathead","Cascade","Lewis and Clark","Ravalli","Silver Bow"],
  GA: ["Fulton","Gwinnett","Cobb","DeKalb","Chatham","Cherokee","Forsyth","Hall","Henry","Clayton"],
  TN: ["Davidson","Shelby","Knox","Hamilton","Rutherford","Williamson","Montgomery","Sumner","Wilson","Blount"],
  AZ: ["Maricopa","Pima","Pinal","Yavapai","Mohave","Coconino","Cochise","Yuma","Navajo","Apache"],
  NC: ["Wake","Mecklenburg","Guilford","Forsyth","Cumberland","Durham","Buncombe","Union","New Hanover","Henderson"],
  OH: ["Franklin","Cuyahoga","Hamilton","Summit","Montgomery","Lucas","Butler","Stark","Lorain","Warren"],
  MI: ["Wayne","Oakland","Macomb","Kent","Genesee","Washtenaw","Ottawa","Ingham","Kalamazoo","Livingston"],
  WA: ["King","Pierce","Snohomish","Spokane","Clark","Thurston","Kitsap","Yakima","Whatcom","Benton"],
  OR: ["Multnomah","Washington","Clackamas","Lane","Marion","Jackson","Deschutes","Linn","Douglas","Yamhill"],
  VA: ["Fairfax","Prince William","Loudoun","Henrico","Chesterfield","Virginia Beach","Arlington","Norfolk","Richmond"],
  IL: ["Cook","DuPage","Lake","Will","Kane","McHenry","Winnebago","St. Clair","Madison","Peoria"],
};

// Very simplified US state grid positions (approx) — enough for a schematic choropleth
const STATE_GRID = {
  //           col, row
  AK:[0,6], ME:[11,0], VT:[10,1], NH:[11,1], MA:[11,2], CT:[10,3], RI:[11,3],
  WA:[1,1], ID:[2,1], MT:[3,1], ND:[4,1], MN:[5,1], WI:[6,1], MI:[7,1], NY:[9,1], PA:[9,2],
  OR:[1,2], NV:[1,3], UT:[2,3], WY:[3,2], SD:[4,2], IA:[5,2], IL:[6,2], IN:[7,2], OH:[8,2],
  NJ:[10,2], DE:[10,3], MD:[9,3], DC:[9,4],
  CA:[0,3], AZ:[2,4], CO:[3,3], NE:[4,3], MO:[5,3], KY:[7,3], WV:[8,3], VA:[9,3],
  NM:[2,5], KS:[4,4], AR:[5,4], TN:[6,4], NC:[8,4], SC:[8,5],
  TX:[3,5], OK:[4,5], LA:[5,5], MS:[6,5], AL:[7,5], GA:[8,6],
  FL:[9,6], HI:[0,7]
};

const STATUS_STYLE = {
  live:     { dot: "#0E1220", bg: "var(--ink)",        fg: "var(--bg)",   label: "Live" },
  early:    { dot: "#4F69A3", bg: "var(--navy)",       fg: "#fff",        label: "Early access" },
  planned:  { dot: "#E6D7B8", bg: "var(--beige)",      fg: "#0E1220",     label: "Q3 2026" },
  waitlist: { dot: "#D4D0C4", bg: "var(--bg-2)",       fg: "var(--muted)",label: "Waitlist" },
};

function StateTile({ code, status, onHover, onLeave, active, onClick }) {
  const s = STATUS_STYLE[status];
  return (
    <button
      onMouseEnter={onHover}
      onMouseLeave={onLeave}
      onFocus={onHover}
      onBlur={onLeave}
      onClick={onClick}
      style={{
        width: 54, height: 54,
        background: s.bg, color: s.fg,
        border: "1px solid " + (active ? "var(--blue)" : "var(--line-2)"),
        borderRadius: 8,
        fontFamily: "'JetBrains Mono', monospace",
        fontSize: 11, fontWeight: 600, letterSpacing: "0.04em",
        cursor: "pointer",
        display: "grid", placeItems: "center",
        transform: active ? "scale(1.08)" : "scale(1)",
        transition: "transform .15s, border-color .15s",
        boxShadow: active ? "0 4px 14px rgba(1,179,241,0.25)" : "none",
        padding: 0,
      }}
      aria-label={STATE_NAMES[code] + " — " + s.label}
    >
      {code}
    </button>
  );
}

function Coverage() {
  const [sel, setSel] = React.useState("TX");
  const [hover, setHover] = React.useState(null);
  const [filter, setFilter] = React.useState("all");
  const [query, setQuery] = React.useState("");
  /** @type {[null|'loading'|{kind:'live',statusMap:any,byState:any,totalParcels:number,meta:any}|{kind:'fallback',reason:string}]} */
  const [rollout, setRollout] = React.useState("loading");

  React.useEffect(() => {
    let cancelled = false;
    const url = COVERAGE_API_BASE + "/api/counties/all";
    fetch(url)
      .then(function (r) {
        if (!r.ok) throw new Error(String(r.status));
        return r.json();
      })
      .then(function (data) {
        if (cancelled) return;
        var counties = data.counties || [];
        /** @type {Record<string, Object[]>} */
        var byState = {};
        var totalParcels = 0;
        counties.forEach(function (c) {
          var code = String(c.state_code || '').trim().toUpperCase();
          if (!code || !STATE_NAMES[code]) return;
          if (!byState[code]) byState[code] = [];
          byState[code].push(c);
          var pc = Number(c.parcel_count) || 0;
          totalParcels += pc;
        });
        var statusMap = {};
        Object.keys(STATE_NAMES).forEach(function (scode) {
          var n = (byState[scode] || []).length;
          statusMap[scode] = rollupStateStatus(n, scode);
        });
        setRollout({
          kind: "live",
          statusMap,
          byState,
          totalParcels,
          meta: data._meta || null,
        });
      })
      .catch(function () {
        if (!cancelled) setRollout({ kind: "fallback", reason: "api" });
      });
    return function () {
      cancelled = true;
    };
  }, []);

  var STATE_STATUS = FALLBACK_STATE_STATUS;
  /** @type {Record<string,string[]>} */
  var FEATURED_NAMES = FALLBACK_FEATURED_COUNTIES;
  var totalParcelLabel = "150M+";
  var coverageHint = '';

  if (rollout && rollout.kind === 'live') {
    STATE_STATUS = rollout.statusMap;
    totalParcelLabel =
      formatCompactNumber(rollout.totalParcels || 0) + " parcels indexed";
    coverageHint = "Rollout synced from LandAI.";
    FEATURED_NAMES = {};
    Object.keys(rollout.byState).forEach(function (code) {
      var rows = (rollout.byState[code] || []).slice();
      rows.sort(function (a, b) {
        return (Number(b.parcel_count) || 0) - (Number(a.parcel_count) || 0);
      });
      FEATURED_NAMES[code] = rows.slice(0, 14).map(function (r) { return shortenCountyLabel(r.county_name || ''); }).filter(Boolean);
    });
  } else if (rollout && rollout.kind === "fallback") {
    coverageHint =
      "Couldn\u2019t reach the live rollout API \u2014 showing a static preview.";
    totalParcelLabel = "\u2014";
    STATE_STATUS = FALLBACK_STATE_STATUS;
    FEATURED_NAMES = FALLBACK_FEATURED_COUNTIES;
  } else if (rollout === "loading") {
    coverageHint = "Loading rollout from LandAI servers\u2026";
    totalParcelLabel = "\u2014";
    STATE_STATUS = FALLBACK_STATE_STATUS;
    FEATURED_NAMES = FALLBACK_FEATURED_COUNTIES;
  }

  /** County names for dropdowns (sorted), by state — from API or fallback chips */
  var countiesDropdownByState = {};
  if (rollout && rollout.kind === 'live' && rollout.byState) {
    Object.keys(rollout.byState).forEach(function (code) {
      var sorted = rollout.byState[code].map(function (r) {
        return shortenCountyLabel(r.county_name || '');
      }).filter(Boolean).sort(function (a,b) {
        return a.localeCompare(b);
      });
      var seen = {};
      countiesDropdownByState[code] = sorted.filter(function (x) {
        if (seen[x]) return false;
        seen[x] = true;
        return true;
      });
    });
  }

  // Initialize MapLibre map (free OSM raster tiles — no API key required)
  React.useEffect(() => {
    if (!window.maplibregl) return;
    const el = document.getElementById("rollout-map");
    if (!el || el.dataset.inited) return;
    el.dataset.inited = "1";

    try {
      const map = new window.maplibregl.Map({
        container: el,
        style: {
          version: 8,
          sources: {
            "carto": {
              type: "raster",
              tiles: [
                "https://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}@2x.png",
                "https://b.basemaps.cartocdn.com/light_all/{z}/{x}/{y}@2x.png",
                "https://c.basemaps.cartocdn.com/light_all/{z}/{x}/{y}@2x.png",
                "https://d.basemaps.cartocdn.com/light_all/{z}/{x}/{y}@2x.png"
              ],
              tileSize: 256,
              attribution: "© OpenStreetMap © CARTO"
            }
          },
          layers: [{ id: "carto", type: "raster", source: "carto" }]
        },
        center: [-96.5, 38.5],
        zoom: 3.2,
        attributionControl: false,
      });
      map.addControl(new window.maplibregl.NavigationControl({ showCompass: false }), "top-right");
      map.addControl(new window.maplibregl.AttributionControl({ compact: true }));
      map.on("error", e => console.warn("Map error", e && e.error));

      // Force resize after layout settles — MapLibre sometimes initializes before container has dimensions
      const kick = () => { try { map.resize(); } catch(e){} };
      requestAnimationFrame(kick);
      setTimeout(kick, 100);
      setTimeout(kick, 400);

      // Also resize on container size changes
      if (window.ResizeObserver) {
        const ro = new ResizeObserver(kick);
        ro.observe(el);
      }
    } catch (err) {
      console.warn("Map init failed", err);
      el.innerHTML = '<div style="height:100%;display:grid;place-items:center;color:#fff;font-family:monospace;font-size:12px;letter-spacing:.06em;text-transform:uppercase;opacity:.6">Map unavailable</div>';
    }
  }, []);

  const cols = 12, rows = 8;
  const grid = [];
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      const code = Object.entries(STATE_GRID).find(([k,[cc,rr]]) => cc === c && rr === r)?.[0];
      grid.push({ r, c, code });
    }
  }

  const counts = Object.values(STATE_STATUS).reduce((a,s) => (a[s]=(a[s]||0)+1, a), {});
  const liveCount = counts.live || 0;

  const activeStatus = STATE_STATUS[sel];
  const activeCounties = FEATURED_NAMES[sel] || [];

  const shown = Object.entries(STATE_STATUS)
    .filter(([c,s]) => filter === "all" || s === filter)
    .filter(([c]) => !query || STATE_NAMES[c].toLowerCase().includes(query.toLowerCase()) || c.toLowerCase().includes(query.toLowerCase()))
    .sort(([a],[b]) => STATE_NAMES[a].localeCompare(STATE_NAMES[b]));

  return (
    <section id="coverage" style={{ borderTop: "1px solid var(--line-2)" }}>
      <div className="shell">
        <SectionHead label="Coverage" title="Nationwide — and <em>getting deeper.</em>"/>

        {coverageHint && (
          <p style={{
            margin: "-8px 0 28px",
            fontSize: 13,
            color: "var(--muted)",
          }}>
            {coverageHint}
            {rollout && rollout.kind === "live" && rollout.meta && rollout.meta.count != null && (
              <span>{` \u2014 ${rollout.meta.count} counties.`}</span>
            )}
          </p>
        )}

        {/* Stats row */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 0, border: "1px solid var(--line)", borderRadius: 16, overflow: "hidden", marginBottom: 40 }}>
          {[
            ["States live", liveCount, "live"],
            ["Early access", counts.early || 0, "early"],
            ["Roadmap", (counts.planned || 0) + (counts.waitlist || 0), "planned"],
            ["Total parcels", totalParcelLabel, null],
          ].map(([label, val, status], i) => (
            <div key={label} style={{
              padding: "22px 24px",
              borderLeft: i === 0 ? "none" : "1px solid var(--line-2)",
              background: "var(--bg)",
            }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                {status && <span style={{ width: 8, height: 8, borderRadius: 99, background: STATUS_STYLE[status].dot }}/>}
                <div className="caps mono" style={{ color: "var(--muted)" }}>{label}</div>
              </div>
              <div className="serif" style={{ fontSize: 44, lineHeight: 1, letterSpacing: "-0.02em", marginTop: 10 }}>
                {val}
              </div>
            </div>
          ))}
        </div>

        {/* Legend */}
        <div style={{ display: "flex", flexWrap: "wrap", gap: 16, marginBottom: 24 }}>
          {Object.entries(STATUS_STYLE).map(([k,v]) => (
            <button key={k}
              onClick={() => setFilter(filter === k ? "all" : k)}
              style={{
                display: "inline-flex", alignItems: "center", gap: 8,
                padding: "6px 12px",
                border: "1px solid " + (filter === k ? "var(--ink)" : "var(--line)"),
                borderRadius: 99,
                background: filter === k ? "var(--ink)" : "transparent",
                color: filter === k ? "var(--bg)" : "var(--ink)",
                fontSize: 12, cursor: "pointer",
                fontFamily: "inherit",
              }}>
              <span style={{ width: 10, height: 10, borderRadius: 3, background: v.dot }}/>
              {v.label}
            </button>
          ))}
          {filter !== "all" && (
            <button onClick={() => setFilter("all")} style={{ border: "none", background: "transparent", color: "var(--muted)", fontSize: 12, cursor: "pointer" }}>Clear filter</button>
          )}
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 40, alignItems: "start" }} className="coverage-grid">
          {/* Live Mapbox map */}
          <div style={{ border: "1px solid var(--line)", borderRadius: 20, padding: 24, background: "var(--bg)", position: "relative", display: "flex", flexDirection: "column" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
              <div className="caps mono" style={{ color: "var(--muted)" }}>US rollout map</div>
              <span className="chip">
                {rollout && rollout.kind === "live"
                  ? "Live · Counties API"
                  : "Preview · OSM"}
              </span>
            </div>
            <div id="rollout-map" style={{
              flex: 1,
              minHeight: 480,
              borderRadius: 14,
              overflow: "hidden",
              border: "1px solid var(--line-2)",
              background: "#0E1220",
            }}/>
            <div style={{ marginTop: 12, fontSize: 11, color: "var(--muted)", fontFamily: "'JetBrains Mono', monospace", letterSpacing: ".06em", textTransform: "uppercase" }}>
              Drag to pan · scroll to zoom
            </div>
          </div>

          {/* Detail panel */}
          <div style={{ border: "1px solid var(--line)", borderRadius: 20, background: "var(--bg)", overflow: "hidden", minHeight: 500 }}>
            <div style={{ padding: 24, borderBottom: "1px solid var(--line-2)" }}>
              <div className="caps mono" style={{ color: "var(--muted)" }}>{sel} · {STATUS_STYLE[activeStatus].label}</div>
              <div className="serif" style={{ fontSize: 36, lineHeight: 1.05, marginTop: 4 }}>{STATE_NAMES[sel]}</div>
              <p style={{ fontSize: 13, color: "var(--muted)", margin: "8px 0 0" }}>
                {activeStatus === "live" && "Full parcel coverage across all counties. Nightly refresh from county assessor feeds."}
                {activeStatus === "early" && "Early-access coverage. Major metros are live; rural counties rolling in this quarter."}
                {activeStatus === "planned" && "Scheduled for Q3 2026. Join the waitlist to be notified on launch."}
                {activeStatus === "waitlist" && "On the roadmap. Small state — join the waitlist to move it up."}
              </p>
            </div>

            <div style={{ padding: "16px 24px", borderBottom: "1px solid var(--line-2)", display: "flex", alignItems: "center", gap: 8 }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ color: "var(--muted)" }}><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.35-4.35"/></svg>
              <input
                value={query}
                onChange={e => setQuery(e.target.value)}
                placeholder="Search states…"
                style={{ flex: 1, border: "none", outline: "none", background: "transparent", fontSize: 13, fontFamily: "inherit", color: "var(--ink)" }}
              />
            </div>

            <div style={{ maxHeight: 340, overflow: "auto" }}>
              {activeCounties.length > 0 && (
                <div style={{ padding: "16px 24px", borderBottom: "1px solid var(--line-2)" }}>
                  <div className="caps mono" style={{ color: "var(--muted)", marginBottom: 10 }}>Featured counties in {sel}</div>
                  <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                    {activeCounties.map(c => (
                      <span key={c} className="chip" style={{ background: "var(--bg)", color: "var(--ink-2)" }}>{c}</span>
                    ))}
                  </div>
                </div>
              )}

              <div>
                {shown.map(([code, status]) => (
                  <button
                    key={code}
                    onClick={() => setSel(code)}
                    style={{
                      width: "100%",
                      padding: "12px 24px",
                      border: "none",
                      borderBottom: "1px solid var(--line-2)",
                      background: sel === code ? "var(--bg-2)" : "transparent",
                      display: "flex", alignItems: "center", gap: 12,
                      cursor: "pointer",
                      fontFamily: "inherit",
                      textAlign: "left",
                      color: "var(--ink)",
                    }}
                  >
                    <span style={{ width: 8, height: 8, borderRadius: 99, background: STATUS_STYLE[status].dot, flexShrink: 0 }}/>
                    <span style={{ fontWeight: 500, fontSize: 14 }}>{STATE_NAMES[code]}</span>
                    <span className="mono" style={{ color: "var(--muted)", fontSize: 11 }}>{code}</span>
                    <span style={{ marginLeft: "auto", fontSize: 11, color: "var(--muted)" }}>{STATUS_STYLE[status].label}</span>
                  </button>
                ))}
                {shown.length === 0 && (
                  <div style={{ padding: 32, textAlign: "center", color: "var(--muted)", fontSize: 13 }}>No states match.</div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Waitlist CTA */}
        <WaitlistCTA countiesByState={countiesDropdownByState} featuredFallback={FALLBACK_FEATURED_COUNTIES}/>
      </div>
    </section>
  );
}

function WaitlistCTA({ countiesByState = {}, featuredFallback = {} }) {
  const [state, setState] = React.useState("");
  const [county, setCounty] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [submitted, setSubmitted] = React.useState(false);

  const stateOptions = Object.entries(STATE_NAMES).sort((a,b) => a[1].localeCompare(b[1]));
  const apiPick = state ? countiesByState[state] : null;
  const hasApi = Array.isArray(apiPick) && apiPick.length > 0;
  const fallbackPick = featuredFallback[state] || [];
  const countyOptions = state ? (hasApi ? apiPick : fallbackPick) : [];

  const inputStyle = {
    padding: "12px 16px",
    border: "1px solid var(--line)",
    borderRadius: 12,
    background: "var(--bg)",
    fontSize: 14,
    fontFamily: "inherit",
    outline: "none",
    color: "var(--ink)",
    width: "100%",
    boxSizing: "border-box",
    appearance: "none",
    WebkitAppearance: "none",
  };

  const selectStyle = {
    ...inputStyle,
    backgroundImage: 'url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' width=\'12\' height=\'8\' viewBox=\'0 0 12 8\' fill=\'none\' stroke=\'%236B6F7E\' stroke-width=\'1.5\'><path d=\'M1 1l5 5 5-5\'/></svg>")',
    backgroundRepeat: "no-repeat",
    backgroundPosition: "right 14px center",
    paddingRight: 36,
  };

  function handleSubmit(e) {
    e.preventDefault();
    if (!state || !email) return;
    setSubmitted(true);
  }

  return (
    <div style={{ marginTop: 40, padding: "32px 36px", border: "1px solid var(--line)", borderRadius: 20, background: "var(--bg-2)" }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1.6fr", gap: 32, alignItems: "start" }} className="waitlist-grid">
        <div>
          <div className="serif" style={{ fontSize: 28, lineHeight: 1.05, letterSpacing: "-0.01em" }}>Don't see your state or county yet?</div>
          <div style={{ fontSize: 14, color: "var(--muted)", marginTop: 8, maxWidth: "36ch" }}>
            Tell us where you need it. We prioritize rollout by demand and email you the moment your county goes live.
          </div>
        </div>

        {submitted ? (
          <div style={{ padding: "20px 24px", background: "var(--bg)", border: "1px solid var(--line)", borderRadius: 14, display: "flex", alignItems: "center", gap: 14 }}>
            <span style={{ width: 28, height: 28, borderRadius: 99, background: "var(--green)", color: "#fff", display: "grid", placeItems: "center", flexShrink: 0 }}>
              <Icon.Check/>
            </span>
            <div>
              <div style={{ fontWeight: 600 }}>You're on the list.</div>
              <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 2 }}>
                We'll notify {email} when {county ? county + " County, " : ""}{STATE_NAMES[state]} is live.
              </div>
            </div>
          </div>
        ) : (
          <form onSubmit={handleSubmit} style={{ display: "grid", gap: 12 }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
              <div>
                <label className="caps mono" style={{ color: "var(--muted)", display: "block", marginBottom: 6 }}>State</label>
                <select value={state} onChange={e => { setState(e.target.value); setCounty(""); }} style={selectStyle} required>
                  <option value="">Select a state…</option>
                  {stateOptions.map(([code, name]) => (
                    <option key={code} value={code}>{name}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="caps mono" style={{ color: "var(--muted)", display: "block", marginBottom: 6 }}>
                  County <span style={{ textTransform: "none", letterSpacing: 0, fontFamily: "inherit" }}>(optional)</span>
                </label>
                <select value={county} onChange={e => setCounty(e.target.value)} style={selectStyle} disabled={!state}>
                  <option value="">{!state ? "Pick a state first" : countyOptions.length ? "Any county" : "County not listed"}</option>
                  {countyOptions.map(c => (
                    <option key={c} value={c}>{c}</option>
                  ))}
                  {state && <option value="__other__">Other county…</option>}
                </select>
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 10 }}>
              <div>
                <label className="caps mono" style={{ color: "var(--muted)", display: "block", marginBottom: 6 }}>Email</label>
                <input type="email" required value={email} onChange={e => setEmail(e.target.value)} placeholder="you@domain.com" style={inputStyle}/>
              </div>
              <button className="btn btn-primary" type="submit" style={{ alignSelf: "end", height: 46 }}>
                Notify me <Icon.Arrow/>
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

window.Coverage = Coverage;
