// UAE map — real Leaflet map with muted CartoDB basemap.
// Uses actual lat/lng for each neighborhood. Click a pin → popover locks open.

const { useState, useRef, useEffect } = React;

function UAEMap({ active, setActive, onSelectNeighborhood, L, lang }) {
  const isRTL = lang === 'ar';
  const { NEIGHBORHOODS, PROPERTIES } = window.DATA;
  const [hover, setHover] = useState(null);
  const [locked, setLocked] = useState(null);
  const mapDiv = useRef(null);
  const mapRef = useRef(null);
  const markersRef = useRef({});

  // Resolve display name for a neighborhood in the current language
  function getNhDisplay(n) {
    const tr = (isRTL && window.I18N_NEIGHBORHOODS) ? window.I18N_NEIGHBORHOODS[n.id] : null;
    return {
      name: tr ? tr.name : n.name,
      tag: tr ? tr.tag : n.tag,
      blurb: tr ? tr.blurb : n.blurb,
      emirate: isRTL ? (n.emirate === 'Dubai' ? L.mapUI.dubai : L.mapUI.abuDhabi) : n.emirate,
    };
  }

  const current = locked ? NEIGHBORHOODS.find(n => n.id === locked) : (hover ? NEIGHBORHOODS.find(n => n.id === hover) : null);

  // Emirate focus helpers
  function focusEmirate(emirate) {
    if (!mapRef.current) return;
    const L = window.L;
    const pins = NEIGHBORHOODS.filter(n => n.emirate === emirate);
    if (pins.length === 0) return;
    const b = L.latLngBounds(pins.map(n => [n.ll.lat, n.ll.lng]));
    mapRef.current.flyToBounds(b, { padding: [80, 80], duration: 0.8, maxZoom: 12 });
  }
  function resetView() {
    if (!mapRef.current) return;
    const L = window.L;
    const bounds = L.latLngBounds([24.05, 53.55], [25.55, 55.60]);
    mapRef.current.flyToBounds(bounds, { padding: [40, 40], duration: 0.8 });
    setLocked(null);
  }

  useEffect(() => {
    if (!mapDiv.current || mapRef.current) return;
    const L = window.L;

    // Fit both Dubai and Abu Dhabi in view
    const bounds = L.latLngBounds(
      [24.05, 53.55],  // SW - offshore of Abu Dhabi
      [25.55, 55.60]   // NE - past Dubai
    );

    const map = L.map(mapDiv.current, {
      zoomControl: false,
      attributionControl: false,
      scrollWheelZoom: false,
      doubleClickZoom: true,
      dragging: true,
      minZoom: 8,
      maxZoom: 14,
    }).fitBounds(bounds, { padding: [40, 40] });

    // Muted basemap with visible coastlines + roads (CartoDB Voyager no-labels)
    L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager_nolabels/{z}/{x}/{y}{r}.png', {
      subdomains: 'abcd',
      maxZoom: 19,
    }).addTo(map);

    // No labels layer — our own callouts handle naming

    // Zoom controls (custom styled, top-right)
    const zoom = L.control.zoom({ position: 'topright' });
    zoom.addTo(map);

    // Click empty map → unlock
    map.on('click', () => setLocked(null));

    mapRef.current = map;

    // Fix tile rendering if container was resized after map init
    setTimeout(() => map.invalidateSize(), 100);
    setTimeout(() => map.invalidateSize(), 500);

    // Big emirate callout labels (anchored at approximate cluster centers)
    const dubaiLabel = L.divIcon({
      className: 'hm-emirate-label',
      html: `<div class="hm-emirate-wrap" dir="${isRTL ? 'rtl' : 'ltr'}">
        <div class="hm-emirate-rule"></div>
        <div class="hm-emirate-name" style="${isRTL ? "font-family:'Amiri',serif;letter-spacing:0" : ''}">${L.mapUI ? '' : ''}${isRTL ? 'دبي' : 'DUBAI'}</div>
        <div class="hm-emirate-sub" style="${isRTL ? "font-family:'Noto Kufi Arabic',sans-serif" : ''}">${isRTL ? 'الإمارة الشماليّة' : 'Northern Emirate'}</div>
      </div>`,
      iconSize: [0, 0], iconAnchor: [0, 0],
    });
    const abuDhabiLabel = L.divIcon({
      className: 'hm-emirate-label',
      html: `<div class="hm-emirate-wrap" dir="${isRTL ? 'rtl' : 'ltr'}">
        <div class="hm-emirate-rule"></div>
        <div class="hm-emirate-name" style="${isRTL ? "font-family:'Amiri',serif;letter-spacing:0" : ''}">${isRTL ? 'أبوظبي' : 'ABU DHABI'}</div>
        <div class="hm-emirate-sub" style="${isRTL ? "font-family:'Noto Kufi Arabic',sans-serif" : ''}">${isRTL ? 'العاصمة' : 'The Capital'}</div>
      </div>`,
      iconSize: [0, 0], iconAnchor: [0, 0],
    });
    // Placed offshore in the Gulf, away from pins
    L.marker([25.40, 54.80], { icon: dubaiLabel, interactive: false, keyboard: false, zIndexOffset: -1000 }).addTo(map);
    L.marker([24.25, 53.75], { icon: abuDhabiLabel, interactive: false, keyboard: false, zIndexOffset: -1000 }).addTo(map);

    // Add pins
    NEIGHBORHOODS.forEach(n => {
      const count = PROPERTIES.filter(p => p.nh === n.id).length;
      const disp = getNhDisplay(n);
      // labelSide: 'left' = extends left of pin (right-anchored), 'right' = extends right
      const side = n.labelSide || 'right';
      const y = n.labelY || 0;
      // For LTR: 'right' side uses left:14px; 'left' side uses right:14px (label grows leftward)
      // For RTL: flip
      const labelPositionLTR = side === 'right'
        ? `left:14px;right:auto;text-align:left;top:${-4 + y}px`
        : `right:14px;left:auto;text-align:right;top:${-4 + y}px`;
      const labelPositionRTL = side === 'right'
        ? `right:14px;left:auto;text-align:right;top:${-4 + y}px`
        : `left:14px;right:auto;text-align:left;top:${-4 + y}px`;
      const labelStyle = isRTL ? labelPositionRTL : labelPositionLTR;
      const fontFam = isRTL ? "font-family:'Amiri',serif" : '';
      const countFam = isRTL ? "font-family:'Noto Kufi Arabic',sans-serif;letter-spacing:0.08em" : '';
      const icon = L.divIcon({
        className: 'hm-pin',
        html: `
          <div class="hm-pin-wrap" data-id="${n.id}">
            <div class="hm-pin-glow"></div>
            <div class="hm-pin-ring" style="border-color:${n.accent}">
              <div class="hm-pin-dot" style="background:${n.accent}"></div>
            </div>
            <div class="hm-pin-label" dir="${isRTL ? 'rtl' : 'ltr'}" style="${labelStyle}">
              <div class="hm-pin-name" style="${fontFam}">${disp.name}</div>
              <div class="hm-pin-count" style="${countFam}">${count} ${isRTL ? (count === 1 ? 'عقار' : 'عقارات') : (count === 1 ? 'RESIDENCE' : 'RESIDENCES')}</div>
            </div>
          </div>
        `,
        iconSize: [0, 0],
        iconAnchor: [0, 0],
      });
      const m = L.marker([n.ll.lat, n.ll.lng], { icon, riseOnHover: true }).addTo(map);
      m.on('click', (e) => {
        L.DomEvent.stopPropagation(e);
        setLocked(n.id);
      });
      m.on('mouseover', () => setHover(n.id));
      m.on('mouseout', () => setHover(null));
      markersRef.current[n.id] = m;
    });

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

  // Fly to locked pin
  useEffect(() => {
    if (locked && mapRef.current) {
      const n = NEIGHBORHOODS.find(x => x.id === locked);
      if (n) mapRef.current.panTo([n.ll.lat, n.ll.lng], { animate: true, duration: 0.6 });
    }
  }, [locked]);

  // Sync locked → parent active state (so the hero card knows to hide/show)
  useEffect(() => {
    setActive(locked);
  }, [locked]);

  // Update active pin class
  useEffect(() => {
    Object.keys(markersRef.current).forEach(id => {
      const el = markersRef.current[id].getElement();
      if (!el) return;
      const wrap = el.querySelector('.hm-pin-wrap');
      if (!wrap) return;
      wrap.classList.toggle('is-active', id === locked || id === hover);
      wrap.classList.toggle('is-locked', id === locked);
    });
  }, [hover, locked]);

  return (
    <div style={{position:'relative', width:'100%', height:'100%'}}>
      <div ref={mapDiv} style={{position:'absolute', inset:0, background:'#ebe4d6'}}/>

      {/* Sepia tint overlay to match site */}
      <div style={{
        position:'absolute', inset:0, pointerEvents:'none',
        background:'linear-gradient(180deg, rgba(243,238,229,0.22), rgba(227,217,195,0.28))',
        mixBlendMode:'multiply',
      }}/>

      {/* Legend — top; clicking focuses that emirate */}
      <div style={{
        position:'absolute', top:20,
        [isRTL ? 'left' : 'right']: 70,
        zIndex:500,
        display:'flex', gap:0,
        background:'rgba(243,238,229,0.92)',
        backdropFilter:'blur(8px)',
        border:'1px solid var(--line)',
      }}>
        <Legend color="#b89466" label={L.mapUI.dubai} count={NEIGHBORHOODS.filter(n => n.emirate === 'Dubai').length} areasLabel={L.mapUI.areas} onClick={() => focusEmirate('Dubai')}/>
        <div style={{width:1, background:'var(--line-2)'}}/>
        <Legend color="#8a6a3b" label={L.mapUI.abuDhabi} count={NEIGHBORHOODS.filter(n => n.emirate === 'Abu Dhabi').length} areasLabel={L.mapUI.areas} onClick={() => focusEmirate('Abu Dhabi')}/>
        <div style={{width:1, background:'var(--line-2)'}}/>
        <button onClick={() => resetView()} className="mono" style={{
          padding:'10px 16px', background:'transparent', border:'none',
          fontSize:9, color:'var(--mute)', cursor:'pointer', letterSpacing:'0.15em',
        }}>{isRTL ? 'عرض الكل' : 'SHOW ALL'}</button>
      </div>

      {/* Detail popover */}
      {current && (() => {
        const disp = getNhDisplay(current);
        return (
        <div style={{
          position:'absolute',
          [isRTL ? 'right' : 'left']: 32, bottom: 32,
          maxWidth: 360, zIndex:600,
          background:'#f3eee5',
          border:'1px solid var(--line)',
          padding:'22px 24px 20px',
          boxShadow:'0 20px 40px -20px rgba(18,18,18,0.22)',
        }}>
          {locked && (
            <button onClick={() => setLocked(null)}
              className="mono"
              style={{
                position:'absolute', top:10,
                [isRTL ? 'left' : 'right']: 10,
                width:24, height:24, color:'var(--mute)',
                fontSize:13, cursor:'pointer',
              }}>✕</button>
          )}
          <div className="mono" style={{color:'var(--bronze)', marginBottom:10}}>
            {disp.emirate} · {disp.tag}
          </div>
          <div className="display" style={{fontSize:32, lineHeight:1.2, marginBottom:10}}>{disp.name}</div>
          <div style={{fontSize:13.5, lineHeight:1.65, color:'var(--ink-2)', marginBottom:16}}>{disp.blurb}</div>
          <div style={{display:'flex', gap:22, paddingTop:14, paddingBottom:14, borderTop:'1px solid var(--line-2)', borderBottom:'1px solid var(--line-2)', marginBottom:14}}>
            <div>
              <div className="mono" style={{color:'var(--mute)', fontSize:9, marginBottom:4}}>{L.mapUI.listings}</div>
              <div className="display" style={{fontSize:20}}>{current.stats.listings}</div>
            </div>
            <div>
              <div className="mono" style={{color:'var(--mute)', fontSize:9, marginBottom:4}}>{L.mapUI.typical}</div>
              <div className="display" style={{fontSize:20}}>{current.stats.avg}</div>
            </div>
          </div>
          {locked ? (
            <button onClick={() => onSelectNeighborhood(current.id)}
              className="mono"
              style={{
                width:'100%', padding:'12px', background:'var(--ink)',
                color:'var(--ivory)', fontSize:10, cursor:'pointer', border:'none',
              }}>
              {L.mapUI.viewRes}
            </button>
          ) : (
            <div className="mono" style={{color:'var(--mute)', fontSize:9, textAlign:'center', padding:'8px 0'}}>
              {L.mapUI.clickPin}
            </div>
          )}
        </div>
        );
      })()}

      <style>{`
        .hm-pin { background: transparent; border: none; }
        .hm-pin-wrap {
          position: relative;
          width: 0; height: 0;
          cursor: pointer;
        }
        .hm-pin-glow {
          position: absolute;
          left: -26px; top: -26px;
          width: 52px; height: 52px;
          border-radius: 50%;
          background: radial-gradient(circle, rgba(184,148,102,0.45), rgba(184,148,102,0));
          opacity: 0;
          transition: opacity .3s;
          pointer-events: none;
        }
        .hm-pin-wrap.is-active .hm-pin-glow { opacity: 1; animation: hmPulse 2.6s ease-in-out infinite; }
        @keyframes hmPulse { 0%,100% { transform: scale(1); } 50% { transform: scale(1.35); } }
        .hm-pin-ring {
          position: absolute;
          left: -9px; top: -9px;
          width: 18px; height: 18px;
          border-radius: 50%;
          background: #f3eee5;
          border: 1.4px solid;
          display: flex; align-items: center; justify-content: center;
          transition: all .2s;
        }
        .hm-pin-wrap.is-active .hm-pin-ring { border-width: 2.4px; transform: scale(1.1); }
        .hm-pin-dot {
          width: 6px; height: 6px; border-radius: 50%;
          transition: all .2s;
        }
        .hm-pin-wrap.is-locked .hm-pin-dot { animation: hmDot 1.6s ease-in-out infinite; }
        @keyframes hmDot { 0%,100% { transform: scale(1); } 50% { transform: scale(1.5); } }
        .hm-pin-label {
          position: absolute;
          left: 14px; top: -4px;
          white-space: nowrap;
          text-shadow: 0 0 2px #ebe4d6, 0 0 6px #ebe4d6, 0 0 2px #ebe4d6;
          opacity: 0;
          transform: translateY(2px);
          transition: opacity .2s ease, transform .2s ease;
          pointer-events: none;
        }
        .hm-pin-wrap.is-active .hm-pin-label {
          opacity: 1;
          transform: translateY(0);
        }
        .hm-pin-name {
          font-family: 'Italiana', serif;
          font-size: 17px;
          color: #121212;
          line-height: 1.1;
        }
        .hm-pin-count {
          font-family: 'Archivo Narrow', sans-serif;
          font-size: 9px;
          letter-spacing: 2px;
          color: #8a6a3b;
          margin-top: 3px;
        }

        /* Big emirate callouts behind pins */
        .hm-emirate-label { background: transparent; border: none; pointer-events: none; }
        .hm-emirate-wrap {
          position: absolute;
          transform: translate(-50%, -50%);
          text-align: center;
          white-space: nowrap;
          pointer-events: none;
          mix-blend-mode: multiply;
          opacity: 0.42;
        }
        .hm-emirate-rule {
          width: 48px; height: 1px;
          background: #8a6a3b;
          margin: 0 auto 10px;
          opacity: 0.4;
        }
        .hm-emirate-name {
          font-family: 'Italiana', serif;
          font-size: 34px;
          letter-spacing: 0.18em;
          color: #3a2f22;
          line-height: 1;
          text-shadow: 0 0 6px rgba(243,238,229,0.9), 0 0 14px rgba(243,238,229,0.7);
        }
        .hm-emirate-sub {
          font-family: 'Archivo Narrow', sans-serif;
          font-size: 9px;
          letter-spacing: 0.3em;
          color: #8a6a3b;
          margin-top: 8px;
          text-transform: uppercase;
          text-shadow: 0 0 6px rgba(243,238,229,0.9);
        }
        body[data-map-mood='nocturne'] .hm-emirate-name { color: #d9cdb4; text-shadow: 0 0 10px rgba(26,23,19,0.9); }
        body[data-map-mood='nocturne'] .hm-emirate-sub { color: #b89466; text-shadow: 0 0 6px rgba(26,23,19,0.9); }
        body[data-map-mood='nocturne'] .hm-emirate-wrap { mix-blend-mode: normal; opacity: 0.72; }

        /* Leaflet zoom controls - restyle to match */
        .leaflet-control-zoom {
          border: 1px solid var(--line) !important;
          box-shadow: none !important;
        }
        .leaflet-control-zoom a {
          background: rgba(243,238,229,0.92) !important;
          color: var(--ink) !important;
          border-bottom: 1px solid var(--line-2) !important;
          font-family: 'Italiana', serif !important;
          font-weight: 400 !important;
        }
        .leaflet-control-zoom a:hover {
          background: var(--ivory) !important;
          color: var(--bronze) !important;
        }
        .leaflet-container { background: #ebe4d6; font: inherit; }
        .leaflet-tile { opacity: 1 !important; }
        body[data-map-mood='daylight'] .leaflet-tile-pane { filter: sepia(0.18) saturate(0.75) hue-rotate(-5deg) brightness(1.02); }
        body[data-map-mood='dusk'] .leaflet-tile-pane { filter: sepia(0.55) saturate(0.65) hue-rotate(-18deg) brightness(0.85) contrast(1.05); }
        body[data-map-mood='nocturne'] .leaflet-tile-pane { filter: invert(0.92) sepia(0.5) saturate(0.6) hue-rotate(180deg) brightness(0.85) contrast(1.1); }
        body[data-map-mood='nocturne'] .leaflet-container { background: #1a1713; }
      `}</style>
    </div>
  );
}

function Legend({color, label, count, areasLabel, onClick}) {
  return (
    <button onClick={onClick} style={{
      padding:'10px 16px', display:'flex', alignItems:'center', gap:10,
      whiteSpace:'nowrap', background:'transparent', border:'none',
      cursor: onClick ? 'pointer' : 'default',
    }}>
      <span style={{width:8, height:8, borderRadius:'50%', background:color, border:'1.5px solid #f3eee5', boxShadow:`0 0 0 1px ${color}`, flexShrink:0}}/>
      <div style={{textAlign:'left'}}>
        <div className="mono" style={{fontSize:10, color:'var(--ink)', whiteSpace:'nowrap'}}>{label}</div>
        <div className="mono" style={{fontSize:8, color:'var(--mute)', marginTop:1, whiteSpace:'nowrap'}}>{count} {areasLabel}</div>
      </div>
    </button>
  );
}

window.UAEMap = UAEMap;
