'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { GoogleMap, OverlayView } from '@react-google-maps/api';
import { MarkerClusterer, SuperClusterAlgorithm } from '@googlemaps/markerclusterer';
import { useGoogleMapsLoader } from '@/hooks';
import {
  openViewportSSE,
  GeoMarkerHotelWithPricing, GeoBounds,
  GeoViewportParams,
} from '@/services/search/search.client';
import { AvailableFilters } from '@/services/search/types';
import { parseChildrenAges } from '@/utils/sanitize';
import { PriceRangeFilter } from '@/components/search/filters/PricingPerNightFilter';
import HotelHoverCard from './explorer-map/HotelHoverCard';
import MapExploreFilterPanel, { MapFiltersState, MapFilterValue } from './explorer-map/MapExploreFilterPanel';
import { assetPath } from '@/utils/assets';
import type { SrpMapFocusHotel } from '@/context/SrpMapContext';

interface MapExploreModalProps {
  isOpen: boolean;
  onClose: () => void;
  mapCenter?: { lat: number; lng: number };
  /** When opening from a hotel card, center/zoom on this hotel. */
  initialFocusHotel?: { id: string; name: string; lat: number; lng: number } | null;
  /** Zoom level at which clustering stops. Above this zoom markers render individually. Default: 15 */
  clusterMaxZoom?: number;
  /** Fill color of cluster bubbles (any CSS color). Default: '#003580' */
  clusterColor?: string;
}

const MAP_CONTAINER_STYLE: React.CSSProperties = {
  position: 'absolute',
  inset: 0,
  width: '100%',
  height: '100%',
};

const MAP_OPTIONS: google.maps.MapOptions = {
  disableDefaultUI: false,
  zoomControl: true,
  streetViewControl: false,
  mapTypeControl: false,
  fullscreenControl: false,
  minZoom: 2,
  maxZoom: 18,
  scrollwheel: true,
};

// Default centre (can be overridden via map load logic)
const DEFAULT_CENTER = { lat: 25.2048, lng: 55.2708 }; // Dubai

// ─────────────────────────────────────────────────────────────────────────────
// Price-tag marker helpers
// ─────────────────────────────────────────────────────────────────────────────

/** Extract a formatted price label from a hotel's pricing data, or null if unavailable. */
function formatPriceLabel(hotel: GeoMarkerHotelWithPricing): string | null {
  const pricing = hotel.pricing;
  if (!pricing?.prices_available || !pricing?.available) return null;
  const offer = pricing.offers?.[0];
  if (!offer) return null;
  const price = offer.pricePerNight?.basePricePerNight;
  const currency = offer.pricePerNight?.currency ?? 'USD';
  if (!price) return null;
  try {
    return new Intl.NumberFormat('en', {
      style: 'currency',
      currency,
      maximumFractionDigits: 0,
    }).format(price);
  } catch {
    return `${currency} ${Math.round(price)}`;
  }
}

/** Build a price-tag SVG data-URI icon. Must only be called after Google Maps API is loaded. */
function buildPriceTagIcon(label: string): google.maps.Icon {
  const charW = 9;
  const padX = 12;
  const width = Math.max(64, label.length * charW + padX * 2);
  const bubbleH = 28;
  const tailH = 7;
  const totalH = bubbleH + tailH;
  const cx = width / 2;
  const r = 6;
  const bg = '#003580';

  const svg = [
    `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${totalH}" viewBox="0 0 ${width} ${totalH}">`,
    `<rect x="0" y="0" width="${width}" height="${bubbleH}" rx="${r}" fill="${bg}"/>`,
    `<polygon points="${cx - 6},${bubbleH} ${cx + 6},${bubbleH} ${cx},${totalH}" fill="${bg}"/>`,
    `<text x="${cx}" y="${bubbleH / 2 - 0.5}" text-anchor="middle" dominant-baseline="central"`,
    ` fill="#fff" font-size="11" font-weight="700" font-family="system-ui,-apple-system,sans-serif">${label}</text>`,
    `</svg>`,
  ].join('');

  return {
    url: `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(svg)}`,
    scaledSize: new google.maps.Size(width, totalH),
    anchor: new google.maps.Point(cx, totalH),
  };
}

/** Return the right icon for a hotel — price-tag chip when pricing is available, default pin otherwise. */
function buildMarkerIcon(hotel: GeoMarkerHotelWithPricing): google.maps.Icon | { url: string } {
  const label = formatPriceLabel(hotel);
  if (label) return buildPriceTagIcon(label);
  return { url: assetPath('/assets/img/hotel-marker.png') };
}

/** Builds a MarkerClusterer renderer that draws a filled SVG circle in `color`. */
function createClusterRenderer(color: string) {
  return {
    render({ count, position }: { count: number; position: google.maps.LatLng }) {
      // Scale bubble slightly with count
      const size = count < 10 ? 36 : count < 100 ? 42 : 48;
      const half = size / 2;
      const fontSize = size < 42 ? 13 : 14;
      const svg = [
        `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">`,
        `<circle cx="${half}" cy="${half}" r="${half - 2}" fill="${color}" fill-opacity="0.9" stroke="#fff" stroke-width="2.5"/>`,
        `<text x="50%" y="50%" text-anchor="middle" dominant-baseline="central"`,
        ` fill="#fff" font-size="${fontSize}" font-weight="700" font-family="sans-serif">${count}</text>`,
        `</svg>`,
      ].join('');
      return new google.maps.Marker({
        position,
        icon: {
          url: `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(svg)}`,
          scaledSize: new google.maps.Size(size, size),
          anchor: new google.maps.Point(half, half),
        },
        zIndex: Number(google.maps.Marker.MAX_ZINDEX) + count,
      });
    },
  };
}

export default function MapExploreModal({
  isOpen,
  onClose,
  mapCenter = DEFAULT_CENTER,
  initialFocusHotel = null,
  clusterMaxZoom = 15,
  clusterColor = '#f45d6b',
  // clusterColor = '#003580',
}: MapExploreModalProps) {
  const searchParams = useSearchParams();

  const [hotels, setHotels] = useState<GeoMarkerHotelWithPricing[]>([]);
  const [isLoadingHotels, setIsLoadingHotels] = useState(false);
  const [isPricingLoading, setIsPricingLoading] = useState(false);
  const [hoveredHotel, setHoveredHotel] = useState<GeoMarkerHotelWithPricing | null>(null);
  const [mapInstance, setMapInstance] = useState<google.maps.Map | null>(null);
  // Filter state — managed internally; changes trigger a new SSE fetch
  const [appliedFilters, setAppliedFilters] = useState<MapFiltersState>({});
  // Available filters populated progressively from SSE `hotels` / `complete` events
  const [internalAvailableFilters, setInternalAvailableFilters] = useState<AvailableFilters | undefined>(undefined);
  // Dynamic transform so the card never overflows the viewport edges
  const [cardTransform, setCardTransform] = useState('translate(-50%, calc(-100% - 40px))');
  // Controls the mobile filter overlay (full-screen panel on small screens)
  const [showMobileFilters, setShowMobileFilters] = useState(false);

  const mapRef = useRef<google.maps.Map | null>(null);
  const sseAbortRef = useRef<AbortController | null>(null);
  const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  // Stores the last fetched bounds+zoom so filter changes can re-trigger a fetch
  const lastBoundsRef = useRef<{ bounds: GeoBounds; zoom?: number } | null>(null);
  // Delays clearing the hovered hotel so the cursor can move from pin → card without dismissal
  const hoverLeaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const clustererRef = useRef<MarkerClusterer | null>(null);
  const nativeMarkersRef = useRef<Map<string, google.maps.Marker>>(new Map());
  // Tracks the latest hotel data by property_code — used in marker listeners to get fresh pricing
  const hotelsMapRef = useRef<Map<string, GeoMarkerHotelWithPricing>>(new Map());
  // Tracks which markers already show a price-tag icon — avoids redundant setIcon calls
  const markerHasPricingRef = useRef<Set<string>>(new Set());

  const { isLoaded } = useGoogleMapsLoader();

  const effectiveCenter = initialFocusHotel
    ? { lat: initialFocusHotel.lat, lng: initialFocusHotel.lng }
    : mapCenter;

  useEffect(() => {
    if (!isOpen || !initialFocusHotel || !mapInstance) return;
    mapInstance.panTo({ lat: initialFocusHotel.lat, lng: initialFocusHotel.lng });
    mapInstance.setZoom(15);
  }, [isOpen, initialFocusHotel, mapInstance]);

  useEffect(() => {
    if (!isOpen || !initialFocusHotel || hotels.length === 0) return;
    const match =
      hotels.find((h) => h.property_code === initialFocusHotel.id) ??
      hotels.find(
        (h) =>
          Math.abs(h.location.lat - initialFocusHotel.lat) < 0.0001 &&
          Math.abs(h.location.lng - initialFocusHotel.lng) < 0.0001
      );
    if (match) setHoveredHotel(match);
  }, [isOpen, initialFocusHotel, hotels]);

  // Unified SSE fetch — opens a single stream that returns hotels then pricing.
  // clearFirst=true: wipe existing hotels + map markers before fetching (used on filter change).
  // clearFirst=false (default): additive — new hotels accumulate on top of existing ones (used on map pan/zoom).
  const fetchHotelsByBounds = useCallback((bounds: GeoBounds, zoom?: number, clearFirst = false) => {
    // Cancel any in-flight SSE stream
    sseAbortRef.current?.abort();
    const controller = new AbortController();
    sseAbortRef.current = controller;

    if (clearFirst) {
      // Wipe hotels state and all native map markers so the map is blank before new results arrive
      setHotels([]);
      if (clustererRef.current) clustererRef.current.clearMarkers();
      nativeMarkersRef.current.forEach((m) => {
        google.maps.event.clearInstanceListeners(m);
        m.setMap(null);
      });
      nativeMarkersRef.current.clear();
      markerHasPricingRef.current.clear();
      hotelsMapRef.current.clear();
    }

    // Build pricing params from URL search params
    const checkinDate  = searchParams.get('checkinDate')  ?? undefined;
    const checkoutDate = searchParams.get('checkoutDate') ?? undefined;
    const rooms  = searchParams.get('rooms')  ? Number(searchParams.get('rooms'))  : 1;
    const adults = searchParams.get('adults') ? Number(searchParams.get('adults')) : 2;
    const children: number[] = parseChildrenAges(searchParams.get('children'));

    // Map appliedFilters from props into API shape
    const star_rating = (appliedFilters.starRating as string[] | undefined)
      ?.map(Number).filter(Boolean);
    const amenities = appliedFilters.amenities as string[] | undefined;
    const chains    = appliedFilters.chains    as string[] | undefined;
    const priceRangeFilter = appliedFilters.priceRange as PriceRangeFilter | undefined;
    const priceRange = priceRangeFilter
      ? { from: priceRangeFilter.from, to: priceRangeFilter.to }
      : undefined;

    const viewportParams: GeoViewportParams = {
      bounds,
      ...(zoom !== undefined && { zoom }),
      ...(star_rating?.length && { star_rating }),
      ...(amenities?.length   && { amenities }),
      ...(chains?.length      && { chains }),
      ...(checkinDate  && { checkinDate }),
      ...(checkoutDate && { checkoutDate }),
      rooms,
      adults,
      children,
      ...(priceRange && { priceRange }),
    };

    setIsLoadingHotels(true);
    setIsPricingLoading(false);

    openViewportSSE(viewportParams, {
      // ── 1. Hotels arrive immediately from ES (with Redis-cached pricing attached) ──
      onHotels: (data) => {
        setIsLoadingHotels(false);
        setInternalAvailableFilters(data.availableFilters);
        // Additive merge — already-seen hotels keep their map markers
        setHotels(data.hotels)
        // setHotels(prev => {
        //   const cache = new Map(prev.map(h => [h.property_code, h]));
        //   data.hotels.forEach(h => cache.set(h.property_code, h));
        //   return Array.from(cache.values());
        // });
        if (data.pricingEnabled) setIsPricingLoading(true);
      },

      // ── 2. Each Amadeus batch resolves: hotels carry their pricing now ───
      onPricingBatch: (data) => {
        if (data.availableFilters) setInternalAvailableFilters(data.availableFilters);
        setHotels(prev => {
          const cache = new Map(prev.map(h => [h.property_code, h]));
          // Merge batch hotels — pricing is already attached on each object
          data.hotels.forEach(h => cache.set(h.property_code, h));
          return Array.from(cache.values());
        });
      },

      // ── 3. Final event: priceRange-filtered hotels + final availableFilters ─
      onComplete: (data) => {
        setIsPricingLoading(false);
        if (data.availableFilters) setInternalAvailableFilters(data.availableFilters);
        setHotels(prev => {
          const cache = new Map(prev.map(h => [h.property_code, h]));
          data.hotels.forEach(h => cache.set(h.property_code, h));
          return Array.from(cache.values());
        });
      },

      onError: (data) => {
        setIsLoadingHotels(false);
        setIsPricingLoading(false);
        console.error('[MapExploreModal] SSE error:', data);
      },
    }, controller.signal);
  }, [searchParams, appliedFilters]);

  // Called on every map "idle" event (after pan / zoom settles)
  const handleIdle = useCallback(() => {
    if (!mapRef.current) return;
    const boundJson = mapRef.current.getBounds()?.toJSON();
    if (!boundJson) return;
    const zoom = mapRef.current.getZoom();

    if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
    if (zoom && zoom >= 8) {
      lastBoundsRef.current = { bounds: boundJson, zoom };
      debounceTimerRef.current = setTimeout(() => {
        fetchHotelsByBounds(boundJson, zoom);
      }, 600);
    }
  }, [fetchHotelsByBounds]);

  // Filter change handlers — update internal state, which triggers the re-fetch effect below
  const handleFilterChange = useCallback((filterKey: string, values: MapFilterValue) => {
    setAppliedFilters(prev => ({ ...prev, [filterKey]: values }));
  }, []);

  const handleClearFilters = useCallback(() => {
    setAppliedFilters({});
  }, []);

  // Re-fetch when applied filters change (only after the map has been idle at least once).
  // clearFirst=true so stale hotels are wiped from the map before new results arrive.
  useEffect(() => {
    if (!lastBoundsRef.current) return;
    const { bounds, zoom } = lastBoundsRef.current;
    fetchHotelsByBounds(bounds, zoom, true);
    // fetchHotelsByBounds is recreated whenever appliedFilters changes (it's in its deps),
    // so this effect fires with the correct closure.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [appliedFilters]);

  const handleHotelClick = useCallback(
    (hotel: GeoMarkerHotelWithPricing) => {
      const params = new URLSearchParams(searchParams.toString());
      const latLngParams = hotel.location?.lat && hotel.location?.lng
        ? `&lat=${hotel.location.lat}&lng=${hotel.location.lng}`
        : '';
      const url = `/hotel-details?hotelId=${hotel.amadeus_hotel_id}${latLngParams}&${params.toString()}`;
      window.open(url, '_blank', 'noopener,noreferrer');
    },
    [searchParams]
  );

  const onMapLoad = useCallback((map: google.maps.Map) => {
    mapRef.current = map;
    setMapInstance(map);
    if (initialFocusHotel) {
      map.setCenter({ lat: initialFocusHotel.lat, lng: initialFocusHotel.lng });
      map.setZoom(15);
    }
  }, [initialFocusHotel]);

  useEffect(() => {
    if (!mapInstance || !initialFocusHotel) return;
    mapInstance.setCenter({ lat: initialFocusHotel.lat, lng: initialFocusHotel.lng });
    mapInstance.setZoom(15);
  }, [mapInstance, initialFocusHotel]);

  // Create (or recreate) the clusterer when map is ready, zoom threshold, or color changes
  useEffect(() => {
    if (!mapInstance) return;
    // Preserve any existing markers so they carry over to the new clusterer
    const existingMarkers = Array.from(nativeMarkersRef.current.values());
    clustererRef.current?.clearMarkers();
    clustererRef.current = new MarkerClusterer({
      map: mapInstance,
      markers: existingMarkers,
      algorithm: new SuperClusterAlgorithm({ maxZoom: clusterMaxZoom }),
      renderer: createClusterRenderer(clusterColor),
    });
    return () => {
      clustererRef.current?.clearMarkers();
      clustererRef.current = null;
    };
  }, [mapInstance, clusterMaxZoom, clusterColor]);

  // Additive-only marker sync: once a hotel pin is on the map it stays until the modal closes.
  // We never remove markers just because the viewport moved — they accumulate as the user pans.
  // When pricing arrives via onPricingBatch, existing markers have their icon swapped in-place
  // (via setIcon) so there is no removal/re-addition and therefore no visual flicker.
  useEffect(() => {
    if (!mapInstance || !clustererRef.current) return;

    const existing = nativeMarkersRef.current;

    // Keep the lookup map fresh so marker listeners always read current pricing
    hotels.forEach(h => hotelsMapRef.current.set(h.property_code, h));

    const toAdd: google.maps.Marker[] = [];
    for (const hotel of hotels) {
      const priceLabel = formatPriceLabel(hotel);

      if (existing.has(hotel.property_code)) {
        // Marker already on the map — upgrade icon to price tag if pricing just arrived
        if (priceLabel && !markerHasPricingRef.current.has(hotel.property_code)) {
          existing.get(hotel.property_code)!.setIcon(buildPriceTagIcon(priceLabel));
          markerHasPricingRef.current.add(hotel.property_code);
        }
        continue;
      }

      // New hotel — create marker with the best icon available right now
      const marker = new google.maps.Marker({
        position: hotel.location,
        icon: buildMarkerIcon(hotel),
      });

      if (priceLabel) markerHasPricingRef.current.add(hotel.property_code);

      marker.addListener('mouseover', (e: google.maps.MapMouseEvent) => {
        if (hoverLeaveTimerRef.current) clearTimeout(hoverLeaveTimerRef.current);
        const dom = e.domEvent as MouseEvent;
        if (dom && 'clientX' in dom) {
          const CARD_W = 240, CARD_H = 300, MARKER_PX = 40;
          const vw = window.innerWidth;
          const showBelow = dom.clientY < CARD_H + MARKER_PX;
          const vert = showBelow ? `6px` : `calc(-100% - ${MARKER_PX}px)`;
          const tooCloseLeft = dom.clientX < CARD_W / 2 + 16;
          const tooCloseRight = dom.clientX > vw - CARD_W / 2 - 16;
          const horiz = tooCloseLeft ? '-8px' : tooCloseRight ? 'calc(-100% + 8px)' : '-50%';
          setCardTransform(`translate(${horiz}, ${vert})`);
        }
        // Look up the latest hotel object so the hover card shows current pricing
        setHoveredHotel(hotelsMapRef.current.get(hotel.property_code) ?? hotel);
      });

      marker.addListener('mouseout', () => {
        hoverLeaveTimerRef.current = setTimeout(() => setHoveredHotel(null), 150);
      });

      marker.addListener('click', () => handleHotelClick(hotel));

      existing.set(hotel.property_code, marker);
      toAdd.push(marker);
    }

    if (toAdd.length) {
      clustererRef.current.addMarkers(toAdd, true);
      clustererRef.current.render();
    }
  }, [hotels, mapInstance, handleHotelClick]);

  // Clear hotels + abort the SSE stream when modal closes
  useEffect(() => {
    if (!isOpen) {
      setHotels([]);
      setIsLoadingHotels(false);
      setIsPricingLoading(false);
      setInternalAvailableFilters(undefined);
      lastBoundsRef.current = null;
      setHoveredHotel(null);
      setCardTransform('translate(-50%, calc(-100% - 40px))');
      setShowMobileFilters(false);
      if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
      if (hoverLeaveTimerRef.current) clearTimeout(hoverLeaveTimerRef.current);
      sseAbortRef.current?.abort();
      // Clear all native markers + clusterer
      if (clustererRef.current) {
        clustererRef.current.clearMarkers();
      }
      nativeMarkersRef.current.forEach((m) => {
        google.maps.event.clearInstanceListeners(m);
        m.setMap(null);
      });
      nativeMarkersRef.current.clear();
      markerHasPricingRef.current.clear();
      hotelsMapRef.current.clear();
    }
  }, [isOpen]);

  // Cleanup on unmount
  useEffect(() => {
    const debounce = debounceTimerRef;
    const hoverLeave = hoverLeaveTimerRef;
    const sse = sseAbortRef;
    const clusterer = clustererRef;
    const nativeMarkers = nativeMarkersRef;
    return () => {
      if (debounce.current) clearTimeout(debounce.current);
      if (hoverLeave.current) clearTimeout(hoverLeave.current);
      sse.current?.abort();
      clusterer.current?.clearMarkers();
      nativeMarkers.current.forEach((m) => {
        google.maps.event.clearInstanceListeners(m);
        m.setMap(null);
      });
      nativeMarkers.current.clear();
    };
  }, []);

  // Prevent body scroll when modal is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => {
      document.body.style.overflow = '';
    };
  }, [isOpen]);

  if (!isOpen) return null;

  return (
    <div
      style={{
        position: 'fixed',
        inset: 0,
        zIndex: 9999,
      }}
    >
      <div style={{
        position: 'fixed',
        inset: 0,
        zIndex: 9999,
        display: 'flex',
      }}>
        {/* ── Left: filter panel — hidden on mobile, visible as sidebar on desktop ── */}
        <div className="d-none d-lg-flex" style={{ height: '100%' }}>
          <MapExploreFilterPanel
            availableFilters={internalAvailableFilters}
            appliedFilters={appliedFilters}
            onFilterChange={handleFilterChange}
            onClearFilters={handleClearFilters}
            isLoadingHotels={isLoadingHotels}
          />
        </div>

        {/* ── Right: map + all overlays ── */}
        <div style={{ flex: 1, position: 'relative', overflow: 'hidden' }}>
          {/* Map */}
          {!isLoaded ? (
            <div
              style={{
                width: '100%',
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                background: '#f8f9fa',
              }}
            >
              <div className="spinner-border text-primary" role="status">
                <span className="visually-hidden">Loading map…</span>
              </div>
            </div>
          ) : (
            <GoogleMap
              mapContainerStyle={MAP_CONTAINER_STYLE}
              zoom={13}
              center={effectiveCenter}
              options={MAP_OPTIONS}
              onLoad={onMapLoad}
              onIdle={handleIdle}
            >
              {/* ── Pins rendered imperatively via MarkerClusterer – no JSX markers needed ── */}
              {hoveredHotel && (
                <OverlayView
                  position={hoveredHotel.location}
                  mapPaneName={OverlayView.OVERLAY_MOUSE_TARGET}
                >
                  <div
                    style={{
                      transform: cardTransform,
                      display: 'inline-flex',
                      flexDirection: 'column',
                      alignItems: 'center',
                    }}
                    onMouseEnter={() => {
                      if (hoverLeaveTimerRef.current) clearTimeout(hoverLeaveTimerRef.current);
                    }}
                    onMouseLeave={() => {
                      hoverLeaveTimerRef.current = setTimeout(() => setHoveredHotel(null), 150);
                    }}
                  >
                    <HotelHoverCard hotel={hoveredHotel} pricing={hoveredHotel.pricing ?? undefined} onClick={() => handleHotelClick(hoveredHotel)} />
                  </div>
                </OverlayView>
              )}
            </GoogleMap>
          )}

          {/* ── Top-left overlay: title + loading/count ── */}
          <div
            style={{
              position: 'absolute',
              top: 12,
              left: 12,
              display: 'flex',
              alignItems: 'center',
              gap: 6,
              pointerEvents: 'none',
              flexWrap: 'wrap',
              maxWidth: 'calc(100% - 130px)',
            }}
          >
            {/* "Explore on Map" chip */}
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 5,
                background: '#fff',
                borderRadius: 4,
                padding: '6px 8px',
                boxShadow: '0 1px 4px rgba(0,0,0,0.28)',
                fontWeight: 700,
                fontSize: 13,
                color: '#1a1a2e',
                whiteSpace: 'nowrap',
              }}
              className="d-none d-sm-flex"
            >
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ flexShrink: 0 }}>
                <path
                  d="M8.00004 7.66667C7.55801 7.66667 7.13409 7.49107 6.82153 7.17851C6.50897 6.86595 6.33337 6.44203 6.33337 6C6.33337 5.55797 6.50897 5.13405 6.82153 4.82149C7.13409 4.50893 7.55801 4.33333 8.00004 4.33333C8.44207 4.33333 8.86599 4.50893 9.17855 4.82149C9.49111 5.13405 9.66671 5.55797 9.66671 6C9.66671 6.21887 9.6236 6.4356 9.53984 6.6378C9.45608 6.84001 9.33332 7.02375 9.17855 7.17851C9.02379 7.33327 8.84006 7.45604 8.63785 7.5398C8.43564 7.62356 8.21891 7.66667 8.00004 7.66667ZM8.00004 1.33333C6.76236 1.33333 5.57538 1.825 4.70021 2.70017C3.82504 3.57534 3.33337 4.76232 3.33337 6C3.33337 9.5 8.00004 14.6667 8.00004 14.6667C8.00004 14.6667 12.6667 9.5 12.6667 6C12.6667 4.76232 12.175 3.57534 11.2999 2.70017C10.4247 1.825 9.23772 1.33333 8.00004 1.33333Z"
                  fill="#003580"
                />
              </svg>
              Explore on Map
            </div>

            {/* Loading indicator chip — hotels phase */}
            {isLoadingHotels && (
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 5,
                  background: '#fff',
                  borderRadius: 4,
                  padding: '6px 8px',
                  boxShadow: '0 1px 4px rgba(0,0,0,0.28)',
                  fontSize: 12,
                  color: '#555',
                  whiteSpace: 'nowrap',
                }}
              >
                <span
                  className="spinner-border spinner-border-sm"
                  role="status"
                  style={{ width: 13, height: 13, borderWidth: 2, flexShrink: 0 }}
                />
                <span>Loading hotels…</span>
              </div>
            )}

            {/* Pricing loading chip — Amadeus batches still streaming */}
            {!isLoadingHotels && isPricingLoading && (
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 5,
                  background: '#fff',
                  borderRadius: 4,
                  padding: '6px 8px',
                  boxShadow: '0 1px 4px rgba(0,0,0,0.28)',
                  fontSize: 12,
                  color: '#555',
                  whiteSpace: 'nowrap',
                }}
              >
                <span
                  className="spinner-border spinner-border-sm"
                  role="status"
                  style={{ width: 13, height: 13, borderWidth: 2, flexShrink: 0 }}
                />
                <span>Loading prices…</span>
              </div>
            )}

            {/* Hotel count chip — shows count from the latest viewport query */}
            {!isLoadingHotels && hotels.length > 0 && (
              <div
                style={{
                  background: '#fff',
                  borderRadius: 4,
                  padding: '6px 8px',
                  boxShadow: '0 1px 4px rgba(0,0,0,0.28)',
                  fontSize: 12,
                  color: '#555',
                  whiteSpace: 'nowrap',
                }}
              >
                <strong>{hotels.length}</strong>
                <span> hotel{hotels.length !== 1 ? 's' : ''} in this area</span>
              </div>
            )}
          </div>

          {/* ── Top-right overlay: Close map button ── */}
          <button
            type="button"
            onClick={onClose}
            aria-label="Close map"
            style={{
              position: 'absolute',
              top: 12,
              right: 12,
              display: 'flex',
              alignItems: 'center',
              gap: 6,
              background: '#2f6271',
              border: 'none',
              borderRadius: 4,
              padding: '8px 10px',
              boxShadow: '0 1px 4px rgba(0,0,0,0.28)',
              cursor: 'pointer',
              fontWeight: 600,
              fontSize: 15,
              color: '#fff',
              whiteSpace: 'nowrap',
            }}
          >
            <span className="d-none d-sm-inline" style={{ paddingLeft: 6, color: "#fff" }}>Close map</span>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M18 6L6 18M6 6l12 12" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" />
            </svg>
          </button>

          {/* ── Mobile filter button — bottom-left, visible only on small screens ── */}
          {(() => {
            const appliedFiltersCount = Object.values(appliedFilters).reduce<number>((count, value) => {
              if (!value) return count;
              if (Array.isArray(value)) return count + value.length;
              return count + 1;
            }, 0);
            return (
              <button
                type="button"
                className="d-lg-none shadow"
                onClick={() => setShowMobileFilters(true)}
                aria-label="Open map filters"
                style={{
                  position: 'absolute',
                  bottom: 72,
                  left: 0,
                  zIndex: 100,
                  display: 'inline-flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  gap: 3,
                  background: '#2f6271',
                  color: '#fff',
                  border: 'none',
                  borderRadius: '0 8px 8px 0',
                  padding: '10px 12px',
                  fontWeight: 600,
                  fontSize: 12,
                  cursor: 'pointer',
                  lineHeight: 1.3,
                }}
              >
                <svg className="d-block mx-auto" fill="#fff" height="15" viewBox="0 0 512 512" width="15" xmlns="http://www.w3.org/2000/svg">
                  <path d="m16 90.259h243.605c7.342 33.419 37.186 58.508 72.778 58.508s65.436-25.088 72.778-58.508h90.839c8.836 0 16-7.164 16-16s-7.164-16-16-16h-90.847c-7.356-33.402-37.241-58.507-72.77-58.507-35.548 0-65.419 25.101-72.772 58.507h-243.611c-8.836 0-16 7.164-16 16s7.164 16 16 16zm273.877-15.958c0-.057.001-.115.001-.172.07-23.367 19.137-42.376 42.505-42.376 23.335 0 42.403 18.983 42.504 42.339l.003.235c-.037 23.407-19.091 42.441-42.507 42.441-23.406 0-42.454-19.015-42.507-42.408zm206.123 347.439h-90.847c-7.357-33.401-37.241-58.507-72.77-58.507-35.548 0-65.419 25.102-72.772 58.507h-243.611c-8.836 0-16 7.163-16 16s7.164 16 16 16h243.605c7.342 33.419 37.186 58.508 72.778 58.508s65.436-25.089 72.778-58.508h90.839c8.836 0 16-7.163 16-16s-7.164-16-16-16zm-163.617 58.508c-23.406 0-42.454-19.015-42.507-42.408l.001-.058c0-.058.001-.115.001-.172.07-23.367 19.137-42.377 42.505-42.377 23.335 0 42.403 18.983 42.504 42.338l.003.235c-.034 23.41-19.089 42.442-42.507 42.442zm163.617-240.248h-243.605c-7.342-33.419-37.186-58.507-72.778-58.507s-65.436 25.088-72.778 58.507h-90.839c-8.836 0-16 7.164-16 16 0 8.837 7.164 16 16 16h90.847c7.357 33.401 37.241 58.507 72.77 58.507 35.548 0 65.419-25.102 72.772-58.507h243.611c8.836 0 16-7.163 16-16 0-8.836-7.164-16-16-16zm-273.877 15.958c0 .058-.001.115-.001.172-.07 23.367-19.137 42.376-42.505 42.376-23.335 0-42.403-18.983-42.504-42.338l-.003-.234c.035-23.41 19.09-42.441 42.507-42.441 23.406 0 42.454 19.014 42.507 42.408z" />
                </svg>
                Filter
                {appliedFiltersCount > 0 && (
                  <span
                    style={{
                      background: '#fff',
                      color: '#2f6271',
                      borderRadius: 10,
                      padding: '1px 5px',
                      fontSize: 10,
                      fontWeight: 700,
                      minWidth: 16,
                      textAlign: 'center',
                    }}
                  >
                    {appliedFiltersCount}
                  </span>
                )}
              </button>
            );
          })()}
        </div>

        {/* ── Mobile filter overlay — full-screen panel, visible only on small screens ── */}
        {showMobileFilters && (
          <div
            className="d-lg-none"
            style={{
              position: 'fixed',
              inset: 0,
              zIndex: 10001,
              display: 'flex',
              flexDirection: 'column',
              background: '#fff',
              overflow: 'hidden',
            }}
          >
            <div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden' }}>
              <MapExploreFilterPanel
                availableFilters={internalAvailableFilters}
                appliedFilters={appliedFilters}
                onFilterChange={handleFilterChange}
                onClearFilters={handleClearFilters}
                isLoadingHotels={isLoadingHotels}
                onClose={() => setShowMobileFilters(false)}
                fullWidth
              />
            </div>
            <div
              style={{
                padding: '12px 16px',
                borderTop: '1px solid #e9ecef',
                background: '#fff',
                flexShrink: 0,
              }}
            >
              <button
                type="button"
                onClick={() => setShowMobileFilters(false)}
                style={{
                  width: '100%',
                  background: '#f45d6b',
                  color: '#fff',
                  border: 'none',
                  borderRadius: 8,
                  padding: '13px',
                  fontWeight: 700,
                  fontSize: 16,
                  cursor: 'pointer',
                }}
              >
                Apply Filters
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
