'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { useSearchParams, useRouter, usePathname } from 'next/navigation';
import Image from 'next/image';
import DatePicker from '@/components/ui/DatePicker';
import { useRecentSearches } from '@/hooks/useRecentSearches';
import { useCitiesSearch } from '@/hooks/useCitiesSearch';
import { SearchClientService } from '@/services/search';
import { useAppSelector } from '@/store/hooks';
import { parseChildrenAges } from '@/utils/sanitize';
import { formatDateToYYYYMMDD, parseDateOnlyAsLocal } from '@/utils/date';
import { VALIDATION_RULES } from '@/constants/booking';
import type { City, RecentSearch } from '@/types/city';
import type { LocationData } from '../LocationSearchInput';
import locationIcon from '@/public/images/icons/location.png';
import hotelIcon from '@/public/images/icons/hotel.png';
import {
  ClearIcon,
  MinusIcon,
  PlusIcon,
  SearchIcon,
} from '@/components/home/v3/icons';
import { PRODUCT_LINKS } from '@/constants/product-links';
import { BookingForField } from '@/components/booking-for/BookingForField';
import { parseBookingFor, withBookingFor } from '@/services/employee-requests/booking-for';
import { ISO_COUNTRIES, ISO_COUNTRY_CODES } from '@/constants/iso-countries';
// `.fs-field`/`.fs-dropdown`/`.fs-trigger` — BookingForField's own positioning
// contract, owned by flights (CORP-ONLY). Reused rather than duplicated: the
// ticket asks for "same control and placement as the Flights tab already
// has", and these are scoped to the `.fs-*` prefix, so importing this
// alongside this form's own Bootstrap classes does not collide with them.
import '../../flights/v3/flight-search-v3.css';

interface HotelSearchData {
  location: LocationData;
  rooms: number;
  adults: number;
  children: number;
  childrenAges?: number[];
}

export interface HotelSearchFormV3Props {
  /**
   * Render the form alone, for a page that already has its own hero and tabs.
   *
   * Also stops the URL-sync effect below from rewriting the host page's
   * address — see its own comment. `FlightSearchFormV3` draws the same line
   * with `isResultsPage`; this is the hotel half of it.
   */
  embedded?: boolean;
}

export default function HotelSearchFormV3({ embedded = false }: HotelSearchFormV3Props = {}) {
  const searchParams = useSearchParams();
  const router = useRouter();
  const pathname = usePathname();
  const [isSearching, setIsSearching] = useState(false);

  const token = useAppSelector((state) => state.auth.token);
  const isAuthenticated = !!token;

  const { addRecentSearch, refetch, recentSearches, clearRecentSearches } = useRecentSearches();
  const { searchTerm, setSearchTerm, cities } = useCitiesSearch({ debounceMs: 600, minChars: 2, limit: 10 });

  // ── Destination UI state ──────────────────────────────────────────────────
  const [destEditing, setDestEditing] = useState(false);
  const [destOpen, setDestOpen] = useState(false);
  const destInputRef = useRef<HTMLInputElement>(null);

  // ── Traveller panel UI state ──────────────────────────────────────────────
  const [travOpen, setTravOpen] = useState(false);
  const [localChildren, setLocalChildren] = useState(0);
  const [localChildrenAges, setLocalChildrenAges] = useState<number[]>([]);

  // ── Date state ────────────────────────────────────────────────────────────
  const isPastDate = (d: Date) => {
    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);
    const dateStart = new Date(d);
    dateStart.setHours(0, 0, 0, 0);
    return dateStart < todayStart;
  };

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

  const getTodayStart = (): Date => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    return today;
  };

  const getDefaultCheckOutDate = (checkIn: Date): Date => {
    const checkOut = new Date(checkIn);
    checkOut.setDate(checkOut.getDate() + 2);
    return checkOut;
  };

  const formatDateForParam = (date: Date) => formatDateToYYYYMMDD(date);

  const getInitialCheckInDate = () =>
    parseValidParamDate(searchParams.get('checkinDate')) || getTodayStart();

  const getInitialCheckOutDate = () => {
    const checkIn = getInitialCheckInDate();
    const validCheckOut = parseValidParamDate(searchParams.get('checkoutDate'));
    if (!validCheckOut) return getDefaultCheckOutDate(checkIn);
    if (validCheckOut <= checkIn) return getDefaultCheckOutDate(checkIn);
    return validCheckOut;
  };

  const [checkInDate, setCheckInDate] = useState<Date | null>(getInitialCheckInDate());
  const [checkOutDate, setCheckOutDate] = useState<Date | null>(getInitialCheckOutDate());
  const [isCheckInOpen, setIsCheckInOpen] = useState(false);
  const [isCheckOutOpen, setIsCheckOutOpen] = useState(false);

  const getInitialFormData = (): HotelSearchData => {
    const type = searchParams.get('type') || 'city';
    const locationType = searchParams.get('location_type') || 'city';
    const code =
      type === 'property'
        ? searchParams.get('property_code') || ''
        : searchParams.get('city_id') ||
          searchParams.get('destination_id') ||
          searchParams.get('country_id') ||
          (type === 'city' ? '48710' : '');
    return {
      location: {
        destination: searchParams.get('destination') || 'London',
        code,
        type,
        country: searchParams.get('country') || '',
        location_type: type === 'city' ? locationType : undefined,
      },
      rooms: searchParams.get('rooms') ? Number(searchParams.get('rooms')) : 1,
      adults: searchParams.get('adults') ? Number(searchParams.get('adults')) : 2,
      children: parseChildrenAges(searchParams.get('children')).length,
      childrenAges: parseChildrenAges(searchParams.get('children')),
    };
  };

  const [formData, setFormData] = useState<HotelSearchData>(getInitialFormData());

  // ── Booking for (LEIS-1042, CORP-ONLY) ──────────────────────────────────
  const [bookingForOpen, setBookingForOpen] = useState(false);
  const bookingFor = parseBookingFor(searchParams);
  const setBookingFor = useCallback(
    (travellerId: string | null) => {
      // "Only one guest can be selected; stays fixed at 1 room · 1 guest" —
      // a colleague request is for THEM, not a party booked alongside them,
      // so picking one collapses the party size rather than leaving a room
      // count chosen for a different trip silently attached to this one.
      // Switching back to Myself does not restore it — the employee is
      // already in the panel if they want more than one room again.
      if (travellerId !== null) {
        setFormData((prev) => ({ ...prev, rooms: 1, adults: 1, children: 0, childrenAges: [] }));
        setLocalChildren(0);
        setLocalChildrenAges([]);
      }
      const qs = withBookingFor(searchParams.toString(), travellerId);
      router.replace(`${pathname}${qs ? `?${qs}` : ''}`, { scroll: false });
    },
    [searchParams, pathname, router],
  );

  useEffect(() => {
    const next = getInitialFormData();
    setFormData(next);
    setLocalChildren(next.children);
    setLocalChildrenAges(next.childrenAges ?? []);
    setCheckInDate(getInitialCheckInDate());
    setCheckOutDate(getInitialCheckOutDate());
    setIsCheckInOpen(false);
    setIsCheckOutOpen(false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchParams]);

  // Keep the URL in sync with defaults so SRP can fetch reliably — both the
  // dates (already handled here) and the location identifier.
  //
  // Without the location half of this, a URL that never had a
  // city_id/destination_id/country_id/property_code (a bare `/srp/hotels`,
  // one missing just that param, a stale link) stayed that way forever: this
  // form's own `getInitialFormData()` already falls back to a sensible
  // default (London, city_id 48710) and shows it in the destination field,
  // but that was only ever REACT STATE — nothing wrote it back into the URL,
  // so HotelsSearchClientV3's fetch effect (gated on `!locationParam`
  // returning early) never ran at all. Confirmed live: the Network tab shows
  // no search request whatsoever for such a URL, not a request that returns
  // zero results — this is why, and the fix.
  useEffect(() => {
    const checkinParam = searchParams.get('checkinDate');
    const checkoutParam = searchParams.get('checkoutDate');
    const parsedCheckIn = parseValidParamDate(checkinParam);
    const parsedCheckOut = parseValidParamDate(checkoutParam);
    const resolvedCheckIn = parsedCheckIn || getTodayStart();
    const resolvedCheckOut =
      parsedCheckOut && parsedCheckOut > resolvedCheckIn
        ? parsedCheckOut
        : getDefaultCheckOutDate(resolvedCheckIn);
    const formattedCheckIn = formatDateForParam(resolvedCheckIn);
    const formattedCheckOut = formatDateForParam(resolvedCheckOut);
    const datesNeedSync = checkinParam !== formattedCheckIn || checkoutParam !== formattedCheckOut;

    const hasLocation =
      !!searchParams.get('city_id') ||
      !!searchParams.get('destination_id') ||
      !!searchParams.get('country_id') ||
      !!searchParams.get('property_code');
    const location = formData.location;
    const locationNeedsSync = !hasLocation && !!location.code;

    // Embedded on another page (the home hero), this effect has nothing to fix
    // and no right to act: its entire purpose is to make HotelsSearchClientV3's
    // fetch effect fire on /srp/hotels, and there is no such client here. Left
    // ungated it would `router.replace` the HOST page's URL — stamping
    // `city_id`, `checkinDate` and the rest onto `/` or `/admin` on first
    // paint, which is both wrong and visible in the address bar.
    if (embedded) return;

    if (!datesNeedSync && !locationNeedsSync) return;

    const params = new URLSearchParams(searchParams.toString());
    params.set('checkinDate', formattedCheckIn);
    params.set('checkoutDate', formattedCheckOut);

    if (locationNeedsSync) {
      params.set('type', location.type || 'city');
      if (location.type === 'property') {
        params.set('property_code', location.code);
      } else {
        const locType = location.location_type || 'city';
        params.set('location_type', locType);
        if (locType === 'destination') params.set('destination_id', location.code);
        else if (locType === 'country') params.set('country_id', location.code);
        else params.set('city_id', location.code);
      }
      if (location.destination) params.set('destination', location.destination);
      if (location.country) params.set('country', location.country);
    }

    router.replace(`${pathname}?${params.toString()}`, { scroll: false });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchParams, router, pathname, formData.location, embedded]);

  // Close panels on outside click (mirrors HeroSectionV3)
  useEffect(() => {
    const onDocClick = (e: MouseEvent) => {
      const target = e.target as Element;
      if (!target.closest('.destination-field-wrapper')) {
        setDestEditing(false);
        setDestOpen(false);
      }
      if (!target.closest('.guestPanel')) setTravOpen(false);
      // `.fs-field` is Booking For's own contract, carried over from flights
      // (see its CSS import above) — not this form's `.guestPanel`/
      // `.destination-field-wrapper` idiom.
      if (!target.closest('.fs-field')) setBookingForOpen(false);
    };
    document.addEventListener('click', onDocClick);
    return () => document.removeEventListener('click', onDocClick);
  }, []);

  /**
   * The destination's country, as Booking For's hotel-mode scope needs it.
   *
   * `formData.location.country` is a free-text NAME from the cities-search
   * API ("United Kingdom"), not the ISO-2 code `resolveHotelScope` (and
   * Amadeus) require — matched against the same canonical list the traveler
   * passport fields use. An unresolved or not-yet-chosen destination
   * returns "", which still selects hotel mode server-side (countryCode is
   * SENT, just unresolved) rather than silently falling back to flight mode.
   */
  function isoCodeForCountryName(name: string): string {
    const raw = name.trim();
    if (!raw) return '';
    const upper = raw.toUpperCase();
    if (upper.length === 2 && ISO_COUNTRY_CODES.has(upper)) return upper;
    const match = ISO_COUNTRIES.find((c) => c.name.toLowerCase() === raw.toLowerCase());
    return match ? match.code : '';
  }

  const bookingForCountryCode = isoCodeForCountryName(formData.location.country || '');

  // ── Destination handlers ──────────────────────────────────────────────────
  const startDestEdit = () => {
    setDestEditing(true);
    setDestOpen(true);
    requestAnimationFrame(() => destInputRef.current?.focus());
  };

  const clearDest = (e: React.MouseEvent) => {
    e.stopPropagation();
    setSearchTerm('');
    destInputRef.current?.focus();
  };

  const selectCity = (city: City) => {
    const name = city.name || city.destination_name || city.city_name || '';
    const code = city.code || city.property_code || (city.city_id != null ? String(city.city_id) : '');
    if (!name || !code) return;
    setFormData((prev) => ({
      ...prev,
      location: {
        destination: name,
        code,
        type: city.type || 'city',
        country: city.country || city.country_name || '',
        destination_name: city.destination_name || city.name || undefined,
        country_name: city.country_name || city.country || undefined,
        location_type: city.location_type ?? (city.type === 'city' ? 'city' : undefined),
        city_id: city.city_id != null ? String(city.city_id) : undefined,
      },
    }));
    setSearchTerm('');
    setDestEditing(false);
    setDestOpen(false);
    setIsCheckInOpen(true);
  };

  const selectRecent = (r: RecentSearch) => {
    const code = r.code || r.iataCode || '';
    if (!r.cityName || !code) return;
    setFormData((prev) => ({
      ...prev,
      location: {
        destination: r.cityName,
        code,
        type: r.type || 'city',
        country: r.country || '',
        location_type: (r.type || 'city') === 'city' ? 'city' : undefined,
      },
    }));
    setSearchTerm('');
    setDestEditing(false);
    setDestOpen(false);
    setIsCheckInOpen(true);
  };

  // ── Traveller handlers ────────────────────────────────────────────────────
  const { rooms, adults, children } = formData;

  const openTravellers = () => {
    setLocalChildren(formData.children);
    setLocalChildrenAges(formData.childrenAges ?? []);
    setTravOpen(true);
  };

  const toggleTravellers = () => (travOpen ? setTravOpen(false) : openTravellers());

  const stepRooms = (delta: number) => (e: React.MouseEvent) => {
    e.stopPropagation();
    const next = Math.min(VALIDATION_RULES.maxRooms, Math.max(VALIDATION_RULES.minRooms, rooms + delta));
    const maxChildren = next * 2;
    const nextLocalChildren = Math.min(maxChildren, localChildren);
    setLocalChildren(nextLocalChildren);
    setLocalChildrenAges(localChildrenAges.slice(0, nextLocalChildren));
    setFormData((prev) => ({ ...prev, rooms: next, adults: Math.max(adults, next) }));
  };

  const stepAdult = (delta: number) => (e: React.MouseEvent) => {
    e.stopPropagation();
    const next = Math.min(VALIDATION_RULES.maxAdults, Math.max(rooms, adults + delta));
    setFormData((prev) => ({ ...prev, adults: next }));
  };

  const stepChild = (delta: number) => (e: React.MouseEvent) => {
    e.stopPropagation();
    const maxChildren = rooms * 2;
    const next = Math.max(0, Math.min(maxChildren, localChildren + delta));
    let nextAges = [...localChildrenAges];
    if (next > localChildren) {
      nextAges = [...localChildrenAges, ...Array(next - localChildren).fill(-1)];
    } else if (next < localChildren) {
      nextAges = localChildrenAges.slice(0, next);
    }
    setLocalChildren(next);
    setLocalChildrenAges(nextAges);
  };

  const setChildAge = (index: number, age: number) => {
    const ages = [...localChildrenAges];
    ages[index] = age;
    setLocalChildrenAges(ages);
  };

  const applyTravellers = (e: React.MouseEvent) => {
    e.stopPropagation();
    setFormData((prev) => ({ ...prev, children: localChildren, childrenAges: localChildrenAges }));
    setTravOpen(false);
  };

  const localTravellersValid = localChildrenAges.every((age) => age >= 0);

  // ── Date handlers ─────────────────────────────────────────────────────────
  const handleCheckInChange = useCallback((date: Date | null) => {
    setCheckInDate(date);
    if (date) {
      const tomorrow = new Date(date);
      tomorrow.setDate(tomorrow.getDate() + 2);
      setCheckOutDate(tomorrow);
      setTimeout(() => {
        setIsCheckInOpen(false);
        setIsCheckOutOpen(true);
      }, 0);
    }
  }, []);

  const handleCheckOutChange = useCallback((date: Date | null) => {
    setCheckOutDate(date);
    if (date) {
      setTimeout(() => {
        setIsCheckOutOpen(false);
        openTravellers();
      }, 0);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [formData]);

  // ── Submit ────────────────────────────────────────────────────────────────
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!checkInDate || !checkOutDate) {
      if (!checkInDate) {
        setIsCheckOutOpen(false);
        setIsCheckInOpen(true);
      } else {
        setIsCheckInOpen(false);
        setIsCheckOutOpen(true);
      }
      return;
    }

    // Defence in depth alongside the URL-backfill effect above: nothing in
    // this file currently sets `formData.location.code` to empty once
    // `getInitialFormData()` has run, but a search with no destination at
    // all would otherwise silently reach search-service as an empty
    // city_id/destination_id/country_id and come back with zero results
    // instead of being stopped here, before the request — same reasoning as
    // the date check just above.
    if (!formData.location.code) {
      startDestEdit();
      return;
    }

    setIsSearching(true);
    try {
      const checkinDate = formatDateForParam(checkInDate);
      const checkoutDate = formatDateForParam(checkOutDate);

      if (formData.location.destination && formData.location.code) {
        addRecentSearch({
          cityName: formData.location.destination,
          code: formData.location.code,
          iataCode: formData.location.code,
          country: formData.location.country || '',
          type: formData.location.type || 'city',
        });
        if (isAuthenticated) {
          try {
            await SearchClientService.saveRecentSearch({
              searchType: formData.location.type || 'city',
              searchTerm: formData.location.destination,
              resultCount: 1,
              result: {
                id:
                  formData.location?.type === 'property'
                    ? formData.location.city_id!
                    : formData.location.code,
                name: formData.location.destination,
                code: formData.location.code,
              },
            });
            refetch();
          } catch (error) {
            console.error('Failed to save recent search to API:', error);
          }
        }
      }

      const params = new URLSearchParams(searchParams.toString());
      [
        'hotelId', 'lat', 'lng', 'type', 'location_type', 'city_id',
        'destination_id', 'country_id', 'property_code', 'destination',
        'country', 'checkinDate', 'checkoutDate', 'rooms', 'adults', 'children',
      ].forEach((key) => params.delete(key));

      if (formData.location.type) params.set('type', formData.location.type);

      if (formData.location.type === 'city' && formData.location.code) {
        const locType = formData.location.location_type || 'city';
        params.set('location_type', locType);
        if (locType === 'destination') {
          params.set('destination_id', formData.location.code);
        } else if (locType === 'country') {
          params.set('country_id', formData.location.code);
        } else {
          params.set('city_id', formData.location.code);
        }
        params.set('destination', formData.location.destination);
      }

      if (formData.location.type === 'property' && formData.location.code) {
        params.set('property_code', formData.location.code);
        params.set('destination', formData.location.destination);
      }

      if (formData.location.country) params.set('country', formData.location.country);

      params.set('checkinDate', checkinDate);
      params.set('checkoutDate', checkoutDate);
      params.set('rooms', String(formData.rooms));
      params.set('adults', String(formData.adults));
      if (formData.childrenAges && formData.childrenAges.length > 0) {
        params.set('children', JSON.stringify(formData.childrenAges));
      }

      router.push(`/srp/hotels?${params.toString()}`, { scroll: false });
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch (error) {
      console.error('Error searching hotels:', error);
    } finally {
      setIsSearching(false);
    }
  };

  // ── Derived display values ────────────────────────────────────────────────
  const totalTravellers = adults + children;
  const destDisplay = formData.location.destination || '';
  const isTyping = searchTerm.trim().length >= 2;

  /**
   * The form on its own, without the hero band around it.
   *
   * The home page (LEIS-1015) puts Hotels and Flights in one card under its
   * own hero, so the banner, overlay, shape and product tabs below would be a
   * second hero inside the first. Everything that actually searches is in
   * here; the chrome is only in the `/srp/hotels` branch.
   */
  const hotelForm = (
        <div className="search-form-wrap text-start px-2">
          <div className="search-tab-panel" data-panel="hotels">
            <form onSubmit={handleSubmit} className="booking-validation" noValidate>
              <div className="row align-items-center g-0">

                {/* ── Destination ──────────────────────────────────────────── */}
                <div className="col-lg-3 col-md-6 col-12 search-field-col py-0">
                  <div className="destination-field-wrapper position-relative h-56">

                    {/* Static display */}
                    <div
                      className={`collapse-fields destination-static cursor-pointer${destEditing ? ' d-none' : ''}`}
                      data-id="collapseHotelDestination"
                      onClick={startDestEdit}
                    >
                      <label className="search-field-label text-lg color-text-black fw-500 mb-1">
                        Search places or activities
                      </label>
                      <div className="search-field-value text-muted text-md color-text-content" id="dest-display-value">
                        {destDisplay}
                      </div>
                    </div>

                    {/* Input */}
                    <div className={`destination-input-wrap${destEditing ? '' : ' d-none'} h-100`}>
                      <div className="position-relative h-100">
                        <input
                          ref={destInputRef}
                          type="text"
                          value={searchTerm}
                          onChange={(e) => setSearchTerm(e.target.value)}
                          className="form-control search-destination-field h-100 pe-4 shadow-none border border-first rounded-3"
                          placeholder="Where ?"
                          id="main-dest-input"
                        />
                        <span className="clear-dest position-absolute top-50 translate-middle-y end-0 cursor-pointer me-2" onClick={clearDest}>
                          <ClearIcon />
                        </span>
                      </div>
                    </div>

                    {/* Dropdown */}
                    <div
                      className="submenu-web bgColor-white rounded-3 shadow-sm mt-2"
                      id="div_collapseHotelDestination"
                      style={{ display: destOpen ? 'block' : 'none', position: 'absolute', zIndex: 1000, width: '100%', minWidth: 280 }}
                    >
                      <div className="card border-0 rounded-2">
                        <div className="card-body p-3 text-start">

                          {/* Search results */}
                          {isTyping && (
                            <div className="search-results-list mb-3">
                              <small className="text-xs color-text-black fw-500 d-block mb-2">Search results</small>
                              {cities.length === 0 ? (
                                <p className="mb-0 fw-500 text-sm color-text-content px-2 py-1">No results found</p>
                              ) : (
                                cities.map((city) => (
                                  <div
                                    key={`${city.type}-${city.code}-${city.id}`}
                                    className="d-flex align-items-center p-2 rounded-2 hover-bg-light cursor-pointer location-item-new"
                                    onClick={() => selectCity(city)}
                                  >
                                    <div className="me-3 rounded p-1">
                                      {city.type === 'property' ? (
                                        <Image src={hotelIcon} height={20} width={20} alt="hotel" style={{ opacity: 0.6 }} />
                                      ) : city.location_type === 'destination' ? (
                                        <svg width={20} height={20} viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ opacity: 0.6 }}>
                                          <path d="M2 6a2 2 0 012-2h12a2 2 0 012 2v8a2 2 0 01-2 2H4a2 2 0 01-2-2V6z" stroke="#B6B6B6" strokeWidth="1.5" fill="none" />
                                          <path d="M2 8h16M7 2v4M13 2v4" stroke="#B6B6B6" strokeWidth="1.2" strokeLinecap="round" />
                                        </svg>
                                      ) : city.location_type === 'country' ? (
                                        <svg width={20} height={20} viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ opacity: 0.6 }}>
                                          <circle cx="10" cy="10" r="7.5" stroke="#B6B6B6" strokeWidth="1.5" fill="none" />
                                          <path d="M2 10h16M10 2.5a12.2 12.2 0 013 4.5 12.2 12.2 0 01-3 4.5 12.2 12.2 0 01-3-4.5 12.2 12.2 0 013-4.5z" stroke="#B6B6B6" strokeWidth="1.2" strokeLinecap="round" />
                                        </svg>
                                      ) : (
                                        <Image src={locationIcon} height={20} width={20} alt="location" style={{ opacity: 0.6 }} />
                                      )}
                                    </div>
                                    <div className="d-flex flex-column">
                                      {(city.country || city.country_name) && (
                                        <small className="color-text-content fw-500 text-xs">{city.country || city.country_name}</small>
                                      )}
                                      <p className="mb-0 fw-500 text-sm loc-name color-text-black">{city.name}</p>
                                    </div>
                                  </div>
                                ))
                              )}
                            </div>
                          )}

                          {/* Recent searches */}
                          {!isTyping && recentSearches.length > 0 && (
                            <div className="recent-searches mb-3">
                              <div className="d-flex align-items-center justify-content-between mb-2">
                                <small className="text-xs color-text-black fw-500 d-block">Recent searches</small>
                                <button
                                  type="button"
                                  className="btn btn-link p-0 text-xs fw-500 text-decoration-none clear-recent-btn"
                                  onClick={(e) => { e.stopPropagation(); clearRecentSearches(); }}
                                >
                                  Clear
                                </button>
                              </div>
                              {recentSearches.map((r, idx) => (
                                <div
                                  key={`${r.code || r.iataCode}-${idx}`}
                                  className="d-flex align-items-center p-2 rounded-2 hover-bg-light cursor-pointer location-item-new"
                                  onClick={() => selectRecent(r)}
                                >
                                  <div className="me-3 rounded p-1">
                                    {r.type === 'property' ? (
                                      <Image src={hotelIcon} height={20} width={20} alt="hotel" style={{ opacity: 0.6 }} />
                                    ) : (
                                      <Image src={locationIcon} height={20} width={20} alt="location" style={{ opacity: 0.6 }} />
                                    )}
                                  </div>
                                  <div className="d-flex flex-column">
                                    <p className="mb-0 fw-500 text-sm loc-name color-text-black">{r.cityName}</p>
                                    {r.country && <small className="color-text-content fw-500 text-xs">{r.cityName} · {r.country}</small>}
                                  </div>
                                </div>
                              ))}
                            </div>
                          )}

                          {/* Empty state */}
                          {!isTyping && recentSearches.length === 0 && (
                            <div className="px-2 py-3 text-center">
                              <small className="color-text-content fw-500 text-xs d-block">
                                Start typing to search for cities or properties
                              </small>
                            </div>
                          )}

                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                {/* ── Check In ─────────────────────────────────────────────── */}
                <div className="col-lg-2 col-md-3 col-6 search-field-col py-0">
                  <div className="collapse-fields cursor-pointer h-56" data-id="collapseHotelCheckInDates">
                    <div className="position-relative h-100 justify-content-center gap-1">
                      <label className="search-field-label text-lg color-text-black fw-500 mb-1">Check In</label>
                      <div onClick={() => { setIsCheckOutOpen(false); setIsCheckInOpen(true); }}>
                        <DatePicker
                          id="v3-search-check-in"
                          selected={checkInDate}
                          onChange={handleCheckInChange}
                          placeholderText="Add Dates"
                          minDate={new Date()}
                          className="form-control color-text-content p-0 h-auto text-md search-field-input startDate"
                          open={isCheckInOpen}
                          onClickOutside={() => setIsCheckInOpen(false)}
                          onCalendarClose={() => setIsCheckInOpen(false)}
                          dateFormat="EEE, dd MMM"
                        />
                      </div>
                    </div>
                  </div>
                </div>

                {/* ── Check Out ────────────────────────────────────────────── */}
                <div className="col-lg-2 col-md-3 col-6 search-field-col py-0">
                  <div className="collapse-fields cursor-pointer h-56" data-id="collapseHotelCheckOutDates">
                    <div className="position-relative h-100 justify-content-center gap-1">
                      <label className="search-field-label text-lg color-text-black fw-500 mb-1">Check Out</label>
                      <div onClick={() => { setIsCheckInOpen(false); setIsCheckOutOpen(true); }}>
                        <DatePicker
                          id="v3-search-check-out"
                          key={checkInDate?.toISOString()}
                          selected={checkOutDate}
                          onChange={handleCheckOutChange}
                          placeholderText="Add Dates"
                          minDate={
                            checkInDate
                              ? (() => { const d = new Date(checkInDate); d.setDate(d.getDate() + 1); return d; })()
                              : new Date()
                          }
                          className="form-control color-text-content p-0 h-auto text-md search-field-input endDate"
                          open={isCheckOutOpen}
                          onClickOutside={() => setIsCheckOutOpen(false)}
                          onCalendarClose={() => setIsCheckOutOpen(false)}
                          dateFormat="EEE, dd MMM"
                        />
                      </div>
                    </div>
                  </div>
                </div>

                {/* ── Traveller panel ──────────────────────────────────────────
                    LEIS-1046: was col-lg-3. "2 Traveler / 2 adults, 0 Children"
                    never filled a quarter of the row, so the right half of this
                    column read as a hole punched between the travellers and
                    Booking For. The two columns swapped widths — the three units
                    go to Booking For below, which was the cramped one. */}
                <div className="col-lg-2 col-md-6 col-12 search-field-col guestPanel py-0 mt-2 mt-md-0">
                  <div
                    className="collapse-fields cursor-pointer h-56"
                    data-id="collapseHotelTravellerClass"
                    onClick={toggleTravellers}
                  >
                    <div className="d-flex align-items-center mb-1">
                      <input
                        type="text"
                        className="total-travellers border-0 bg-transparent p-0 text-lg color-text-black fw-500"
                        value={totalTravellers}
                        readOnly
                        style={{ width: 12, fontSize: 14, pointerEvents: 'none' }}
                      />
                      <span className="search-field-label ms-1 mb-0 text-lg color-text-black fw-500">Traveler</span>
                    </div>
                    <div className="travel-class-value">
                      <span className="search-field-input text-md color-text-content">
                        {adults} {adults === 1 ? 'adult' : 'adults'},{' '}
                        <span className="totalChildren d-inline-block text-md color-text-content">{children}</span>
                        {children === 1 ? ' Child' : ' Children'}
                      </span>
                    </div>
                  </div>

                  {/* `minWidth` because the column above is narrower since
                      LEIS-1046. The panel's width comes from
                      leisure-new-style.css's `.submenu-web { width: 110% }`,
                      and home-v3.css's `.search-field-col.guestPanel
                      .submenu-web { left: 0 }` beats the 450px min-width that
                      sheet pairs with it — so at col-lg-2 the rooms/adults/
                      children steppers were sizing themselves off a 242px box.
                      It opens rightwards out of the column and still ends well
                      inside the card. */}
                  <div
                    className="submenu-web bgColor-white rounded-3 shadow-sm mt-2"
                    id="div_collapseHotelTravellerClass"
                    style={{
                      display: travOpen ? 'block' : 'none',
                      position: 'absolute',
                      right: 0,
                      minWidth: 360,
                      zIndex: 1000,
                    }}
                  >
                    <div className="card border-0 rounded-2">
                      <div className="card-body p-3">

                        {/* Booking for a colleague fixes the party at 1 room · 1 guest
                            (LEIS-1042) — locked rather than merely defaulted, so there is
                            no state where a multi-room search is attached to a single
                            named traveller. */}
                        {bookingFor !== null && (
                          <p className="mb-3 text-xs color-text-content">
                            Booking for one colleague — fixed at 1 room, 1 adult.
                          </p>
                        )}

                        {/* Rooms */}
                        <div className="row align-items-center mb-3">
                          <div className="col-6">
                            <p className="mb-0 fw-500 text-lg color-text-content">Rooms</p>
                            <small className="text-muted">Max 5</small>
                          </div>
                          <div className="col-6">
                            <div className="qty-container d-flex justify-content-between align-items-center rounded p-1">
                              <button className="qty-btn-minus btn btn-sm btn-white shadow-none border border-light1" type="button" onClick={stepRooms(-1)} disabled={bookingFor !== null}><MinusIcon /></button>
                              <input type="text" value={rooms} readOnly className="input-qty passenger-qty border-0 bg-transparent text-center fw-500" style={{ width: 30 }} />
                              <button className="qty-btn-plus btn btn-sm btn-white shadow-none border border-light1" type="button" onClick={stepRooms(1)} disabled={bookingFor !== null}><PlusIcon /></button>
                            </div>
                          </div>
                        </div>

                        {/* Adults */}
                        <div className="row align-items-center mb-3">
                          <div className="col-6">
                            <p className="mb-0 fw-500 text-lg color-text-content">Adults</p>
                            <small className="text-muted">Age +17</small>
                          </div>
                          <div className="col-6">
                            <div className="qty-container d-flex justify-content-between align-items-center rounded p-1">
                              <button className="qty-btn-minus btn btn-sm btn-white shadow-none border border-light1" type="button" onClick={stepAdult(-1)} disabled={bookingFor !== null}><MinusIcon /></button>
                              <input type="text" value={adults} readOnly className="input-qty passenger-qty border-0 bg-transparent text-center fw-500" style={{ width: 30 }} />
                              <button className="qty-btn-plus btn btn-sm btn-white shadow-none border border-light1" type="button" onClick={stepAdult(1)} disabled={bookingFor !== null}><PlusIcon /></button>
                            </div>
                          </div>
                        </div>

                        {/* Children */}
                        <div className="row align-items-center childSelectRow">
                          <div className="col-6">
                            <p className="mb-0 fw-500 text-lg color-text-content">Children</p>
                            <small className="text-muted">0-17 Years Old</small>
                          </div>
                          <div className="col-6">
                            <div className="qty-container d-flex justify-content-between align-items-center rounded p-1">
                              <button className="qty-btn-minus btn btn-sm btn-white shadow-none border border-light1" type="button" onClick={stepChild(-1)} disabled={bookingFor !== null}><MinusIcon /></button>
                              <input type="text" value={localChildren} readOnly id="child-number" className="input-qty passenger-qty child-qty border-0 bg-transparent text-center fw-500" style={{ width: 30 }} />
                              <button className="qty-btn-plus btn btn-sm btn-white shadow-none border border-light1" type="button" onClick={stepChild(1)} disabled={bookingFor !== null}><PlusIcon /></button>
                            </div>
                          </div>
                        </div>

                        {/* Child ages */}
                        <div className="row mt-3">
                          <div className="col-12">
                            <div className={`child-age-boxes${localChildren > 0 ? ' border-top pt-2' : ''}`}>
                              {localChildren > 0 && (
                                <div className="row g-2">
                                  {localChildrenAges.map((age, i) => (
                                    <div key={i} className="col-md-6 col-12 mb-3 d-flex align-items-center justify-content-between">
                                      <label className="text-md color-text-content fw-500 mb-1">Child {i + 1} Age</label>
                                      <select className="form-select form-select-sm child-age" value={age} onChange={(e) => setChildAge(i, Number(e.target.value))}>
                                        <option value={-1} disabled>Select age</option>
                                        {Array.from({ length: 18 }).map((_, a) => (
                                          <option key={a} value={a}>Age {a}</option>
                                        ))}
                                      </select>
                                    </div>
                                  ))}
                                </div>
                              )}
                            </div>
                          </div>
                        </div>

                        {/* Apply */}
                        <div className="row mt-2">
                          <div className="col-12 border-top pt-3 text-end">
                            <button
                              type="button"
                              className="buttons btnColor-second px-4 py-2 rounded-2"
                              onClick={applyTravellers}
                              disabled={!localTravellersValid}
                            >
                              Apply
                            </button>
                          </div>
                        </div>

                      </div>
                    </div>
                  </div>
                </div>

                {/* ── Booking for (LEIS-1042, CORP-ONLY) ──────────────────────
                    Self-gates on business session — see BookingForField's own
                    doc comment — so a signed-out or Personal-mode visitor sees
                    nothing different here. */}
                <div className="col-lg-3 col-md-6 col-12 search-field-col py-0 mt-2 mt-lg-0">
                  <div
                    className={`fs-field fs-bookingfor-field${bookingForOpen ? ' open' : ''}`}
                    data-dd="bookingfor"
                  >
                    <BookingForField
                      value={bookingFor}
                      onChange={setBookingFor}
                      countryCode={bookingForCountryCode}
                      open={bookingForOpen}
                      onOpenChange={setBookingForOpen}
                    />
                  </div>
                </div>

              </div>

              {/* ── Search Button ─────────────────────────────────────────────
                  Its own centered row below the fields, not a grid column
                  squeezed in beside them — matches FlightSearchFormV3's "full"
                  variant exactly, which is also what freed the field row back
                  down to an even 12 columns once Booking For (LEIS-1042) was
                  added, so it reads as the row's last field rather than
                  picking up a divider meant for a field that still has a
                  neighbour to its right. */}
              <div className="d-flex justify-content-center pt-3 px-2">
                <button
                  type="submit"
                  disabled={isSearching}
                  className="button btn-subscribe h-45 px-4 rounded-2 d-flex align-items-center justify-content-center gap-2 w-sm-100"
                >
                  {isSearching ? (
                    <span className="spinner-border spinner-border-sm" role="status" aria-hidden="true" />
                  ) : (
                    <SearchIcon />
                  )}
                  Search
                </button>
              </div>
            </form>
          </div>
        </div>
  );

  if (embedded) return hotelForm;

  return (
    <section className="hero-banner-section py-5">
      <div className="hero-banner-bg">
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img src="/images/v3/v748-toon-103.jpg" alt="" />
      </div>
      <div className="hero-banner-overlay hero-banner-overlay-light" />
      <div className="search-panel-container text-center text-md-start h-auto mb-0">
        <div className="shape-element">
          <svg className="fill-white" width={406} height={25} viewBox="0 0 406 25" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M0 24C0 10.7452 10.7452 2.77559e-06 24 2.6702e-06L347.101 1.01301e-07C354.84 3.97714e-08 361.844 4.58429 364.94 11.6766C367.958 18.5881 374.696 23.1346 382.235 23.3455L405.132 23.986C405.41 23.9938 405.632 24.2216 405.632 24.5H0V24Z" fill="white" />
          </svg>
        </div>

        {/* Tabs */}
        <div className="hero-tabs d-inline-flex align-items-center gap-2 mb-2 mb-md-0 me-auto me-md-0 ms-auto ms-md-3">
          <button type="button" className="hero-tab active buttons py-1 px-2 bg-transparent text-md d-flex align-items-center gap-2">
            <svg className="iconSize-20" width={199} height={199} viewBox="0 0 199 199" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M182.417 174.125H16.5833V157.542H24.875V33.1667C24.875 30.9676 25.7486 28.8586 27.3036 27.3036C28.8586 25.7486 30.9676 24.875 33.1667 24.875H149.25C151.449 24.875 153.558 25.7486 155.113 27.3036C156.668 28.8586 157.542 30.9676 157.542 33.1667V74.625H174.125V157.542H182.417V174.125ZM140.958 157.542H157.542V91.2083H107.792V157.542H124.375V107.792H140.958V157.542ZM140.958 74.625V41.4583H41.4583V157.542H91.2083V74.625H140.958ZM58.0417 91.2083H74.625V107.792H58.0417V91.2083ZM58.0417 124.375H74.625V140.958H58.0417V124.375ZM58.0417 58.0417H74.625V74.625H58.0417V58.0417Z" fill="white" />
            </svg>
            Hotels
          </button>
          <a href={PRODUCT_LINKS.flights} className="buttons py-1 px-2 bg-transparent text-md d-flex align-items-center gap-2">
            <svg className="iconSize-20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M21 20.25C21 20.4489 20.921 20.6397 20.7803 20.7803C20.6397 20.921 20.4489 21 20.25 21H6.74998C6.55107 21 6.36031 20.921 6.21965 20.7803C6.079 20.6397 5.99998 20.4489 5.99998 20.25C5.99998 20.0511 6.079 19.8603 6.21965 19.7197C6.36031 19.579 6.55107 19.5 6.74998 19.5H20.25C20.4489 19.5 20.6397 19.579 20.7803 19.7197C20.921 19.8603 21 20.0511 21 20.25ZM23.25 12.75V15C23.25 15.1989 23.171 15.3897 23.0303 15.5303C22.8897 15.671 22.6989 15.75 22.5 15.75H5.7253C4.9179 15.7537 4.13114 15.4951 3.48341 15.013C2.83569 14.531 2.36203 13.8516 2.13373 13.0772L0.814672 8.68125C0.747471 8.45737 0.733519 8.22089 0.773931 7.99067C0.814342 7.76044 0.907998 7.54285 1.04743 7.35524C1.18686 7.16764 1.3682 7.01521 1.57699 6.91013C1.78578 6.80505 2.01624 6.75021 2.24998 6.75H2.99998C3.19863 6.75009 3.38913 6.82899 3.52967 6.96938L5.56123 9H7.66967L6.82592 6.47438C6.75073 6.24881 6.73023 6.0086 6.76613 5.77355C6.80202 5.53851 6.89328 5.31537 7.03237 5.12252C7.17146 4.92968 7.3544 4.77267 7.56611 4.66443C7.77781 4.55619 8.01222 4.49983 8.24998 4.5H8.99998C9.09851 4.49992 9.19608 4.51926 9.28712 4.5569C9.37817 4.59454 9.46091 4.64975 9.53061 4.71938L13.8112 9H19.5C20.4945 9 21.4484 9.39509 22.1516 10.0984C22.8549 10.8016 23.25 11.7554 23.25 12.75ZM21.75 12.75C21.75 12.1533 21.5129 11.581 21.091 11.159C20.669 10.7371 20.0967 10.5 19.5 10.5H13.5C13.3013 10.4999 13.1108 10.421 12.9703 10.2806L8.68967 6H8.24998L9.42092 9.51281C9.45848 9.62548 9.46875 9.74546 9.45087 9.86288C9.433 9.98029 9.3875 10.0918 9.31811 10.1882C9.24872 10.2846 9.15744 10.3631 9.05177 10.4173C8.9461 10.4715 8.82906 10.4999 8.7103 10.5H5.24998C5.15146 10.5001 5.05389 10.4807 4.96285 10.4431C4.8718 10.4055 4.78906 10.3503 4.71936 10.2806L2.68967 8.25H2.24998L3.56905 12.6469C3.70619 13.1117 3.99062 13.5193 4.37951 13.8084C4.76841 14.0976 5.24071 14.2525 5.7253 14.25H21.75V12.75Z" fill="white" />
            </svg>
            Flights
          </a>
        </div>

        {/* Search Fields */}
        {hotelForm}
      </div>
    </section>
  );
}
