// Global reach — world map highlighting active ad markets in light blue.
// Uses d3-geo + topojson-client (loaded via CDN in index.html).
function HpMap({ bg }) {
  const [geo, setGeo] = React.useState(null);
  const [error, setError] = React.useState(null);

  // ISO numeric country codes (world-atlas v2 uses these as feature.id, no leading zeros)
  const ACTIVE = React.useMemo(() => new Set([
    // North America
    "840", // United States
    "124", // Canada
    "484", // Mexico
    // Western & Northern Europe
    "826", // United Kingdom
    "372", // Ireland
    "250", // France
    "276", // Germany
    "724", // Spain
    "620", // Portugal
    "380", // Italy
    "528", // Netherlands
    "56",  // Belgium
    "442", // Luxembourg
    "756", // Switzerland
    "40",  // Austria
    "208", // Denmark
    "752", // Sweden
    "578", // Norway
    "246", // Finland
    "352", // Iceland
    // Central / Eastern / Southern Europe
    "616", // Poland
    "203", // Czechia
    "703", // Slovakia
    "348", // Hungary
    "705", // Slovenia
    "191", // Croatia
    "642", // Romania
    "100", // Bulgaria
    "300", // Greece
    // Oceania
    "36",  // Australia
    "554", // New Zealand
  ]), []);

  const COUNTRY_CHIPS = [
    "USA", "Canada", "Mexico", "UK", "Ireland", "Germany", "France", "Spain",
    "Portugal", "Italy", "Netherlands", "Belgium", "Switzerland", "Austria",
    "Sweden", "Norway", "Denmark", "Finland", "Poland", "Greece",
    "Australia", "New Zealand",
  ];

  React.useEffect(() => {
    let cancelled = false;
    const ready = () => window.d3 && window.d3.geoNaturalEarth1 && window.topojson && window.topojson.feature;
    const loadData = () => {
      fetch("https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json")
        .then(r => r.ok ? r.json() : Promise.reject(new Error("Network response was not ok")))
        .then(topo => {
          if (cancelled) return;
          const features = window.topojson.feature(topo, topo.objects.countries);
          setGeo(features);
        })
        .catch(e => !cancelled && setError(e.message || "Failed to load map"));
    };
    if (ready()) {
      loadData();
    } else {
      // Poll briefly until the deferred CDN scripts have parsed.
      let tries = 0;
      const id = setInterval(() => {
        tries += 1;
        if (ready()) { clearInterval(id); loadData(); }
        else if (tries > 80) { clearInterval(id); setError("Map libraries failed to load"); }
      }, 75);
      return () => { cancelled = true; clearInterval(id); };
    }
    return () => { cancelled = true; };
  }, []);

  const W = 1280, H = 640;

  let pathD = null;
  if (geo && window.d3) {
    const projection = window.d3.geoNaturalEarth1().fitSize([W, H], geo);
    pathD = window.d3.geoPath(projection);
  }

  return (
    <section
      id="map"
      className="hp-section"
      style={{
        background: bg,
        borderBottom: "1px solid var(--rule)",
      }}
    >
      <div className="hp-container">
        <div className="hp-eyebrow-row">
          <span className="eyebrow" style={{ borderBottom: "1px solid var(--coral)", paddingBottom: 2 }}>
            Global reach
          </span>
          <span className="eyebrow">25+ countries · USA · CA · EU · AU</span>
        </div>

        <h2 style={{
          fontFamily: "var(--font-display)", fontWeight: 500,
          fontSize: "clamp(28px, 4vw, 56px)", lineHeight: 1.05,
          letterSpacing: "-0.04em", margin: 0, color: "var(--ink)", maxWidth: "22ch",
          marginBottom: 48,
        }}>
          $1M+ in ad spend, run profitably across <span style={{ fontWeight: 200 }}>USA, Canada, Europe, and beyond.</span>
        </h2>

        <div className="hp-map-frame">
          {pathD && geo ? (
            <svg
              viewBox={`0 0 ${W} ${H}`}
              className="hp-map-svg"
              role="img"
              aria-label="World map showing active ad markets in light blue"
            >
              {geo.features.map(f => {
                const isActive = ACTIVE.has(String(f.id));
                return (
                  <path
                    key={f.id || f.properties?.name}
                    d={pathD(f)}
                    className={"country" + (isActive ? " is-active" : "")}
                  >
                    {isActive && <title>{f.properties?.name} — active market</title>}
                  </path>
                );
              })}
            </svg>
          ) : error ? (
            <div className="hp-map-loading">Map unavailable · {error}</div>
          ) : (
            <div className="hp-map-loading">Loading map…</div>
          )}

          <div className="hp-map-legend">
            <span className="hp-legend-dot">Active markets</span>
            <span className="hp-legend-dot is-base">Other geos</span>
          </div>
        </div>

        <div className="hp-chip-row">
          {COUNTRY_CHIPS.map(c => (
            <span key={c} className="hp-chip">{c}</span>
          ))}
        </div>
      </div>
    </section>
  );
}
window.HpMap = HpMap;
