'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import { seedFor, useHotelPolicyLimits } from '@/services/employee-requests/hotel-policy';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import dynamic from 'next/dynamic';
import DynamicFilterSidebarV3 from '@/components/search/v3/DynamicFilterSidebarV3';
import SearchHeader from '@/components/search/SearchHeader';
import HotelsList from '@/components/search/HotelsList';
import HotelsListSkeleton from '@/components/search/HotelsListSkeleton';
import { PriceRangeFilter } from '../filters/PricingPerNightFilter';
import { searchHotelsClient, searchHotelsNextPage, applyFiltersAndSort } from '@/services/search/search.client';
import { parseChildrenAges } from '@/utils/sanitize';
import { parseDateOnlyAsLocal } from '@/utils/date';
import type { SearchHotelsRequest } from '@/services/search/types';
import { mapSearchResponseToHotels } from '@/services/search/mapper';
import { lookupWishlistItemsBatch } from '@/services/wishlist/wishlist.service';
import { useAppSelector } from '@/store/hooks';
import { Hotel, SortOption, ViewMode } from '@/features/search/types';
import { AvailableFilters } from '@/services/search/types';
import { trackMetaPixelEvent } from '@/lib/meta-pixel';
import { sendFunnelEvent } from '@/utils/tracking';
import { SrpMapProvider, type SrpMapFocusHotel } from '@/context/SrpMapContext';

const MapExploreModal = dynamic(
  () => import('@/components/search/MapExploreModal'),
  { ssr: false }
);

const DynamicMobileFilterModal = dynamic(
  () => import('@/components/search/DynamicMobileFilterModal'),
  { ssr: false }
);

type WishlistBatchLookupResult = {
  exists: boolean;
  wishlist?: { id: string; name: string };
  item?: { id: number | string; wishlistId: string };
};


type DynamicFilterValue = string[] | PriceRangeFilter | boolean | undefined;
type DynamicFiltersState = Record<string, DynamicFilterValue>;
type FilterPayloadState = Record<string, string[] | PriceRangeFilter | boolean>;

const isPastParamDate = (value: string | null) => {
  if (!value) return true;
  const d = parseDateOnlyAsLocal(value) ?? new Date(value);
  if (Number.isNaN(d.getTime())) return true;
  const todayStart = new Date();
  todayStart.setHours(0, 0, 0, 0);
  const dateStart = new Date(d);
  dateStart.setHours(0, 0, 0, 0);
  return dateStart < todayStart;
};

// Helper function to map SortOption to API sort format
const getSortParams = (sortOption: SortOption) => {
  switch (sortOption) {
    case 'price-low':
      return { field: 'price', order: 'asc' as const };
    case 'price-high':
      return { field: 'price', order: 'desc' as const };
    case 'rating':
      return { field: 'rating', order: 'desc' as const };
    case 'best-value':
      return { field: 'best-value', order: 'asc' as const };
    case 'popularity':
      return { field: 'popularity', order: 'desc' as const };
    case 'default':
      return { field: 'default', order: null };
    default:
      return { field: 'default', order: null };
  }
};

export default function HotelsSearchClientV3() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const pathname = usePathname();
  const user = useAppSelector((state) => state.auth.user);
  const isAuthenticated = !!user;
  const [viewMode, setViewMode] = useState<ViewMode>('list');
  const [sortBy, setSortBy] = useState<SortOption>('default');
  const [hotels, setHotels] = useState<Hotel[]>([]);
  const [totalResults, setTotalResults] = useState(0);
  const [totalFilteredResults, setTotalFilteredResults] = useState<number | undefined>();
  const [isLoading, setIsLoading] = useState(true);
  const [priceId, setPriceId] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [hasMore, setHasMore] = useState(false);
  const [wishlistLookupByHotelId, setWishlistLookupByHotelId] = useState<
    Record<string, { wishlistItemId: number | null; wishlistName?: string }>
  >({});

  const [availableFilters, setAvailableFilters] = useState<AvailableFilters | undefined>(undefined);
  const [dynamicFilters, setDynamicFilters] = useState<DynamicFiltersState>({});

  /* ── the group's default search filters (LEIS-999) ────────────────────────
   * PRD §8.5: an admin's "Default filters" are PRE-APPLIED to hotel search and
   * the traveller can remove them. They never flag anything — they only change
   * what the search returns.
   *
   * Seeded ONCE, and the latch is what makes that true. A `useEffect` keyed on
   * the filter object would re-apply a filter the traveller had just removed
   * the moment anything else re-rendered, which is the difference between a
   * default and a setting they cannot escape. The latch is keyed on traveller
   * and tab, so switching who you are booking for, or crossing into the other
   * tab, seeds again — but only if the traveller has not touched the filters
   * themselves by then.
   *
   * Runs after the first search, because applying filters needs the `priceId`
   * that search returns.
   * ---------------------------------------------------------------------- */
  const bookingFor = searchParams.get('bookingFor');
  const policyLimits = useHotelPolicyLimits({
    travelerId: bookingFor,
    countryCode: hotels[0]?.address?.country_code ?? null,
  });
  const seededFor = useRef<string | null>(null);
  const filtersTouched = useRef(false);

  useEffect(() => {
    if (!priceId || !policyLimits) return;
    const key = `${bookingFor ?? 'self'}:${policyLimits.scope}`;
    if (seededFor.current === key || filtersTouched.current) return;
    seededFor.current = key;

    const seed = seedFor(policyLimits);
    if (!seed || seed.filters.length === 0) return;

    const next: DynamicFiltersState = { ...dynamicFilters };
    for (const filter of seed.filters) {
      switch (filter) {
        case 'FREE_CANCELLATION':
          next.freeCancellation = true;
          break;
        case 'BREAKFAST':
          next.breakfast = true;
          break;
        case 'HOTELS_ONLY':
          next.hotelsOnly = true;
          break;
        case 'STAR_RATING': {
          // Every rating AT OR BELOW the group's Maximum eligibility cap, so
          // search shows only in-policy classes. Seeded from the same number
          // the evaluator judges against (`starCap`), never re-derived.
          if (seed.starCap && seed.starCap > 0) {
            // Strings, like every other checkbox filter on this page — the
            // sidebar's own values are strings and the payload type says so.
            // search-service compares them against a numeric `star_rating`,
            // which its OpenSearch pushdown coerces and its in-memory filter
            // now coerces too.
            next.starRating = Array.from({ length: seed.starCap }, (_, i) => String(i + 1));
          }
          break;
        }
        case 'HOTEL_CHAIN': {
          // The admin's PREFERRED chains — deliberately not the flagged ones,
          // which mean the opposite.
          if (seed.preferredChains.length > 0) {
            next.chains = seed.preferredChains.map((chain) => chain.code);
          }
          break;
        }
      }
    }

    setDynamicFilters(next);
    applyFiltersAndSortToAPI(next, sortBy);
    // `dynamicFilters` is read, not depended on: including it would re-run this
    // on every filter change, and the latch already makes it single-shot.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [priceId, policyLimits, bookingFor, sortBy]);

  const [showMobileFilters, setShowMobileFilters] = useState(false);
  const [mapCenter, setMapCenter] = useState<{ lat: number; lng: number } | undefined>(undefined);
  const [showMapModal, setShowMapModal] = useState(false);
  const [mapFocusHotel, setMapFocusHotel] = useState<SrpMapFocusHotel | null>(null);

  const openMapForHotel = useCallback((hotel: SrpMapFocusHotel) => {
    setMapFocusHotel(hotel);
    setMapCenter({ lat: hotel.lat, lng: hotel.lng });
    setShowMapModal(true);
  }, []);

  // Push a history entry when the map modal opens so the browser back button
  // closes the modal instead of navigating to the previous page.
  useEffect(() => {
    if (showMapModal) {
      window.history.pushState({ mapModal: true }, '');
    }

    const handlePopState = (e: PopStateEvent) => {
      if (showMapModal) {
        e.preventDefault();
        setShowMapModal(false);
        setMapFocusHotel(null);
      }
    };

    window.addEventListener('popstate', handlePopState);
    return () => window.removeEventListener('popstate', handlePopState);
  }, [showMapModal]);

  const abortControllerRef = useRef<AbortController | null>(null);
  const lastSearchKeyRef = useRef<string>('');
  const isFetchingRef = useRef(false);
  const filterAbortControllerRef = useRef<AbortController | null>(null);
  const filterDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const trackedSearchKeysRef = useRef<Set<string>>(new Set());

  // Create stable search params string for dependency
  const locationParam = searchParams.get('city_id') || searchParams.get('destination_id') || searchParams.get('country_id') || searchParams.get('property_code') || '';
  const searchParamsString = [
    locationParam,
    searchParams.get('checkinDate') || '',
    searchParams.get('checkoutDate') || '',
    searchParams.get('rooms') || '1',
    searchParams.get('adults') || '2',
    searchParams.get('type') || 'city',
    searchParams.get('location_type') || ''
  ].join('|');

  // Initial data fetch - reacts to search params changes
  useEffect(() => {
    if (!locationParam) {
      return;
    }

    const searchKey = `Search:${searchParamsString}`;
    if (trackedSearchKeysRef.current.has(searchKey)) {
      return;
    }

    trackedSearchKeysRef.current.add(searchKey);
    trackMetaPixelEvent('Search', {
      search_string:
        searchParams.get('destination') ||
        searchParams.get('search') ||
        searchParams.get('property_code') ||
        searchParams.get('city_id') ||
        searchParams.get('destination_id') ||
        searchParams.get('country_id') ||
        '',
    });
  }, [locationParam, searchParams, searchParamsString]);

  useEffect(() => {
    // Skip if required location param is missing
    if (!locationParam) {
      setIsLoading(false);
      return;
    }

    const checkinParam = searchParams.get('checkinDate');
    const checkoutParam = searchParams.get('checkoutDate');

    if (!checkinParam || !checkoutParam) {
      setIsLoading(false);
      return;
    }

    // Treat past/invalid dates the same as missing dates
    if (isPastParamDate(checkinParam) || isPastParamDate(checkoutParam)) {
      setIsLoading(false);
      return;
    }

    // Prevent duplicate calls - only fetch if search params actually changed
    if (lastSearchKeyRef.current === searchParamsString && isFetchingRef.current) {
      console.log('[HotelsSearchClient] Skipping duplicate request:', {
        searchKey: searchParamsString,
        timestamp: new Date().toISOString()
      });
      return;
    }

    // Cancel any in-flight request
    if (abortControllerRef.current) {
      console.log('[HotelsSearchClient] Aborting previous request:', {
        previousKey: lastSearchKeyRef.current,
        newKey: searchParamsString,
        timestamp: new Date().toISOString()
      });
      abortControllerRef.current.abort();
    }

    // Mark as fetching and update search key
    lastSearchKeyRef.current = searchParamsString;
    isFetchingRef.current = true;

    const fetchInitialHotels = async () => {
      const requestStartTime = Date.now();
      console.log('[HotelsSearchClient] Starting fetchInitialHotels:', {
        searchKey: searchParamsString,
        timestamp: new Date().toISOString()
      });

      // Reset state before new search
      setIsLoading(true);
      setPriceId('');
      setTotalResults(0);
      setTotalFilteredResults(undefined);
      setCurrentPage(1);
      setHotels([]);
      setWishlistLookupByHotelId({});
      setDynamicFilters({});
      setAvailableFilters(undefined);
      noProgressSinceRef.current = null;


      // Create new AbortController for this request
      abortControllerRef.current = new AbortController();
      const currentAbortController = abortControllerRef.current;

      try {
        // Build search payload based on type and location_type (for city)
        const searchType = searchParams.get('type') || 'city';
        const locationType = searchParams.get('location_type') || 'city';
        const basePayload = {
          checkinDate: searchParams.get('checkinDate') || '',
          checkoutDate: searchParams.get('checkoutDate') || '',
          rooms: searchParams.get('rooms') ? Number(searchParams.get('rooms')) : 1,
          adults: searchParams.get('adults') ? Number(searchParams.get('adults')) : 2,
          children: parseChildrenAges(searchParams.get('children')),
          pricePerNightFrom: searchParams.get('pricePerNightFrom')
            ? Number(searchParams.get('pricePerNightFrom'))
            : undefined,
          pricePerNightTo: searchParams.get('pricePerNightTo')
            ? Number(searchParams.get('pricePerNightTo'))
            : undefined,
        };

        if (searchParams.get('pricePerNightTo') || searchParams.get('pricePerNightFrom')) {
          setDynamicFilters({
            priceRange: {
              from: Number(searchParams.get('pricePerNightFrom')) || 0,
              to: Number(searchParams.get('pricePerNightTo')) || 10000,
            }
          });

          const nextParams = new URLSearchParams(searchParams.toString());
          nextParams.delete('pricePerNightFrom');
          nextParams.delete('pricePerNightTo');
          const nextQuery = nextParams.toString();
          router.replace(nextQuery ? `${pathname}?${nextQuery}` : pathname, { scroll: false });
        } 
      
        // Add location param: property_code, or city_id / destination_id / country_id by location_type
        let searchPayload: SearchHotelsRequest;
        if (searchType === 'property') {
          searchPayload = { ...basePayload, property_code: searchParams.get('property_code') || '' };
        } else if (locationType === 'destination') {
          searchPayload = { ...basePayload, destination_id: searchParams.get('destination_id') || '' };
        } else if (locationType === 'country') {
          searchPayload = { ...basePayload, country_id: searchParams.get('country_id') || '' };
        } else {
          searchPayload = { ...basePayload, city_id: searchParams.get('city_id') || '' };
        }

        // Pass abort signal to the API call
        const response = await searchHotelsClient(searchPayload, currentAbortController.signal);

        // Check if request was aborted
        if (currentAbortController.signal.aborted) {
          const duration = Date.now() - requestStartTime;
          console.log('[HotelsSearchClient] Request was aborted after response:', {
            duration: `${duration}ms`,
            timestamp: new Date().toISOString()
          });
          return;
        }

        const duration = Date.now() - requestStartTime;
        if (response && response.success !== false) {
          console.log('[HotelsSearchClient] Request successful:', {
            duration: `${duration}ms`,
            hotelsCount: response.totalSearched,
            timestamp: new Date().toISOString()
          });
          const fetchedHotels = mapSearchResponseToHotels(response);
          console.log('fetchedHotels in HotelsSearchClient---', fetchedHotels);
          setHotels(fetchedHotels);
          setPriceId(response.priceId);
          setTotalResults(response.totalSearched);
          setHasMore(response.hasMore);

         await sendFunnelEvent('SRP_LISTINGS_VIEWED', {
            metadata: {
              path: pathname,
              search: searchParams.toString(),
              totalListings: response.totalSearched,
              visibleListings: fetchedHotels.length || 0,
            },
          });

          // Store available filters from API response
          if (response.availableFilters) {
            setAvailableFilters(response.availableFilters);
            console.log('[HotelsSearchClient] Available filters:', response.availableFilters);
          }

          // Extract map center from the first property that has coordinates
          const firstWithCoords = response.properties?.find(
            (p) => p.address?.latitude && p.address?.longitude
          );
          if (firstWithCoords?.address) {
            setMapCenter({
              lat: firstWithCoords.address.latitude,
              lng: firstWithCoords.address.longitude,
            });
          }
        }
      } catch (error: unknown) {
        const duration = Date.now() - requestStartTime;
        // Ignore abort errors
        const isAbortError = error instanceof Error &&
          (error.name === 'AbortError' || error.name === 'CanceledError');

        if (isAbortError || currentAbortController.signal.aborted) {
          console.log('[HotelsSearchClient] Request was aborted (in catch):', {
            duration: `${duration}ms`,
            errorName: error instanceof Error ? error.name : 'unknown',
            timestamp: new Date().toISOString()
          });
          return;
        }
        console.error('[HotelsSearchClient] Error fetching initial hotels:', {
          duration: `${duration}ms`,
          error: error instanceof Error ? error.message : String(error),
          timestamp: new Date().toISOString()
        });
      } finally {
        // Only update loading state if this is still the current request
        if (!currentAbortController.signal.aborted) {
          setIsLoading(false);
          isFetchingRef.current = false;
        }
      }
    };

    fetchInitialHotels();

    // Cleanup: abort request if component unmounts or params change
    return () => {
      if (abortControllerRef.current) {
        console.log('[HotelsSearchClient] Cleanup: aborting request:', {
          searchKey: searchParamsString,
          timestamp: new Date().toISOString()
        });
        abortControllerRef.current.abort();
      }
      isFetchingRef.current = false;
    };
  }, [searchParamsString]); // eslint-disable-line react-hooks/exhaustive-deps

  // SRP batch wishlist lookup: only for newly loaded hotels
  useEffect(() => {
    if (!isAuthenticated) return;
    if (!hotels.length) return;

    const propertyCodes = hotels.map((h) => String(h.id));
    const unknown = propertyCodes.filter((code) => wishlistLookupByHotelId[code] === undefined);
    if (!unknown.length) return;

    const checkinDate = searchParams.get('checkinDate') || '';
    const checkoutDate = searchParams.get('checkoutDate') || '';

    (async () => {
      try {
        const resp = await lookupWishlistItemsBatch({
          property_codes: unknown,
          ...(checkinDate ? { checkinDate } : {}),
          ...(checkoutDate ? { checkoutDate } : {}),
        });

        const results =
          (resp as { data?: { results?: Record<string, WishlistBatchLookupResult> } })?.data?.results ??
          (resp as unknown as { results?: Record<string, WishlistBatchLookupResult> })?.results;
        if (!results || typeof results !== 'object') return;

        setWishlistLookupByHotelId((prev) => {
          const next = { ...prev };
          for (const code of unknown) {
            const r = results[code];
            const exists = r?.exists === true;
            const rawId = r?.item?.id;
            const idNum = typeof rawId === 'string' ? Number(rawId) : rawId;
            next[code] = {
              wishlistItemId: exists && typeof idNum === 'number' && Number.isFinite(idNum) ? idNum : null,
              wishlistName: r?.wishlist?.name,
            };
          }
          return next;
        });
      } catch {
        // fail open: keep buttons functional (they can still add/remove on click)
      }
    })();
  }, [isAuthenticated, hotels, searchParams, wishlistLookupByHotelId]);

  // Shared function to apply filters and sorting
  const applyFiltersAndSortToAPI = (
    filters: DynamicFiltersState,
    sort: SortOption
  ) => {
    // Only apply filters if we have a priceId (initial search completed)
    if (!priceId) {
      console.log('[HotelsSearchClient] No priceId yet, skipping filter/sort API call');
      return;
    }

    // Clear any pending debounced call
    if (filterDebounceRef.current) {
      clearTimeout(filterDebounceRef.current);
    }

    // Cancel any in-flight filter/sort request
    if (filterAbortControllerRef.current) {
      filterAbortControllerRef.current.abort();
    }

    filterDebounceRef.current = setTimeout(async () => {
    const currentFilterAbortController = new AbortController();
    filterAbortControllerRef.current = currentFilterAbortController;

    setIsLoading(true);
    setHotels([]);

    try {
      const sortParams = getSortParams(sort);
      const payloadFilters: FilterPayloadState = Object.entries(filters).reduce((acc, [key, value]) => {
        if (value !== undefined) {
          acc[key] = value;
        }
        return acc;
      }, {} as FilterPayloadState);

      const searchType = searchParams.get('type') || 'city';
      const locationType = searchParams.get('location_type') || 'city';
      const basePayload = {
        checkinDate: searchParams.get('checkinDate') || '',
        checkoutDate: searchParams.get('checkoutDate') || '',
        rooms: searchParams.get('rooms') ? Number(searchParams.get('rooms')) : 1,
        adults: searchParams.get('adults') ? Number(searchParams.get('adults')) : 2,
        children: parseChildrenAges(searchParams.get('children')),
        pricePerNightFrom: searchParams.get('pricePerNightFrom')
          ? Number(searchParams.get('pricePerNightFrom'))
          : undefined,
        pricePerNightTo: searchParams.get('pricePerNightTo')
          ? Number(searchParams.get('pricePerNightTo'))
          : undefined,
      };

      // Add location param: property_code, or city_id / destination_id / country_id by location_type
      let searchPayload: SearchHotelsRequest;
      if (searchType === 'property') {
        searchPayload = { ...basePayload, property_code: searchParams.get('property_code') || '' };
      } else if (locationType === 'destination') {
        searchPayload = { ...basePayload, destination_id: searchParams.get('destination_id') || '' };
      } else if (locationType === 'country') {
        searchPayload = { ...basePayload, country_id: searchParams.get('country_id') || '' };
      } else {
        searchPayload = { ...basePayload, city_id: searchParams.get('city_id') || '' };
      }


      const payload = {
        filters: Object.keys(payloadFilters)?.length ? payloadFilters : undefined,
        sort: sortParams,
        ...searchPayload
      };

      const response = await applyFiltersAndSort(priceId, payload, {
        page: 1,
        limit: 10,
      }, currentFilterAbortController.signal);

      if (currentFilterAbortController.signal.aborted) return;

      if (response && response.success !== false) {
        const fetchedHotels = mapSearchResponseToHotels(response);
        setHotels(fetchedHotels);
        setPriceId(response.priceId);
        setTotalResults(response.totalSearched);
        setTotalFilteredResults(response.totalFiltered);
        setHasMore(response.hasMore);
        if (response.availableFilters) setAvailableFilters(response.availableFilters);
        setCurrentPage(1);
      }
    } catch (error: unknown) {
      if (currentFilterAbortController.signal.aborted) return;
      console.error('[HotelsSearchClient] Error applying filters:', error);
      const status = (error as { response?: { status?: number } })?.response?.status;
      if (status === 404) {
        setHasMore(false);
      }
    } finally {
      if (!currentFilterAbortController.signal.aborted) {
        setIsLoading(false);
      }
    }
    }, 300);
  };

  const handleSearch = (query: string) => {
    console.log('Search query:', query);
    // TODO: Implement search functionality
  };

  // Wall-clock, not an attempt count: `searchHotelsNextPage` itself already
  // retries an empty/processing page up to 5 times internally (waiting the
  // server's own `retryAfter` between tries — see search.client.ts), so one
  // "empty" result back here can already represent ~10s of real waiting.
  // Background pricing for a big city (1000+ properties) can legitimately
  // take longer than that to reach the next page, so giving up on a short
  // attempt count cuts off a search that was still genuinely working — it
  // only needs to stop the OTHER case: a search that will NEVER produce
  // another hotel (e.g. every property failing supplier pricing forever),
  // which looks identical from here except that no amount of waiting helps.
  // A dead end is only a dead end once it has had real time to prove it.
  const noProgressSinceRef = useRef<number | null>(null);
  // 4 minutes, up from 90s: on an Amadeus account with thin inventory most of a
  // city's properties answer "no rooms", so the stretches with no new priced hotel
  // are long (London: 1,264 properties, ~3 minutes end to end, with 2+ minutes
  // stuck between the first and third batches). 90s gave up in the middle of that
  // and left the list at the first handful of hotels.
  const MAX_NO_PROGRESS_MS = 240_000;

  const handleLoadMore = async () => {
    if (isLoading || !hasMore) return;
    setIsLoading(true);
    try {
      const response = await searchHotelsNextPage(priceId, {
        page: currentPage + 1,
        offset: hotels.length,
        limit: 20,
      });
      const newHotels = mapSearchResponseToHotels(response);
      // Don't skip ahead when background/buffer returned an empty page
      if (newHotels.length === 0) {
        const stillGoing = Boolean(response.hasMore || (response as { processing?: boolean }).processing);
        if (!stillGoing) {
          noProgressSinceRef.current = null;
          setHasMore(false);
          return;
        }
        if (noProgressSinceRef.current === null) {
          noProgressSinceRef.current = Date.now();
        } else if (Date.now() - noProgressSinceRef.current >= MAX_NO_PROGRESS_MS) {
          // The IntersectionObserver re-arms on every `hasMore` change (see
          // HotelsList.tsx) and the sentinel never left the viewport because
          // the page never grew — trusting the backend's "still working"
          // forever is what turns that into an unbounded request loop. This
          // is the actual circuit breaker; the time budget above is what
          // keeps it from tripping on a search that was merely slow.
          noProgressSinceRef.current = null;
          setHasMore(false);
          return;
        }
        setHasMore(true);
        return;
      }
      noProgressSinceRef.current = null;
      setHotels([...hotels, ...newHotels]);
      setCurrentPage(currentPage + 1);
      setPriceId(response.priceId); // Update priceId if it changes
      setHasMore(response.hasMore);
    } catch (error: unknown) {
      console.error('Error loading more hotels:', error);
      const status = (error as { response?: { status?: number } })?.response?.status;
      if (status === 404) {
        setHasMore(false);
      }
    } finally {
      setIsLoading(false);
    }
  };

  const handleSortChange = (sort: SortOption) => {
    setSortBy(sort);
    console.log('Sort by:', sort);
    
    // scroll to top when filters change
    window.scrollTo({ top: 0, behavior: 'smooth' });

    // Call API with new sort and current filters
    applyFiltersAndSortToAPI(dynamicFilters, sort);
  };

  const handleDynamicFilterChange = (filterKey: string, values: DynamicFilterValue) => {
    // From here on the filters are the traveller's, not the policy's: a
    // default they removed must never be seeded back.
    filtersTouched.current = true;
    const updatedFilters = { ...dynamicFilters };

    if (values === undefined || (Array.isArray(values) && values.length === 0)) {
      delete updatedFilters[filterKey];
    } else {
      updatedFilters[filterKey] = values;
    }

    setDynamicFilters(updatedFilters);
    console.log(`Dynamic filter [${filterKey}] updated:`, values);

    // scroll to top when filters change
    window.scrollTo({ top: 0, behavior: 'smooth' });
    
    // Call API with updated filters and current sort
    applyFiltersAndSortToAPI(updatedFilters, sortBy);
  };

  const handleClearDynamicFilters = () => {
    filtersTouched.current = true;
    setDynamicFilters({});
    console.log('Cleared all dynamic filters');

    // scroll to top when filters change
    window.scrollTo({ top: 0, behavior: 'smooth' });

    // Call API with empty filters and current sort
    applyFiltersAndSortToAPI({}, sortBy);
  };
  return (
    <SrpMapProvider openMapForHotel={openMapForHotel}>
      {/* Use DynamicFilterSidebarV3 if available filters exist, otherwise use static FilterSidebar */}
      <DynamicFilterSidebarV3
        availableFilters={availableFilters}
        appliedFilters={dynamicFilters}
        onFilterChange={handleDynamicFilterChange}
        onSearch={handleSearch}
        onClearFilters={handleClearDynamicFilters}
        onExploreMap={() => {
          setMapFocusHotel(null);
          setShowMapModal(true);
        }}
        mapCenter={mapCenter}
        isLoading={isLoading}
        isMapLoading={isLoading && hotels.length === 0}
      />

      {/* <FilterSidebar
        filters={filters}
        appliedFilters={appliedFilters}
        onFilterChange={handleFilterChange}
        onSearch={handleSearch}
        onRemoveFilter={handleRemoveFilter}
        onClearFilters={handleClearFilters}
      /> */}

      {/* Main Content */}
      <div className="col-xxl-9 col-xl-9 col-lg-9 col-md-12 col-12 listing-details mb-3 mb-lg-0">
        {/* Search Header */}
        <SearchHeader
          totalResults={(totalFilteredResults !== undefined && totalFilteredResults >= 0) ? totalFilteredResults : totalResults}
          viewMode={viewMode}
          sortBy={sortBy}
          onViewModeChange={setViewMode}
          onSortChange={handleSortChange}
          destination={searchParams.get('destination') || ''}
          isLoading={isLoading && hotels.length === 0}
        />

        {/* Hotels List */}
        {isLoading && hotels.length === 0 ? (
          <HotelsListSkeleton viewMode={viewMode} count={6} />
        ) : (
          <HotelsList
            hotels={hotels}
            viewMode={viewMode}
            onLoadMore={handleLoadMore}
            hasMore={hasMore}
            isLoading={isLoading}
            wishlistLookupByHotelId={isAuthenticated ? wishlistLookupByHotelId : undefined}
            disableWishlistAutoLookup={isAuthenticated}
          />
        )}
      </div>

      {/* Mobile Filter Button */}
      <button onClick={() => setShowMobileFilters(true)} className="w-fit-content buttons btnColor-first bgColor-first-same rounded-end-0 color-text-white-same shadow filterMobButton d-lg-none d-inline-block">
        <svg className="d-block mx-auto mb-1" fill="#fff" enableBackground="new 0 0 512 512" 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"></path>
        </svg>
        Filter
      </button>

      {/* Mobile Filter Modal - Dynamic */}
      <DynamicMobileFilterModal
        isOpen={showMobileFilters}
        onClose={() => setShowMobileFilters(false)}
        availableFilters={availableFilters}
        appliedFilters={dynamicFilters}
        sortBy={sortBy}
        onFilterChange={handleDynamicFilterChange}
        onSortChange={handleSortChange}
        onClearFilters={handleClearDynamicFilters}
      />

      {/* Old Mobile Filter Modal - Static (Commented for reference) */}
      {/* <MobileFilterModal
        isOpen={showMobileFilters}
        onClose={() => setShowMobileFilters(false)}
        filters={filters}
        sortBy={sortBy}
        onFilterChange={handleFilterChange}
        onSortChange={handleSortChange}
      /> */}

      {/* Map Explore Modal — mount only when open so Google Maps is not loaded on initial SRP paint */}
      {showMapModal && (
        <MapExploreModal
          isOpen={showMapModal}
          onClose={() => {
            setShowMapModal(false);
            setMapFocusHotel(null);
          }}
          mapCenter={mapFocusHotel ? { lat: mapFocusHotel.lat, lng: mapFocusHotel.lng } : mapCenter}
          initialFocusHotel={mapFocusHotel}
        />
      )}
    </SrpMapProvider>
  );
}
