/* ============================================================
   PWC COVERAGE — interactive response map (Leaflet).
   Response-time bands from Midland (estimate, not a guarantee) +
   custom reticle markers for documented events (same PWC_DATA as
   the Events page) + a complete text fallback for a11y / no-JS.
   ============================================================ */
const CV = window.PWC.INV;
const CVD = window.PWC_DATA;

function CoverageStyles() {
  return <style dangerouslySetInnerHTML={{ __html: `
.map-howto{ display:grid; grid-template-columns:repeat(3,1fr); gap:18px; margin-bottom:24px; }
.howto-item{ display:flex; gap:11px; align-items:flex-start; color:var(--text-2); font-size:.98rem; line-height:1.5; }
.howto-n{ flex:none; width:26px; height:26px; border-radius:50%; display:grid; place-items:center; font-family:var(--font-display);
  font-weight:800; font-size:.85rem; color:var(--ember); border:1px solid color-mix(in srgb,var(--ember) 45%,transparent); }
.legend-row{ display:flex; flex-wrap:wrap; gap:10px 22px; align-items:center; margin-bottom:22px; }
.legend-bands{ display:flex; flex-wrap:wrap; gap:8px; }
.legend-band{ display:inline-flex; align-items:center; gap:8px; font-size:.85rem; font-weight:600; color:var(--text-2); }
.legend-sw{ width:16px; height:16px; border-radius:4px; border:1px solid rgba(255,255,255,.25); }

.pwc-map{ height:clamp(440px,68vh,680px); width:100%; border-radius:var(--r-lg); overflow:hidden; border:1px solid var(--line);
  background:#0c1115; z-index:1; }
.pwc-map .leaflet-tile-pane{ filter:saturate(.92); }
.leaflet-container{ font-family:var(--font-body); background:#0c1115; }
.leaflet-popup-content-wrapper{ background:var(--bg-2); color:var(--text); border-radius:var(--r-lg);
  border:1px solid var(--line-strong); box-shadow:0 18px 50px -18px rgba(0,0,0,.7); }
.leaflet-popup-tip{ background:var(--bg-2); border:1px solid var(--line-strong); }
.leaflet-popup-content{ margin:15px 17px; min-width:230px; }
.leaflet-popup-close-button{ color:var(--text-2) !important; }
.pop-op{ display:inline-flex; align-items:center; gap:7px; font-size:.72rem; font-weight:700; letter-spacing:.03em; color:var(--text-2); margin-bottom:6px; }
.pop-dot{ width:8px; height:8px; border-radius:50%; }
.pop-title{ font-family:var(--font-display); font-weight:800; font-size:1.02rem; line-height:1.2; color:var(--text); margin:0 0 6px; }
.pop-meta{ font-size:.78rem; color:var(--text-3); font-weight:600; margin-bottom:9px; }
.pop-lesson{ font-size:.86rem; line-height:1.45; color:var(--text-2); margin:0 0 11px; }
.pop-lesson b{ color:var(--text); }
.pop-actions{ display:flex; flex-direction:column; gap:7px; }
.pop-call{ display:inline-flex; align-items:center; justify-content:center; gap:7px; background:var(--ember); color:var(--ember-ink);
  font-family:var(--font-display); font-weight:800; font-size:.92rem; padding:9px 12px; border-radius:var(--r); text-decoration:none; }
.pop-link{ font-size:.8rem; color:var(--steel); text-decoration:none; font-weight:600; }
.pop-911{ font-size:.72rem; color:var(--text-3); line-height:1.4; }
.pop-911 a{ color:var(--ember); }
.pwc-origin-ico, .pwc-event-ico{ background:none; border:none; }
.pwc-event-ico svg{ filter:drop-shadow(0 2px 4px rgba(0,0,0,.55)); transition:transform .15s var(--ease); }
.pwc-event-ico:hover svg{ transform:scale(1.18); }

/* text fallback */
.fallback-grid{ display:grid; grid-template-columns:1fr 1fr; gap:clamp(28px,4vw,56px); }
.fb-list{ list-style:none; margin:14px 0 0; padding:0; }
.fb-list li{ display:flex; justify-content:space-between; gap:12px; padding:12px 0; border-bottom:1px solid var(--line); font-size:.97rem; }
.fb-band{ font-weight:700; font-size:.82rem; color:var(--text); padding:3px 9px; border-radius:999px; border:1px solid var(--line-strong); white-space:nowrap; }
.fb-county{ color:var(--text); font-weight:600; }
.fb-sub{ color:var(--text-3); font-size:.84rem; }
.disclaimer-box{ margin-top:clamp(28px,4vw,44px); padding:18px 22px; border:1px solid var(--line); border-left:3px solid var(--steel);
  border-radius:var(--r); background:var(--bg-2); color:var(--text-2); font-size:.92rem; line-height:1.55; }

@media (max-width:860px){
  .map-howto{ grid-template-columns:1fr; gap:12px; }
  .fallback-grid{ grid-template-columns:1fr; gap:30px; }
}
` }} />;
}

function reticleSVG(color, size) {
  return `<svg width="${size}" height="${size}" viewBox="0 0 40 40" fill="none">
    <circle cx="20" cy="20" r="11" fill="rgba(12,17,21,.55)" stroke="${color}" stroke-width="2.4"/>
    <path d="M20 5v6M20 29v6M5 20h6M29 20h6" stroke="${color}" stroke-width="2.4" stroke-linecap="round"/>
    <rect x="16.5" y="16.5" width="7" height="7" rx="1" fill="var(--ember,#F2842B)"/></svg>`;
}

function CoverageMap({ theme }) {
  const ref = React.useRef(null);
  const mapRef = React.useRef(null);
  const tileRef = React.useRef(null);
  const markersRef = React.useRef({});

  React.useEffect(() => {
    if (!window.L || !ref.current || mapRef.current) return;
    const L = window.L;
    const o = CVD.origin;
    const map = L.map(ref.current, { scrollWheelZoom: false, zoomControl: true }).setView([o.lat, o.lng], 7);
    mapRef.current = map;

    // response bands — real drive-time isochrone rings (anisotropic, follow the
    // highway corridors out of Midland). Draw largest first so inner bands read on top.
    [...CVD.bands].reverse().forEach((b) => {
      L.polygon(b.ring, {
        color: b.color, weight: 1.3, opacity: .55, smoothFactor: 1,
        fillColor: b.color, fillOpacity: b.id === "A" ? .17 : b.id === "B" ? .14 : b.id === "C" ? .11 : .08,
      }).addTo(map);
    });

    // origin marker (Midland)
    L.marker([o.lat, o.lng], {
      icon: L.divIcon({ className: "pwc-origin-ico", html:
        `<div style="display:flex;align-items:center;gap:6px">${reticleSVG("#F2842B", 30)}
          <span style="font:700 12px/1 'Archivo',sans-serif;color:#fff;text-shadow:0 1px 3px rgba(0,0,0,.8);white-space:nowrap">Midland — response origin</span></div>`,
        iconSize: [240, 30], iconAnchor: [15, 15] }), interactive: false,
    }).addTo(map);

    // event markers
    CVD.mapEvents.forEach((e) => {
      const color = window.OP_COLORS[e.operation_type] || "#3E94B5";
      const m = L.marker([e.lat, e.lng], {
        icon: L.divIcon({ className: "pwc-event-ico", html: reticleSVG(color, 30), iconSize: [30, 30], iconAnchor: [15, 15] }),
        title: e.title, riseOnHover: true,
      }).addTo(map);
      const opLabel = (CVD.OPS[e.operation_type] || {}).label || e.operation_type;
      m.bindPopup(
        `<div class="pop-op"><span class="pop-dot" style="background:${color}"></span>${opLabel} · ${e.county} County, ${e.state}</div>
         <p class="pop-title">${e.title}</p>
         <div class="pop-meta">${e.sub_basin} · ${e.date} · ${e.precision}</div>
         <p class="pop-lesson"><b>Lesson:</b> ${e.lesson_learned}</p>
         <div class="pop-actions">
           <a class="pop-call" href="tel:${CV.tel}">Call Now: ${CV.phone}</a>
           <a class="pop-link" href="${e.source_url}" target="_blank" rel="noopener noreferrer">Read the source →</a>
           <p class="pop-911">Life-threatening — fire, injury, or H2S? Call <a href="tel:911">911</a> first.</p>
         </div>`, { maxWidth: 290 });
      markersRef.current[e.id] = m;
    });

    // open a marker if the URL points at one (from the events page "View on map")
    const id = (location.hash || "").replace("#", "");
    if (id && markersRef.current[id]) {
      const m = markersRef.current[id];
      map.setView(m.getLatLng(), 8, { animate: false });
      setTimeout(() => m.openPopup(), 300);
    }
    setTimeout(() => map.invalidateSize(), 200);
    window.__pwcMap = map; window.__pwcMarkers = markersRef.current;
  }, []);

  // swap tiles on theme change
  React.useEffect(() => {
    if (!window.L || !mapRef.current) return;
    const url = theme === "light"
      ? "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png"
      : "https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png";
    if (tileRef.current) mapRef.current.removeLayer(tileRef.current);
    tileRef.current = window.L.tileLayer(url, {
      attribution: '&copy; OpenStreetMap &copy; CARTO', subdomains: "abcd", maxZoom: 19,
    }).addTo(mapRef.current);
    tileRef.current.bringToBack();
  }, [theme]);

  return <div className="pwc-map" ref={ref} role="application" aria-label="Permian Well Control coverage and documented-events map" />;
}

function CoveragePage({ theme }) {
  return (
    <React.Fragment>
      <PagesStyles />
      <CoverageStyles />
      <PageHero
        eyebrow="Response area"
        h1="We cover the Permian — and when you call, we move fast."
        sub="Permian Well Control responds across West Texas and Southeast New Mexico from Midland. The map shows estimated response coverage and real, documented events across the basin — so you know what early intervention looks like where you operate."
        secondary={{ label: "See the events", href: CV.nav[0].href }}
      />

      <section className="section">
        <div className="wrap">
          <Reveal className="map-howto" as="div">
            <div className="howto-item"><span className="howto-n">1</span><span>Shaded bands = estimated response time from Midland (about an hour to mobilize, plus drive time). Closer = faster.</span></div>
            <div className="howto-item"><span className="howto-n">2</span><span>Marked points = documented well control events. Tap any one for the root cause and the lesson.</span></div>
            <div className="howto-item"><span className="howto-n">3</span><span>Estimates are planning guidance, not a guarantee. Call and we'll give you a straight answer for your location.</span></div>
          </Reveal>

          <Reveal className="legend-row" as="div">
            <div className="legend-bands">
              {CVD.bands.map((b) => (
                <span className="legend-band" key={b.id}>
                  <span className="legend-sw" style={{ background: b.color, opacity: .85 }} />{b.drive} · {b.resp}
                </span>
              ))}
            </div>
          </Reveal>

          <Reveal as="div"><CoverageMap theme={theme} /></Reveal>

          <div className="disclaimer-box">
            Response times are estimates (approx. mobilization + drive time from Midland) for planning only — not a guarantee. Call for a straight estimate for your location. Event markers credit and link their source; coordinates are approximate county/place centroids, not survey locations.
          </div>
        </div>
      </section>

      <section className="section alt">
        <div className="wrap">
          <Reveal className="sec-head">
            <p className="eyebrow">If the map won't load</p>
            <h2 className="sec-h">Counties served &amp; documented events.</h2>
            <p className="sec-sub">Everything on the map, in plain text — estimated response band by county, and the documented events behind each marker.</p>
          </Reveal>
          <div className="fallback-grid">
            <Reveal as="div">
              <h3 className="svc-h" style={{ marginBottom: "4px" }}>Estimated response by county</h3>
              <ul className="fb-list">
                {CVD.counties.map((c) => (
                  <li key={c.county + c.state}>
                    <span><span className="fb-county">{c.county} County, {c.state}</span> <span className="fb-sub">· {c.sub_basin}</span></span>
                    <span className="fb-band">{c.band.resp}</span>
                  </li>
                ))}
              </ul>
            </Reveal>
            <Reveal as="div" delay={70}>
              <h3 className="svc-h" style={{ marginBottom: "4px" }}>Documented events on this map</h3>
              <ul className="fb-list">
                {CVD.mapEvents.map((e) => (
                  <li key={e.id}>
                    <span><span className="fb-county">{e.title}</span><br /><span className="fb-sub">{e.county} County, {e.state} · {e.date}</span></span>
                    <a className="ev-map-link" href={CV.nav[0].href + "#" + e.id} style={{ flex: "none" }}>Lesson →</a>
                  </li>
                ))}
              </ul>
            </Reveal>
          </div>
        </div>
      </section>

      <section className="section">
        <div className="wrap">
          <Reveal className="prose-col">
            <p className="prose-p">Coverage is only half of it. What matters when a well gets away from you is a responder who's already moving and an honest read on what the event needs. That's what we do — early stabilization, informed escalation, you in command. Wherever you are on this map, the first move is the same.</p>
          </Reveal>
        </div>
      </section>

      <CtaBand heading="Wherever you are on the map, the first move is the same." save={true} />
    </React.Fragment>
  );
}

Object.assign(window, { CoverageStyles, CoverageMap, CoveragePage, reticleSVG });
