/* Danex Roofing — service areas across the Lower Mainland.
   Clickable location chips highlight the matching pin on the Leaflet map. */

// teardrop pin icon; `active` = larger ember pin with a pulsing ring
function dxPin(active) {
  const size = active ? 32 : 22;
  const ring = active ? '<span class="dx-pin-ring"></span>' : '';
  return window.L.divIcon({
    className: '',
    html: '<div class="dx-pin" style="position:relative;filter:drop-shadow(0 3px 4px rgba(0,0,0,0.45))">' + ring +
      '<svg width="' + size + '" height="' + (size * 1.27) + '" viewBox="0 0 24 30" style="position:relative;z-index:2">' +
      '<path d="M12 0C6 0 1.5 4.5 1.5 10.5 1.5 18 12 30 12 30s10.5-12 10.5-19.5C22.5 4.5 18 0 12 0z" fill="#E55416" stroke="' +
      (active ? '#fff' : 'rgba(255,255,255,0.55)') + '" stroke-width="' + (active ? 1.6 : 1) + '"/>' +
      '<circle cx="12" cy="10" r="3" fill="#fff"/></svg></div>',
    iconSize: [size, size * 1.27],
    iconAnchor: [size / 2, size * 1.27],
    popupAnchor: [0, -size * 1.05],
  });
}

function ServiceAreas() {
  const { Eyebrow } = DS;
  const places = [
    { name: 'Vancouver', lat: 49.2827, lng: -123.1207 },
    { name: 'North Vancouver', lat: 49.3210, lng: -123.0724 },
    { name: 'Burnaby', lat: 49.2810, lng: -122.9970 },
    { name: 'Surrey', lat: 49.1913, lng: -122.8490 },
    { name: 'White Rock', lat: 49.0253, lng: -122.8029 },
    { name: 'Langley', lat: 49.1042, lng: -122.6604 },
    { name: 'Maple Ridge', lat: 49.2193, lng: -122.5984 },
    { name: 'Richmond', lat: 49.1666, lng: -123.1336 },
    { name: 'Delta', lat: 49.0847, lng: -123.0586 },
    { name: 'Mission', lat: 49.1337, lng: -122.3095 },
    { name: 'Coquitlam', lat: 49.2838, lng: -122.7932 },
    { name: 'New Westminster', lat: 49.2057, lng: -122.9110 },
  ];

  const mapRef = React.useRef(null);
  const mapObj = React.useRef(null);
  const markers = React.useRef({});
  const [selected, setSelected] = React.useState(null);
  const [hintGone, setHintGone] = React.useState(false);

  // init map once
  React.useEffect(() => {
    if (!window.L || !mapRef.current || mapRef.current._dxMap) return;

    const map = window.L.map(mapRef.current, {
      zoomControl: false, scrollWheelZoom: false, attributionControl: true,
    });
    map.attributionControl.setPrefix(false); // drop the "Leaflet" flag
    window.L.control.zoom({ position: 'topright' }).addTo(map);
    mapRef.current._dxMap = map;
    mapObj.current = map;

    window.L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
      subdomains: 'abcd', maxZoom: 19,
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="https://carto.com/attributions">CARTO</a>',
    }).addTo(map);
    map.getPane('tilePane').style.filter = 'brightness(1.28) contrast(0.96)';

    // loose orange dotted boundary encircling the service area (not a strict border)
    const coverage = window.L.polygon([
      [49.41, -123.22], [49.43, -122.58], [49.33, -122.18],
      [49.09, -122.14], [48.96, -122.56], [48.94, -123.06],
      [49.07, -123.30], [49.31, -123.31],
    ], {
      color: '#E55416', weight: 2.5, dashArray: '3 11', lineCap: 'round',
      fill: true, fillColor: '#E55416', fillOpacity: 0.05,
      interactive: false, smoothFactor: 2,
    }).addTo(map);

    const group = [coverage];
    places.forEach((p) => {
      const m = window.L.marker([p.lat, p.lng], { icon: dxPin(false) }).addTo(map);
      m.bindPopup('<strong>' + p.name + '</strong><br>Roofing service area');
      m.on('click', () => setSelected(p.name));
      markers.current[p.name] = m;
      group.push(m);
    });
    map.fitBounds(window.L.featureGroup(group).getBounds().pad(0.02));

    map.on('focus', () => map.scrollWheelZoom.enable());
    map.on('blur', () => map.scrollWheelZoom.disable());

    // first drag/zoom/click kills the "drag to explore" hint
    const killHint = () => setHintGone(true);
    map.on('dragstart zoomstart click', killHint);

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

  // re-style + focus the selected pin
  React.useEffect(() => {
    const map = mapObj.current;
    if (!map) return;
    Object.entries(markers.current).forEach(([name, m]) => {
      const on = name === selected;
      m.setIcon(dxPin(on));
      m.setZIndexOffset(on ? 1000 : 0);
    });
    if (selected && markers.current[selected]) {
      const m = markers.current[selected];
      map.panTo(m.getLatLng(), { animate: true, duration: 0.4 });
      m.openPopup();
    }
  }, [selected]);

  return (
    <section id="service-areas" style={{ background: 'var(--surface-sunken)', padding: 'var(--section-y) 0' }}>
      <style>{`
        .dx-area-chip {
          display: inline-flex; align-items: center; gap: 8px; padding: 9px 16px;
          border-radius: var(--radius-full); border: 1px solid var(--border-strong);
          background: var(--surface-raised); font-family: var(--font-sans); font-weight: 600;
          font-size: 15px; line-height: 1; color: var(--text-default); cursor: pointer;
          transition: transform var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out),
            background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out);
        }
        .dx-area-chip .dx-chip-dot { color: var(--accent); display: inline-flex; transition: color var(--dur-fast) var(--ease-out); }
        .dx-area-chip:hover { transform: translateY(-2px); box-shadow: var(--shadow-md); border-color: var(--accent); }
        .dx-area-chip:active { transform: translateY(0) scale(0.98); }
        .dx-area-chip[data-active="true"] {
          background: var(--accent); border-color: var(--accent); color: var(--text-on-accent);
          box-shadow: var(--shadow-accent-sm);
        }
        .dx-area-chip[data-active="true"] .dx-chip-dot { color: #fff; }
        .dx-pin-ring {
          position: absolute; left: 50%; bottom: 2px; width: 30px; height: 30px; margin-left: -15px;
          border-radius: 50%; background: rgba(229,84,22,0.45); z-index: 1;
          animation: dx-pin-pulse 1.5s ease-out infinite;
        }
        @keyframes dx-pin-pulse {
          0% { transform: scale(0.35); opacity: 0.75; }
          100% { transform: scale(1.7); opacity: 0; }
        }
        @media (prefers-reduced-motion: reduce) {
          .dx-area-chip { transition: none; }
          .dx-pin-ring { animation: none; }
        }
        #service-areas .leaflet-control-attribution {
          font-size: 9px; padding: 1px 5px; line-height: 1.4;
          background: rgba(15,17,21,0.45); color: rgba(255,255,255,0.5);
          border-radius: var(--radius-sm) 0 0 0;
        }
        #service-areas .leaflet-control-attribution a { color: rgba(255,255,255,0.65); }

        /* draggable affordance */
        #service-areas .leaflet-container { cursor: grab; }
        #service-areas .leaflet-container:active { cursor: grabbing; }
        #service-areas .leaflet-marker-icon { cursor: pointer !important; }

        /* idle "breathing" so pins read as alive, not a screenshot */
        #service-areas .dx-pin { animation: dx-pin-bob 3.2s ease-in-out infinite; transform-origin: 50% 100%; }
        #service-areas .dx-pin:hover { animation-play-state: paused; }
        @keyframes dx-pin-bob {
          0%, 100% { transform: translateY(0); }
          50% { transform: translateY(-3px); }
        }

        /* styled zoom control */
        #service-areas .leaflet-bar a {
          background: rgba(15,17,21,0.78); color: #fff; border: none;
          border-bottom: 1px solid rgba(255,255,255,0.12); width: 30px; height: 30px; line-height: 30px;
          backdrop-filter: blur(6px);
        }
        #service-areas .leaflet-bar a:hover { background: var(--accent); }
        #service-areas .leaflet-bar { box-shadow: var(--shadow-md); border-radius: var(--radius-sm); overflow: hidden; }

        /* drag-to-explore hint */
        .dx-map-hint {
          position: absolute; top: 14px; left: 14px; z-index: 500;
          display: inline-flex; align-items: center; gap: 8px; padding: 7px 13px 7px 11px;
          background: rgba(15,17,21,0.78); backdrop-filter: blur(8px);
          border: 1px solid rgba(255,255,255,0.14); border-radius: var(--radius-full);
          color: #fff; font-family: var(--font-sans); font-weight: 600; font-size: 13px;
          box-shadow: var(--shadow-md); pointer-events: none;
          transition: opacity var(--dur-base) var(--ease-out), transform var(--dur-base) var(--ease-out);
        }
        .dx-map-hint[data-gone="true"] { opacity: 0; transform: translateY(-6px); }
        .dx-map-hint .dx-hand { color: var(--accent); display: inline-flex; animation: dx-hand-nudge 1.6s ease-in-out infinite; }
        @keyframes dx-hand-nudge {
          0%, 100% { transform: translateX(0); }
          50% { transform: translateX(5px); }
        }
        @media (prefers-reduced-motion: reduce) {
          #service-areas .dx-pin, .dx-map-hint .dx-hand { animation: none; }
        }
      `}</style>
      <div className="dx-container">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 56, alignItems: 'center' }} className="dx-areas-grid">
          <div>
            <Eyebrow>Where We Work</Eyebrow>
            <h2 style={{ fontFamily: 'var(--font-display)', textTransform: 'uppercase', fontSize: 'clamp(2.25rem,4vw,3.25rem)', lineHeight: 0.98, margin: '14px 0 0', fontWeight: 800 }}>
              Proudly Serving<br />The Lower Mainland
            </h2>
            <p style={{ color: 'var(--text-muted)', fontSize: 18, lineHeight: 1.55, margin: '16px 0 28px', maxWidth: 460 }}>
              Based in Burnaby, proudly serving the Lower Mainland and Metro Vancouver.
            </p>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
              {places.map((p) => (
                <button key={p.name} type="button" className="dx-area-chip"
                  data-active={selected === p.name}
                  aria-pressed={selected === p.name}
                  onClick={() => setSelected((s) => (s === p.name ? null : p.name))}>
                  <span className="dx-chip-dot"><i data-lucide="map-pin" style={{ width: 14, height: 14 }}></i></span>
                  {p.name}
                </button>
              ))}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 26, color: 'var(--text-muted)', fontSize: 14.5 }}>
              <i data-lucide="navigation" style={{ width: 16, height: 16, color: 'var(--accent)' }}></i>
              <span><strong style={{ color: 'var(--text-strong)' }}>6288 Cassey Ave, Burnaby BC</strong> . Not sure if you're in range? Just ask.</span>
            </div>
          </div>

          <div style={{ position: 'relative' }}>
            <div ref={mapRef} role="img" aria-label="Map of Danex Roofing service areas across Metro Vancouver"
              style={{ width: '100%', height: 380, borderRadius: 14, overflow: 'hidden',
                border: '1px solid var(--border-subtle)', background: 'var(--slate-900)', zIndex: 1 }}></div>
            <div className="dx-map-hint" data-gone={hintGone} aria-hidden="true">
              <span className="dx-hand"><i data-lucide="move" style={{ width: 15, height: 15 }}></i></span>
              Drag to explore · scroll to zoom
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

window.ServiceAreas = ServiceAreas;
