/* global React L */

const RM_HOME   = [22.5, 80.0];
const RM_HOME_Z = 5;
const RM_PIN_Z  = 8;

/* Simplified India border polygon — clockwise [lat, lon] */
const INDIA_OUTLINE = [
  [23.5, 68.2], [24.8, 68.3], [26.5, 69.5], [28.0, 70.0],
  [29.5, 70.5], [31.2, 74.0], [32.5, 74.5], [33.5, 75.5],
  [34.5, 76.5], [35.5, 77.8], [34.0, 78.8], [32.0, 79.5],
  [30.2, 80.2], [29.0, 80.0], [28.2, 84.5], [27.8, 88.5],
  [27.3, 91.0], [27.8, 92.5], [27.8, 95.5], [28.2, 97.3],
  [27.0, 97.5], [26.0, 96.0], [25.0, 93.5], [24.0, 92.5],
  [23.5, 91.5], [22.0, 91.8], [22.0, 91.0], [21.5, 88.0],
  [19.5, 85.5], [17.0, 82.5], [15.0, 80.5], [13.5, 80.2],
  [11.5, 79.8], [9.0, 78.5],  [8.0, 77.5],  [8.5, 76.9],
  [10.5, 76.0], [12.5, 74.8], [15.0, 74.0], [16.0, 73.5],
  [18.5, 72.8], [20.5, 72.7], [21.5, 69.5], [22.5, 68.5],
  [23.5, 68.2],
];

const RM_PINS = [
  {
    id: 1, state: "Maharashtra", city: "Pune",
    lat: 18.5204, lon: 73.8567, color: "#C9A84C",
    campaigns: [
      { title: "Ward 16 Victory",           sub: "Maruti Aba Tupe · BJP · PMC 2026",        img: "./assets/our%20work/marutiTupe/1.jpeg"     },
      { title: "Hadapsar Assembly",          sub: "Prashant Jagtap · NCP · 2024",        img: "./assets/our%20work/prashantjagtap/1.jpeg" },
      { title: "Pimpri Constituency Survey", sub: "Gautam Chabukswar · SS-UBT · 2024",   img: null },
      { title: "BSP Statewide Branding",     sub: "Dr. Hulgesh Chalwadi · BSP · 2024",   img: null },
    ],
  },
  {
    id: 2, state: "Punjab", city: "Amloh",
    lat: 30.4855, lon: 76.2942, color: "#4AA8A0",
    campaigns: [
      { title: "Amloh Assembly",             sub: "Randeep Singh Nabha · 2026",          img: "./assets/our%20work/Nabha/1.jpeg" },
    ],
  },
  {
    id: 3, state: "Himachal Pradesh", city: "Shimla",
    lat: 31.1048, lon: 77.1734, color: "#E86A2A",
    campaigns: [
      { title: "Kasumpati Assembly",         sub: "Vijay Jyoti Sen · 2026",              img: "./assets/our%20work/vijaysen/1.jpeg" },
    ],
  },
  {
    id: 4, state: "Assam", city: "Bongaigaon",
    lat: 26.4794, lon: 90.5586, color: "#0B6E68",
    campaigns: [
      { title: "Bongaigaon Assembly",        sub: "Phany Bhushan Chaudhuri · AGP · 2023", img: "./assets/our%20work/AGP/1.jpeg" },
    ],
  },
  {
    id: 5, state: "Uttar Pradesh", city: "Rural Constituency",
    lat: 26.8467, lon: 80.9462, color: "#7B5EA7",
    campaigns: [
      { title: "Rural Outreach Campaign",    sub: "SP Candidate · 2022",                 img: null },
    ],
  },
];

/* ── Build popup HTML string ── */
function buildPopupHtml(pin, idx) {
  var c = pin.campaigns[idx];
  var imgHtml = c.img
    ? '<div class="rmp-img-wrap"><img src="' + c.img + '" class="rmp-img"/><div class="rmp-img-fade"></div></div>'
    : '<div class="rmp-no-img" style="--c:' + pin.color + '"><span class="rmp-no-img-label">' + pin.state.toUpperCase() + '</span></div>';

  var navHtml = '';
  if (pin.campaigns.length > 1) {
    navHtml = '<div class="rmp-nav">';
    for (var i = 0; i < pin.campaigns.length; i++) {
      navHtml += '<button class="rmp-nav-dot' + (i === idx ? ' active' : '') +
        '" data-idx="' + i + '" style="' + (i === idx ? 'background:' + pin.color + ';width:18px' : '') + '"></button>';
    }
    navHtml += '</div>';
  }

  return (
    '<div class="rmp-card" style="--c:' + pin.color + '">' +
      '<button class="rmp-close" data-action="close">&#x2715;</button>' +
      imgHtml +
      '<div class="rmp-body">' +
        '<div class="rmp-tag" style="color:' + pin.color + '">' + pin.state + ' &middot; ' + pin.city + '</div>' +
        '<div class="rmp-title">' + c.title + '</div>' +
        '<div class="rmp-sub">' + c.sub + '</div>' +
        navHtml +
      '</div>' +
    '</div>'
  );
}

const RegionsMap = () => {
  const containerRef = React.useRef(null);
  const mapRef       = React.useRef(null);
  const popupRef     = React.useRef(null);

  /* ── Open popup + fly in ── */
  function openPin(pin, idx) {
    var map = mapRef.current;
    if (!map) return;

    /* Close any open popup first */
    if (popupRef.current) { map.closePopup(popupRef.current); }

    var popup = L.popup({
      closeButton: false,
      className: 'rmp-popup',
      maxWidth: 260,
      minWidth: 240,
      autoPan: true,
      autoPanPaddingTopLeft: L.point(20, 20),
      autoPanPaddingBottomRight: L.point(20, 20),
    })
    .setLatLng([pin.lat, pin.lon])
    .setContent(buildPopupHtml(pin, idx));

    popup.openOn(map);
    popupRef.current = popup;

    /* Fly in */
    map.flyTo([pin.lat, pin.lon], RM_PIN_Z, { duration: 0.75, easeLinearity: 0.4 });

    /* Attach delegated handlers inside popup */
    map.once('popupopen', function(e) {
      var el = e.popup.getElement();
      if (!el) return;
      el.addEventListener('click', function(evt) {
        var closeBtn = evt.target.closest('[data-action="close"]');
        var navBtn   = evt.target.closest('[data-idx]');
        if (closeBtn) {
          map.closePopup();
          map.flyTo(RM_HOME, RM_HOME_Z, { duration: 0.75, easeLinearity: 0.4 });
          popupRef.current = null;
        } else if (navBtn) {
          var newIdx = parseInt(navBtn.getAttribute('data-idx'), 10);
          openPin(pin, newIdx);
        }
      });
    });
  }

  /* ── Init Leaflet ── */
  React.useEffect(function() {
    if (mapRef.current || !window.L || !containerRef.current) return;

    var map = L.map(containerRef.current, {
      center: RM_HOME,
      zoom: RM_HOME_Z,
      zoomControl: false,
      scrollWheelZoom: false,
      maxBounds: [[6, 66], [38, 100]],
      maxBoundsViscosity: 1.0,
      minZoom: 4,
      maxZoom: 10,
    });

    /* Realistic tile layer — CartoDB Voyager shows accurate state borders, city labels, roads */
    L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png', {
      attribution: '&copy; <a href="https://carto.com/">CARTO</a> &copy; <a href="https://www.openstreetmap.org/copyright">OSM</a>',
      subdomains: 'abcd',
      maxZoom: 19,
    }).addTo(map);


    /* Campaign pins */
    RM_PINS.forEach(function(pin) {
      var icon = L.divIcon({
        className: 'psm-root',
        html:
          '<div class="psm-wrap" style="--c:' + pin.color + '">' +
            '<span class="psm-ring psm-ring1"></span>' +
            '<span class="psm-ring psm-ring2"></span>' +
            '<span class="psm-outer"></span>' +
            '<span class="psm-dot"></span>' +
            '<span class="psm-lbl">' + pin.state + '</span>' +
          '</div>',
        iconSize:   [16, 16],
        iconAnchor: [8, 8],
      });

      L.marker([pin.lat, pin.lon], { icon })
        .addTo(map)
        .on('click', function(e) {
          L.DomEvent.stopPropagation(e);
          openPin(pin, 0);
        });
    });

    L.control.zoom({ position: 'bottomright' }).addTo(map);

    /* Click map background → close popup + zoom out */
    map.on('click', function() {
      if (popupRef.current) {
        map.closePopup();
        map.flyTo(RM_HOME, RM_HOME_Z, { duration: 0.75, easeLinearity: 0.4 });
        popupRef.current = null;
      }
    });

    mapRef.current = map;

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

  return (
    <section id="regions" style={{
      background: "var(--teal)",
      position: "relative", overflow: "hidden",
      padding: "80px 32px 72px",
      borderTop: "1px solid rgba(244,239,224,0.15)",
    }}>

      {/* Halftone */}
      <div aria-hidden style={{
        position: "absolute", inset: 0, pointerEvents: "none", opacity: 0.07,
        backgroundImage: "radial-gradient(circle, #F4EFE0 1px, transparent 1px)",
        backgroundSize: "12px 12px",
      }}/>
      <div aria-hidden style={{
        position: "absolute", inset: 0, pointerEvents: "none",
        background: "linear-gradient(135deg, rgba(255,255,255,0.04) 0%, transparent 55%)",
      }}/>

      <div style={{ maxWidth: 1280, margin: "0 auto", position: "relative" }}>

        {/* Header */}
        <Eyebrow>Nationwide Presence</Eyebrow>
        <h2 style={{
          fontFamily: "var(--font-display)", fontWeight: 600,
          fontSize: "clamp(36px,5vw,72px)", lineHeight: 1.0,
          letterSpacing: "-0.035em", color: "var(--cream)",
          margin: "12px 0 14px",
        }}>
          Where we've campaigned.
        </h2>
        <p style={{
          fontSize: 17, lineHeight: 1.65, color: "rgba(244,239,224,0.75)",
          maxWidth: 560, marginBottom: 36,
        }}>
          From Maharashtra's urban wards to Punjab's heartland, Himachal's mountain seats
          and Assam's river plains — Pravah Solution deploys where elections are decided on the ground.
        </p>

        {/* Full-width map */}
        <div style={{
          borderRadius: 8, overflow: "hidden",
          border: "1px solid rgba(244,239,224,0.18)",
          boxShadow: "0 32px 80px rgba(0,0,0,0.45)",
          background: "#e8e4d9",
        }}>
          <div ref={containerRef} style={{ width: "100%", height: "580px" }}/>
        </div>

        {/* Stats bar */}
        <div className="rmap-stats" style={{
          display: "grid", gridTemplateColumns: "repeat(4,1fr)",
          marginTop: 52, paddingTop: 28,
          borderTop: "1px solid rgba(244,239,224,0.2)",
        }}>
          {[
            { n: "5",     l: "States Served"            },
            { n: "10+",   l: "Campaigns Delivered"       },
            { n: "7+",    l: "Years Active"              },
            { n: "175K+", l: "Voters Reached / Campaign" },
          ].map(function(s, i, arr) { return (
            <div key={i} style={{
              textAlign: "center", padding: "20px 12px",
              borderRight: i < arr.length - 1 ? "1px solid rgba(244,239,224,0.2)" : "none",
            }}>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 600,
                fontSize: "clamp(28px,3.5vw,44px)", color: "var(--gold)",
                letterSpacing: "-0.02em", lineHeight: 1 }}>{s.n}</div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 9.5,
                letterSpacing: "0.1em", textTransform: "uppercase",
                color: "rgba(244,239,224,0.55)", marginTop: 7 }}>{s.l}</div>
            </div>
          ); })}
        </div>
      </div>

      <style>{`
        /* ── Leaflet base ── */
        .leaflet-container { background: #e8e4d9 !important; }
        .leaflet-control-attribution {
          background: rgba(12,26,40,0.75) !important;
          color: rgba(244,239,224,0.3) !important; font-size: 9px !important;
        }
        .leaflet-control-attribution a { color: rgba(244,239,224,0.4) !important; }
        .leaflet-control-zoom {
          border: 1px solid rgba(244,239,224,0.2) !important;
          border-radius: 6px !important; overflow: hidden;
          box-shadow: 0 4px 16px rgba(0,0,0,0.2) !important;
        }
        .leaflet-control-zoom a {
          background: rgba(12,26,40,0.88) !important;
          color: rgba(244,239,224,0.7) !important;
          border-color: rgba(244,239,224,0.1) !important;
          width: 32px !important; height: 32px !important; line-height: 32px !important;
          backdrop-filter: blur(10px);
        }
        .leaflet-control-zoom a:hover {
          background: rgba(11,110,104,0.85) !important;
          color: #fff !important;
        }

        /* ── Custom popup wrapper ── */
        .rmp-popup .leaflet-popup-content-wrapper {
          background: rgba(8,18,30,0.96) !important;
          border: 1px solid rgba(244,239,224,0.14) !important;
          border-radius: 8px !important;
          padding: 0 !important;
          overflow: hidden !important;
          box-shadow: 0 20px 60px rgba(0,0,0,0.6), 0 0 0 1px rgba(244,239,224,0.06) !important;
          backdrop-filter: blur(20px) !important;
        }
        .rmp-popup .leaflet-popup-content { margin: 0 !important; width: 240px !important; }
        .rmp-popup .leaflet-popup-tip-container { display: none !important; }

        /* ── Popup card internals ── */
        .rmp-card { position: relative; }
        .rmp-close {
          position: absolute; top: 8px; right: 8px; z-index: 10;
          width: 26px; height: 26px; border-radius: 50%;
          background: rgba(0,0,0,0.55); border: 1px solid rgba(244,239,224,0.2);
          color: rgba(244,239,224,0.75); font-size: 13px;
          display: flex; align-items: center; justify-content: center;
          cursor: pointer; transition: background 150ms;
        }
        .rmp-close:hover { background: rgba(200,50,50,0.6); color: #fff; }
        .rmp-img-wrap { height: 148px; overflow: hidden; position: relative; }
        .rmp-img { width: 100%; height: 100%; object-fit: cover; display: block; }
        .rmp-img-fade {
          position: absolute; inset: 0;
          background: linear-gradient(to bottom, transparent 40%, rgba(8,18,30,0.65) 100%);
        }
        .rmp-no-img {
          height: 72px; display: flex; align-items: center; justify-content: center;
          background: linear-gradient(135deg, rgba(var(--c),0.15), rgba(0,0,0,0.2));
          border-bottom: 1px solid rgba(244,239,224,0.08);
        }
        .rmp-no-img-label {
          font-family: 'JetBrains Mono', monospace; font-size: 9px;
          letter-spacing: 0.14em; color: var(--c); opacity: 0.6;
        }
        .rmp-body { padding: 12px 14px 14px; }
        .rmp-tag {
          font-family: 'JetBrains Mono', monospace; font-size: 8.5px;
          letter-spacing: 0.12em; text-transform: uppercase;
          margin-bottom: 5px; opacity: 0.9;
        }
        .rmp-title {
          font-family: var(--font-display); font-size: 14px; font-weight: 600;
          color: #F0E9D8; line-height: 1.35; margin-bottom: 4px;
        }
        .rmp-sub {
          font-size: 11px; color: rgba(240,233,216,0.45);
          font-family: var(--font-body); line-height: 1.4;
        }
        .rmp-nav {
          display: flex; align-items: center; gap: 5px; margin-top: 10px;
        }
        .rmp-nav-dot {
          height: 3px; width: 8px; border-radius: 2px;
          background: rgba(244,239,224,0.2); border: none; cursor: pointer;
          transition: all 200ms; padding: 0;
        }
        .rmp-nav-dot.active { background: var(--c) !important; width: 18px; }

        /* ── Pin markers ── */
        .psm-root { background: transparent !important; border: none !important; }
        .psm-wrap { position: relative; width: 16px; height: 16px; cursor: pointer; }
        .psm-dot {
          position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);
          width: 11px; height: 11px; border-radius: 50%;
          background: var(--c); border: 2px solid rgba(255,255,255,0.45);
          box-shadow: 0 0 10px var(--c), 0 2px 8px rgba(0,0,0,0.4); z-index: 2;
        }
        .psm-outer {
          position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);
          width: 17px; height: 17px; border-radius: 50%;
          border: 1.5px solid var(--c); opacity: 0.4;
        }
        .psm-ring {
          position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);
          width: 16px; height: 16px; border-radius: 50%;
          border: 1.5px solid var(--c);
          animation: psm-pulse 2.8s ease-out infinite;
        }
        .psm-ring2 { animation-delay: 1.2s; }
        .psm-lbl {
          position: absolute; top: 19px; left: 50%; transform: translateX(-50%);
          white-space: nowrap; pointer-events: none;
          font-family: 'JetBrains Mono', monospace; font-size: 8.5px;
          font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase;
          color: var(--c);
          text-shadow: 0 1px 3px rgba(255,255,255,0.95), 0 0 6px rgba(255,255,255,0.7);
        }
        @keyframes psm-pulse {
          0%   { width: 16px; height: 16px; opacity: 0.7; }
          100% { width: 54px; height: 54px; opacity: 0; }
        }
        .rm-state-label { background: transparent !important; border: none !important; pointer-events: none; }
        @media (max-width: 640px) {
          .rmap-stats { grid-template-columns: repeat(2,1fr) !important; }
        }
      `}</style>
    </section>
  );
};

window.RegionsMap = RegionsMap;
