/**
 * Oveyo PWA — Page Carte (Leaflet réelle + filtres produits + liste boutiques)
 * V3.2 : boutiques cliquables (liste + markers) → ouvre ShopDetailSheet
 */

const { useState, useEffect, useRef } = React;
const Lu2 = window.LucideReact || {};
const { Card: CardC, IconBubble: IB, Spinner: Sp, EmptyState: ES } = window.OveyoUI;
const { useShops: uShops, useCatalog: uCatalog } = window.OveyoState;

const MapPage = ({ state, setActiveTab, onOpenSheet }) => {
  const { Store, Check, ShieldCheck, Clock, MapPin, Filter, ChevronRight } = Lu2;
  const { products } = uCatalog();
  const [selectedProduct, setSelectedProduct] = useState('sucre');
  const [neighborhoodFilter, setNeighborhoodFilter] = useState(state.user.neighborhood_slug || '');
  const { shops, loading } = uShops(selectedProduct, neighborhoodFilter);

  const mapRef = useRef(null);
  const mapInstance = useRef(null);
  const markersGroup = useRef(null);
  // ref vers la dernière callback onOpenSheet — pour qu'elle soit accessible
  // depuis l'event handler des markers Leaflet sans recréer toute la carte
  const onOpenSheetRef = useRef(onOpenSheet);
  useEffect(() => { onOpenSheetRef.current = onOpenSheet; }, [onOpenSheet]);

  // Init Leaflet map (une seule fois)
  useEffect(() => {
    if (!mapRef.current || mapInstance.current) return;
    if (typeof L === 'undefined') return;

    const map = L.map(mapRef.current, {
      center: [14.7359, -17.4631],
      zoom: 13,
      zoomControl: false,
      attributionControl: false,
    });

    L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
      maxZoom: 19,
      attribution: '© OpenStreetMap contributors, © CARTO',
    }).addTo(map);

    L.control.zoom({ position: 'topright' }).addTo(map);
    L.control.attribution({ position: 'bottomleft', prefix: false }).addTo(map);

    mapInstance.current = map;
    markersGroup.current = L.layerGroup().addTo(map);

    // Géolocaliser l'utilisateur
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (pos) => {
          map.setView([pos.coords.latitude, pos.coords.longitude], 14);
          L.circleMarker([pos.coords.latitude, pos.coords.longitude], {
            radius: 8,
            fillColor: '#F4632B',
            color: 'white',
            weight: 3,
            fillOpacity: 1,
          }).addTo(map).bindPopup('Tu es ici');
        },
        () => {},
        { timeout: 5000 }
      );
    }

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

  // Mettre à jour les marqueurs quand les boutiques changent
  useEffect(() => {
    if (!mapInstance.current || !markersGroup.current) return;
    markersGroup.current.clearLayers();

    shops.forEach((s) => {
      if (!s.lat || !s.lng) return;
      const color = s.is_abuse ? '#F4632B' : s.stock === 'rupture' ? '#6B7891' : '#102A43';
      const label = s.price ? `${s.price} F` : '—';

      const icon = L.divIcon({
        className: 'price-marker',
        html: `<div style="position:relative;display:flex;flex-direction:column;align-items:center;cursor:pointer;">
          <div style="background:${color};color:white;font-weight:700;font-size:11px;padding:6px 8px;border-radius:14px;box-shadow:0 2px 8px rgba(0,0,0,0.2);min-width:32px;text-align:center;font-family:'DM Sans',sans-serif;">${label}</div>
          <div style="width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;border-top:6px solid ${color};margin-top:-1px;"></div>
        </div>`,
        iconSize: [40, 30],
        iconAnchor: [20, 30],
      });

      const marker = L.marker([s.lat, s.lng], { icon }).addTo(markersGroup.current);

      // C2 : click sur marker → ouvre ShopDetailSheet (au lieu d'un popup)
      marker.on('click', () => {
        if (typeof onOpenSheetRef.current === 'function' && s.id) {
          onOpenSheetRef.current('shop-detail', { shop_id: s.id });
        }
      });
    });

    // Adapter le zoom aux marqueurs si on en a
    if (shops.length > 0) {
      const validShops = shops.filter((s) => s.lat && s.lng);
      if (validShops.length > 0) {
        const bounds = L.latLngBounds(validShops.map((s) => [s.lat, s.lng]));
        mapInstance.current.fitBounds(bounds, { padding: [40, 40], maxZoom: 15 });
      }
    }
  }, [shops]);

  return (
    <div className="space-y-0">
      {/* Carte */}
      <div ref={mapRef} className="w-full h-64" style={{ background: '#DDE3EC' }} />

      {/* Filtres */}
      <div className="px-5 py-4 space-y-3">
        <div className="flex gap-2 overflow-x-auto pb-1 -mx-5 px-5">
          {products.map((p) => (
            <button
              key={p.slug}
              onClick={() => setSelectedProduct(p.slug)}
              className="px-3.5 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap transition-colors"
              style={{
                background: selectedProduct === p.slug ? '#102A43' : 'white',
                color: selectedProduct === p.slug ? 'white' : '#0F1F36',
                border: selectedProduct === p.slug ? 'none' : '1px solid #DDE3EC',
              }}
            >
              {p.icon} {p.name_fr.split(' ')[0]}
            </button>
          ))}
        </div>

        {/* Liste boutiques */}
        {loading ? (
          <div className="text-center py-8"><Sp /></div>
        ) : shops.length === 0 ? (
          <ES
            icon={Store}
            title="Aucune boutique trouvée"
            subtitle={`Pas encore de prix partagé pour ce produit dans ce quartier. Contribue en partageant un prix !`}
          />
        ) : (
          <div className="space-y-2.5">
            {shops.map((s, i) => (
              <div
                key={s.id || i}
                className="bg-white rounded-2xl overflow-hidden"
                style={{ border: s.is_abuse ? '1.5px solid #F4632B' : '1px solid #EAEEF4' }}
              >
                {/* Ligne principale — devient un BOUTON CLIQUABLE */}
                <button
                  onClick={() => onOpenSheet?.('shop-detail', { shop_id: s.id })}
                  className="w-full p-3.5 flex items-center gap-3 text-left active:bg-bg-2"
                >
                  <div
                    className="w-11 h-11 rounded-xl flex items-center justify-center flex-shrink-0 relative"
                    style={{ background: s.stock === 'dispo' ? '#E8F5E9' : '#F1F4F9' }}
                  >
                    <Store size={20} style={{ color: s.stock === 'dispo' ? '#15803D' : '#6B7891' }} strokeWidth={2.2} />
                    <div
                      className="absolute -bottom-0.5 -right-0.5 w-4 h-4 rounded-full flex items-center justify-center"
                      style={{ background: s.stock === 'dispo' ? '#15803D' : '#6B7891' }}
                    >
                      {s.stock === 'dispo'
                        ? <Check size={9} className="text-white" strokeWidth={3.5} />
                        : <span className="text-white text-[8px] font-bold">×</span>}
                    </div>
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-1.5">
                      <div className="font-semibold text-sm truncate text-ink">{s.name}</div>
                      {!!s.verified && <ShieldCheck size={12} style={{ color: '#102A43' }} strokeWidth={2.5} />}
                    </div>
                    <div className="flex items-center gap-2 text-[11px] mt-0.5 text-slate">
                      <span>{s.area}</span>
                      {!!s.distance && (<><span>·</span><span>{s.distance}</span></>)}
                      {!!s.trust_score && (<><span>·</span><span>⭐ {s.trust_score.toFixed(1)}</span></>)}
                    </div>
                  </div>
                  <div className="text-right">
                    {s.price ? (
                      <>
                        <div
                          className="font-display font-bold"
                          style={{
                            color: s.is_abuse ? '#F4632B' : '#0F1F36',
                            // V3.9 — opacité réduite si prix non encore validé
                            opacity: s.price_status === 'pending' ? 0.55 : 1,
                          }}
                        >
                          {s.price} F
                        </div>
                        {!!s.is_abuse && <div className="text-[9px] font-bold uppercase text-orange">Abus</div>}
                        {/* V3.9 — badge "À vérifier" pour les prix pending */}
                        {s.price_status === 'pending' && (
                          <div className="text-[9px] font-bold uppercase mt-0.5" style={{ color: '#9A6F00' }}>
                            À vérifier
                          </div>
                        )}
                      </>
                    ) : (
                      <div
                        className="text-[10px] font-bold uppercase px-2 py-1 rounded text-slate"
                        style={{ background: '#F1F4F9' }}
                      >Rupture</div>
                    )}
                  </div>
                  <ChevronRight size={16} className="flex-shrink-0" style={{ color: '#5B6B7E' }} />
                </button>

                {!s.verified && (
                  <button
                    onClick={(e) => { e.stopPropagation(); onOpenSheet('claim-shop', { shop: s }); }}
                    className="w-full px-3.5 py-2 text-[11px] font-bold flex items-center justify-center gap-1.5 border-t"
                    style={{ borderColor: '#EAEEF4', color: '#F4632B', background: '#FEF8F4' }}
                  >
                    <Store size={11} /> Tu es propriétaire ? Réclame cette boutique →
                  </button>
                )}
                {!!s.is_abuse && (
                  <div
                    className="px-3.5 py-2 text-[11px] border-t flex items-center gap-1.5 text-slate"
                    style={{ borderColor: '#EAEEF4', background: '#FEF8F4' }}
                  >
                    <Clock size={11} /> Boutique invitée à justifier — réponse en attente
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

window.OveyoPages = window.OveyoPages || {};
window.OveyoPages.MapPage = MapPage;
