// Real Leaflet/OpenStreetMap map component.
// Renders tiles + branch markers + selection sync.

const { useEffect: useEffectLeaf, useRef: useRefLeaf } = React;

function LeafletMap({ branches, selectedId, onSelect, height = '100%', interactive = true, defaultZoom = 9, defaultCenter = [25.1, 54.9] }) {
  const containerRef = useRefLeaf(null);
  const mapRef = useRefLeaf(null);
  const markerRefs = useRefLeaf({});
  const filteredIds = new Set(branches.map(b => b.id));

  if (!window.L) {
    return (
      <div style={{
        height,
        width: '100%',
        borderRadius: 'var(--radius)',
        overflow: 'hidden',
        background: 'linear-gradient(135deg, #EFE5D4, #DCE6E8)',
        border: '1px solid rgba(31,27,23,0.12)',
        display: 'grid',
        placeItems: 'center',
        padding: 24,
        textAlign: 'center'
      }}>
        <div>
          <div style={{ fontFamily: 'var(--font-serif)', fontSize: 24, color: 'var(--charcoal)' }}>Branch map</div>
          <p style={{ marginTop: 8, marginBottom: 18, color: 'var(--muted)', maxWidth: 360 }}>
            Map tiles are loading slowly. Branch directions are still available.
          </p>
          <a className="btn btn--primary btn--sm" href="https://www.google.com/maps/search/?api=1&query=Automatic+Restaurant+and+Grill+Dubai" target="_blank" rel="noopener">
            Open Google Maps
          </a>
        </div>
      </div>
    );
  }

  // Initialize map once
  useEffectLeaf(() => {
    if (!containerRef.current || mapRef.current || !window.L) return;
    const map = window.L.map(containerRef.current, {
      zoomControl: interactive,
      attributionControl: true,
      scrollWheelZoom: interactive,
      dragging: interactive,
      doubleClickZoom: interactive,
      touchZoom: interactive,
      boxZoom: interactive,
      keyboard: interactive,
    }).setView(defaultCenter, defaultZoom);

    // Carto Voyager — clean cartographic style, English labels, retina-aware
    window.L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png', {
      attribution: '&copy; OpenStreetMap &copy; CARTO',
      subdomains: 'abcd',
      maxZoom: 19,
    }).addTo(map);

    mapRef.current = map;

    // Add all branches as markers
    window.BRANCHES.forEach(b => {
      const isActive = filteredIds.has(b.id);
      const marker = window.L.marker(b.latlng, {
        icon: brandIcon(isActive, false),
        riseOnHover: true,
      }).addTo(map);
      marker.on('click', () => onSelect && onSelect(b.id));
      marker.bindTooltip(`<div style="font-family:'Playfair Display',serif;font-weight:600;font-size:13px;color:#1F1B17">${b.name}</div><div style="font-family:Inter,sans-serif;font-size:11px;color:#5B5147;margin-top:2px">${b.sub}</div>`, {
        direction: 'top', offset: [0, -28], opacity: 1,
        className: 'leaflet-brand-tooltip',
      });
      markerRefs.current[b.id] = marker;
    });

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

  // Sync filter state -> marker icons (active/inactive)
  useEffectLeaf(() => {
    Object.entries(markerRefs.current).forEach(([id, marker]) => {
      const isActive = filteredIds.has(id);
      const isSelected = selectedId === id;
      marker.setIcon(brandIcon(isActive, isSelected));
      marker.setZIndexOffset(isSelected ? 1000 : (isActive ? 100 : 0));
    });
    if (selectedId && markerRefs.current[selectedId] && mapRef.current) {
      const b = window.BRANCHES.find(b => b.id === selectedId);
      if (b) {
        const z = Math.max(mapRef.current.getZoom(), 11);
        mapRef.current.flyTo(b.latlng, z, { duration: 0.6 });
      }
    }
  }, [selectedId, branches]);

  return (
    <div
      ref={containerRef}
      style={{
        height: height,
        width: '100%',
        borderRadius: 'var(--radius)',
        overflow: 'hidden',
        background: '#DCE6E8',
      }}
    />
  );
}

// Branded pin icon — terracotta circle for active, muted for filtered out, larger ring on selected.
function brandIcon(active, selected) {
  const size = selected ? 36 : 28;
  const fill = active ? '#B7472A' : '#A89678';
  const ringOpacity = active ? 0.25 : 0.15;
  const pulse = selected ? `<circle cx="${size/2}" cy="${size/2}" r="${size/2 - 2}" fill="#B7472A" opacity="0.18"><animate attributeName="r" values="${size/2-6};${size/2-1};${size/2-6}" dur="1.8s" repeatCount="indefinite"/><animate attributeName="opacity" values="0.3;0.05;0.3" dur="1.8s" repeatCount="indefinite"/></circle>` : '';
  const svg = `
    <svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">
      ${pulse}
      <circle cx="${size/2}" cy="${size/2}" r="${size/2 - 6}" fill="${fill}" opacity="${ringOpacity}"/>
      <circle cx="${size/2}" cy="${size/2}" r="${selected ? 8 : 6}" fill="${fill}" stroke="#FFFCF6" stroke-width="${selected ? 2.5 : 2}"/>
      ${selected ? `<circle cx="${size/2}" cy="${size/2}" r="2.5" fill="#FFFCF6"/>` : ''}
    </svg>`;
  return window.L.divIcon({
    html: svg,
    className: 'brand-marker',
    iconSize: [size, size],
    iconAnchor: [size/2, size/2],
  });
}

window.LeafletMap = LeafletMap;
