"use client";

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useRouter, useSearchParams } from "next/navigation";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useAuthStore } from "@/lib/auth-store";
import { apiClient } from "@/lib/api-client";
import { useBookingStore } from "@/lib/booking-store";
import { Station } from "@/types";
import {
  MapPin,
  ArrowLeftRight,
  Plus,
  Minus,
  Search,
  Users,
  ChevronDown,
  X,
  ChevronLeft,
  Clock,
} from "lucide-react";
import { useEffect, useRef, useState, useCallback } from "react";
import ModernDatePicker from "@/components/ModernDatePicker";

function useDarkMode() {
  const [dark, setDark] = useState(
    () =>
      typeof window !== "undefined" &&
      document.documentElement.classList.contains("dark"),
  );
  useEffect(() => {
    const obs = new MutationObserver(() =>
      setDark(document.documentElement.classList.contains("dark")),
    );
    obs.observe(document.documentElement, { attributeFilter: ["class"] });
    return () => obs.disconnect();
  }, []);
  return dark;
}

const searchSchema = z
  .object({
    tripType: z.enum(["ONE_WAY", "ROUND_TRIP"]),
    originStationId: z.string().min(1, "Please select your departure station"),
    destinationStationId: z
      .string()
      .min(1, "Please select your destination station"),
    departureDate: z.string().min(1, "Please select your departure date"),
    returnDate: z.string().optional(),
    adultCount: z.number().min(1).max(9),
    childCount: z.number().min(0).max(9),
    nationality: z.enum(["ETHIOPIAN", "DJIBOUTIAN", "OTHER"], {
      errorMap: () => ({ message: "Please select your nationality" }),
    }),
  })
  .refine(
    (d) => {
      if (d.tripType === "ROUND_TRIP" && !d.returnDate) {
        return false;
      }
      return true;
    },
    {
      message: "Please select return date",
      path: ["returnDate"],
    },
  )
  .refine(
    (d) => {
      if (d.tripType === "ROUND_TRIP" && d.returnDate && d.departureDate) {
        return d.returnDate >= d.departureDate;
      }
      return true;
    },
    {
      message: "Return date must be after departure date",
      path: ["returnDate"],
    },
  )
  .refine(
    (d) =>
      !d.originStationId ||
      !d.destinationStationId ||
      d.originStationId !== d.destinationStationId,
    {
      message: "Departure and destination cannot be the same station",
      path: ["destinationStationId"],
    },
  );

type SearchForm = z.infer<typeof searchSchema>;

// ─── Station Modal ────────────────────────────────────────────────────────────
function StationModal({
  stations,
  title,
  excludeId,
  onSelect,
  onClose,
  recentIds,
}: {
  stations: Station[];
  title: string;
  excludeId?: string;
  onSelect: (s: Station) => void;
  onClose: () => void;
  recentIds: string[];
}) {
  const [query, setQuery] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    setTimeout(() => inputRef.current?.focus(), 100);
  }, []);

  const filtered = query.trim()
    ? stations.filter(
        (s) =>
          s.id !== excludeId &&
          (s.name.toLowerCase().includes(query.toLowerCase()) ||
            s.code?.toLowerCase().includes(query.toLowerCase())),
      )
    : stations.filter((s) => s.id !== excludeId);

  const recentStations = recentIds
    .map((id) => stations.find((s) => s.id === id))
    .filter(Boolean) as Station[];

  return (
    <div className="fixed inset-0 z-[100] bg-white dark:bg-gray-900 flex flex-col md:hidden animate-slide-up">
      {/* Header */}
      <div className="flex items-center gap-3 px-4 py-4 border-b border-gray-100 dark:border-gray-800 bg-white dark:bg-gray-900">
        <button
          type="button"
          onClick={onClose}
          className="w-10 h-10 flex items-center justify-center rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
        >
          <ChevronLeft className="w-5 h-5 text-gray-600 dark:text-gray-400" />
        </button>
        <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
          {title}
        </h2>
      </div>

      {/* Search input */}
      <div className="px-4 py-3 bg-white dark:bg-gray-900">
        <div className="relative">
          <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            ref={inputRef}
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search stations..."
            className="w-full pl-10 pr-10 py-3 bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary text-gray-900 dark:text-white placeholder-gray-400"
          />
          {query && (
            <button
              type="button"
              onClick={() => setQuery("")}
              className="absolute right-3 top-1/2 -translate-y-1/2"
            >
              <X className="w-4 h-4 text-gray-400" />
            </button>
          )}
        </div>
      </div>

      {/* Results */}
      <div className="flex-1 overflow-y-auto px-4 pb-6">
        {!query && recentStations.length > 0 && (
          <div className="mb-4">
            <p className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-2 mt-2">
              Recent
            </p>
            {recentStations.map((s) => (
              <button
                key={s.id}
                type="button"
                onClick={() => onSelect(s)}
                className="w-full flex items-center gap-3 py-3.5 px-3 rounded-xl hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors text-left"
              >
                <div className="w-8 h-8 bg-primary/10 rounded-full flex items-center justify-center flex-shrink-0">
                  <Clock className="w-4 h-4 text-primary" />
                </div>
                <div>
                  <p className="font-medium text-gray-900 dark:text-white text-sm">
                    {s.name}
                  </p>
                  {s.code && <p className="text-xs text-gray-400">{s.code}</p>}
                </div>
              </button>
            ))}
          </div>
        )}

        <p className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-2 mt-2">
          {query ? "Results" : "All Stations"}
        </p>
        {filtered.length === 0 ? (
          <div className="text-center py-10 text-gray-400">
            <MapPin className="w-8 h-8 mx-auto mb-2 opacity-40" />
            <p className="text-sm">No stations found</p>
          </div>
        ) : (
          filtered.map((s) => (
            <button
              key={s.id}
              type="button"
              onClick={() => onSelect(s)}
              className="w-full flex items-center gap-3 py-3.5 px-3 rounded-xl hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors text-left"
            >
              <div className="w-8 h-8 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center flex-shrink-0">
                <MapPin className="w-4 h-4 text-primary" />
              </div>
              <div>
                <p className="font-medium text-gray-900 dark:text-white text-sm">
                  {s.name}
                </p>
                {s.code && (
                  <p className="text-xs text-gray-400">
                    {s.code} • {s.country}
                  </p>
                )}
              </div>
            </button>
          ))
        )}
      </div>
    </div>
  );
}

// ─── Passenger Modal (mobile bottom-sheet) ───────────────────────────────────
function PassengerModal({
  adultCount,
  childCount,
  nationality,
  onChangeAdult,
  onChangeChild,
  onChangeNationality,
  onClose,
  nationalityError,
}: {
  adultCount: number;
  childCount: number;
  nationality: string;
  onChangeAdult: (n: number) => void;
  onChangeChild: (n: number) => void;
  onChangeNationality: (v: string) => void;
  onClose: () => void;
  nationalityError?: string;
}) {
  const rows = [
    {
      label: "Adults",
      sub: "≥ 5 years",
      val: adultCount,
      min: 1,
      max: 9,
      onChange: onChangeAdult,
    },
    {
      label: "Children",
      sub: "< 5 years • First child free",
      val: childCount,
      min: 0,
      max: 9,
      onChange: onChangeChild,
    },
  ];

  const natOptions = [
    { value: "ETHIOPIAN", label: "🇪🇹 Ethiopian" },
    { value: "DJIBOUTIAN", label: "🇩🇯 Djiboutian" },
    { value: "OTHER", label: "🌍 Other" },
  ];

  return (
    <>
      <div className="fixed inset-0 z-[99] bg-black/40" onClick={onClose} />
      <div
        className="fixed inset-x-0 bottom-0 sm:inset-auto sm:top-1/2 sm:left-1/2 sm:-translate-x-1/2 sm:-translate-y-1/2 z-[100] bg-white dark:bg-gray-900 rounded-t-2xl sm:rounded-2xl shadow-2xl w-full sm:w-96"
        style={{ animation: "pax-slide-up 0.25s cubic-bezier(0.32,0.72,0,1)" }}
      >
        <div className="flex justify-center pt-3 pb-1">
          <div className="w-10 h-1 rounded-full bg-gray-300 dark:bg-gray-600" />
        </div>
        <div className="flex items-center justify-between px-5 py-3 border-b border-gray-100 dark:border-gray-800">
          <div className="flex items-center gap-2">
            <Users className="w-4 h-4 text-primary" />
            <h2 className="text-base font-bold text-gray-900 dark:text-white">
              Passengers &amp; Nationality
            </h2>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="w-9 h-9 flex items-center justify-center rounded-full hover:bg-gray-100 dark:hover:bg-gray-800"
          >
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>
        <div className="px-5 py-4 space-y-5">
          {rows.map(({ label, sub, val, min, max, onChange }, i) => (
            <div key={label}>
              {i > 0 && (
                <div className="border-t border-gray-100 dark:border-gray-800 -mx-5 mb-5" />
              )}
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-semibold text-gray-900 dark:text-white">
                    {label}
                  </p>
                  <p className="text-xs text-gray-400 mt-0.5">{sub}</p>
                </div>
                <div className="flex items-center gap-4">
                  <button
                    type="button"
                    onClick={() => val > min && onChange(val - 1)}
                    disabled={val <= min}
                    className="w-10 h-10 rounded-full border-2 border-gray-200 dark:border-gray-700 flex items-center justify-center hover:border-primary hover:text-primary disabled:opacity-30"
                  >
                    <Minus className="w-4 h-4" />
                  </button>
                  <span className="w-6 text-center text-lg font-bold text-gray-900 dark:text-white tabular-nums">
                    {val}
                  </span>
                  <button
                    type="button"
                    onClick={() => val < max && onChange(val + 1)}
                    disabled={val >= max}
                    className="w-10 h-10 rounded-full border-2 border-gray-200 dark:border-gray-700 flex items-center justify-center hover:border-primary hover:text-primary disabled:opacity-30"
                  >
                    <Plus className="w-4 h-4" />
                  </button>
                </div>
              </div>
            </div>
          ))}
          <div className="border-t border-gray-100 dark:border-gray-800 -mx-5 pt-5 px-5">
            <p className="text-sm font-semibold text-gray-900 dark:text-white mb-1">
              Nationality
            </p>
            {nationalityError && (
              <p className="text-xs text-red-500 mb-2">{nationalityError}</p>
            )}
            <div
              className={`grid grid-cols-3 gap-2 ${nationalityError ? "mt-1" : "mt-2"}`}
            >
              {natOptions.map((opt) => (
                <button
                  key={opt.value}
                  type="button"
                  onClick={() => onChangeNationality(opt.value)}
                  className={`py-2.5 px-2 rounded-xl border-2 text-xs font-semibold transition-all ${
                    nationality === opt.value
                      ? "border-primary bg-primary/5 text-primary"
                      : nationalityError
                        ? "border-red-300 dark:border-red-800 text-gray-600 dark:text-gray-400 hover:border-gray-300"
                        : "border-gray-200 dark:border-gray-700 text-gray-600 dark:text-gray-400 hover:border-gray-300"
                  }`}
                >
                  {opt.label}
                </button>
              ))}
            </div>
          </div>
        </div>
        <div className="px-5 pb-8 pt-2">
          <button
            type="button"
            onClick={onClose}
            className="w-full py-3.5 bg-[rgb(20,113,76)] text-white font-bold text-sm rounded-xl"
          >
            Continue
          </button>
        </div>
        <style>{`@keyframes pax-slide-up{from{transform:translateY(100%);opacity:0}to{transform:translateY(0);opacity:1}}`}</style>
      </div>
    </>
  );
}

// ─── Station Autocomplete (Desktop dropdown) ──────────────────────────────────
function StationDropdown({
  stations,
  value,
  excludeId,
  placeholder,
  onSelect,
  error,
  recentIds,
  onOpen,
}: {
  stations: Station[];
  value: string;
  excludeId?: string;
  placeholder: string;
  onSelect: (s: Station) => void;
  error?: string;
  recentIds: string[];
  onOpen?: () => void;
}) {
  const [query, setQuery] = useState("");
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const selectedStation = stations.find((s) => s.id === value);

  useEffect(() => {
    if (selectedStation && !open) setQuery("");
  }, [selectedStation, open]);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node))
        setOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const filtered = query.trim()
    ? stations.filter(
        (s) =>
          s.id !== excludeId &&
          (s.name.toLowerCase().includes(query.toLowerCase()) ||
            s.code?.toLowerCase().includes(query.toLowerCase())),
      )
    : stations.filter((s) => s.id !== excludeId).slice(0, 20);

  const displayValue = open ? query : (selectedStation?.name ?? "");

  return (
    <div ref={ref} className="relative">
      <div
        className={`relative flex items-center border-2 rounded-xl transition-all duration-200 bg-white dark:bg-gray-800 ${
          error
            ? "border-red-400"
            : open
              ? "border-primary ring-2 ring-primary/20"
              : "border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600"
        }`}
      >
        <MapPin className="absolute left-3.5 w-4 h-4 text-primary flex-shrink-0" />
        <input
          ref={inputRef}
          value={displayValue}
          onChange={(e) => {
            setQuery(e.target.value);
            setOpen(true);
          }}
          onFocus={() => {
            setQuery("");
            setOpen(true);
            onOpen?.();
          }}
          placeholder={placeholder}
          className="w-full pl-10 pr-8 py-3.5 bg-transparent rounded-xl focus:outline-none text-sm text-gray-900 dark:text-white placeholder-gray-400"
        />
        {value && (
          <button
            type="button"
            onClick={() => {
              onSelect({ id: "", name: "", code: "", country: "" });
              setQuery("");
            }}
            className="absolute right-3 p-0.5"
          >
            <X className="w-3.5 h-3.5 text-gray-400 hover:text-gray-600" />
          </button>
        )}
      </div>

      {open && (
        <div className="absolute top-full left-0 right-0 mt-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl shadow-xl z-[200] max-h-96 overflow-y-auto overflow-x-hidden scrollbar-hide">
          {!query && recentIds.length > 0 && (
            <div className="px-3 pt-2 pb-1">
              <p className="text-[10px] font-semibold text-gray-400 uppercase tracking-wide mb-1">
                Recent
              </p>
              {recentIds
                .map((id) => stations.find((s) => s.id === id))
                .filter(Boolean)
                .map((s) => (
                  <button
                    key={s!.id}
                    type="button"
                    onMouseDown={() => {
                      onSelect(s!);
                      setOpen(false);
                      setQuery("");
                    }}
                    className="w-full flex items-center gap-2 px-2 py-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 text-left"
                  >
                    <Clock className="w-3.5 h-3.5 text-primary flex-shrink-0" />
                    <span className="text-sm text-gray-800 dark:text-gray-200">
                      {s!.name}
                    </span>
                  </button>
                ))}
              <div className="border-t border-gray-100 dark:border-gray-700 mt-1 mb-1" />
            </div>
          )}
          {filtered.length === 0 ? (
            <p className="text-sm text-gray-400 text-center py-4">
              No stations found
            </p>
          ) : (
            filtered.map((s) => (
              <button
                key={s.id}
                type="button"
                onMouseDown={() => {
                  onSelect(s);
                  setOpen(false);
                  setQuery("");
                }}
                className="w-full flex items-center gap-2 px-3 py-2.5 hover:bg-gray-50 dark:hover:bg-gray-700 text-left transition-colors"
              >
                <MapPin className="w-3.5 h-3.5 text-primary flex-shrink-0" />
                <div>
                  <span className="text-sm font-medium text-gray-900 dark:text-white">
                    {s.name}
                  </span>
                  {s.code && (
                    <span className="text-xs text-gray-400 ml-1.5">
                      {s.code}
                    </span>
                  )}
                </div>
              </button>
            ))
          )}
        </div>
      )}
    </div>
  );
}

// ─── Main Page ────────────────────────────────────────────────────────────────
export default function SearchPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const setSearchCriteria = useBookingStore((s) => s.setSearchCriteria);
  const clearBooking = useBookingStore((s) => s.clearBooking);
  const queryClient = useQueryClient();
  const { user, isAuthenticated } = useAuthStore();

  const dark = useDarkMode();
  const [passengerModalOpen, setPassengerModalOpen] = useState(false);
  const [swapping, setSwapping] = useState(false);
  const [stationModal, setStationModal] = useState<
    "origin" | "destination" | null
  >(null);
  const [hasInteracted, setHasInteracted] = useState(false);
  // Immediate feedback the moment Search is clicked — router.push() itself
  // doesn't paint anything until the target route's JS has loaded, which
  // otherwise reads as a dead click.
  const [isSearching, setIsSearching] = useState(false);
  // Mobile only: collapsed view shows just From/To + Search; tapping Search opens this
  // modal with the full field set (trip type, dates, passengers/nationality) instead of
  // showing everything inline on the page.
  const [mobileSearchModalOpen, setMobileSearchModalOpen] = useState(false);

  // Warms the results route's JS chunk ahead of time so clicking Search
  // doesn't have to wait for it to download/compile on top of the actual
  // search request.
  useEffect(() => {
    router.prefetch("/booking/results");
  }, [router]);
  const [recentStationIds, setRecentStationIds] = useState<string[]>(() => {
    try {
      return JSON.parse(localStorage.getItem("edr_recent_stations") || "[]");
    } catch {
      return [];
    }
  });
  const passengerRef = useRef<HTMLDivElement>(null);
  const widgetRef = useRef<HTMLDivElement>(null);

  const scrollWidgetIntoView = () => {
    const el = widgetRef.current;
    if (!el) return;
    const headerHeight = 64;
    const marginTop = 24;
    const top =
      el.getBoundingClientRect().top +
      window.scrollY -
      headerHeight -
      marginTop;
    window.scrollTo({ top, behavior: "smooth" });
  };

  const {
    data: stations = [],
    isLoading,
    error,
  } = useQuery<Station[]>({
    queryKey: ["stations"],
    // Bounded so a stalled request surfaces the "Unable to load stations"
    // error below instead of leaving the widget stuck loading indefinitely.
    queryFn: async () =>
      (await apiClient.get("/stations", { timeout: 8000 })) as Station[],
  });

  const {
    handleSubmit,
    watch,
    setValue,
    trigger,
    clearErrors,
    formState: { errors },
  } = useForm<SearchForm>({
    resolver: zodResolver(searchSchema as any),
    mode: "onSubmit",
    reValidateMode: "onSubmit",
    defaultValues: {
      tripType: "ONE_WAY",
      // originStationId/destinationStationId must default to "" rather than being omitted —
      // Zod's base string type check runs before .min(1, "..."), so an `undefined` value hits
      // its generic "Required" message instead of our custom one. An empty string is still a
      // string, so .min() (and its custom message) is what actually fires.
      originStationId: "",
      destinationStationId: "",
      adultCount: 1,
      childCount: 0,
      // No default nationality — the user must explicitly pick one. Left blank (not a valid
      // enum member) so the zod schema's errorMap flags it if they try to search without
      // selecting it.
      nationality: "" as any,
      departureDate: "",
    },
  });

  useEffect(() => {
    if (isAuthenticated && user?.nationality) {
      const n = user.nationality.toUpperCase().trim();
      setValue(
        "nationality",
        n.includes("DJIBOUTIAN")
          ? "DJIBOUTIAN"
          : n.includes("ETHIOPIAN")
            ? "ETHIOPIAN"
            : "OTHER",
      );
    }
  }, [isAuthenticated, user?.nationality, setValue]);

  useEffect(() => {
    const o = searchParams.get("origin");
    const d = searchParams.get("destination");
    const date = searchParams.get("date");
    const adults = searchParams.get("adults");
    const children = searchParams.get("children");
    const nat = searchParams.get("nationality");
    const tripType = searchParams.get("tripType");
    const returnDate = searchParams.get("returnDate");
    if (o) setValue("originStationId", o);
    if (d) setValue("destinationStationId", d);
    if (date) setValue("departureDate", date);
    if (adults) setValue("adultCount", parseInt(adults));
    if (children) setValue("childCount", parseInt(children));
    if (nat)
      setValue("nationality", nat as "ETHIOPIAN" | "DJIBOUTIAN" | "OTHER");
    if (tripType) setValue("tripType", tripType as "ONE_WAY" | "ROUND_TRIP");
    if (returnDate) setValue("returnDate", returnDate);
  }, [searchParams, setValue]);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (
        passengerRef.current &&
        !passengerRef.current.contains(e.target as Node)
      ) {
        setPassengerModalOpen(false);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const originId = watch("originStationId");
  const destId = watch("destinationStationId");
  const adultCount = watch("adultCount");
  const childCount = watch("childCount");
  const departureDate = watch("departureDate");
  const returnDate = watch("returnDate");
  const tripType = watch("tripType");
  const totalPassengers = (adultCount || 1) + (childCount || 0);

  const saveRecent = useCallback((id: string) => {
    setRecentStationIds((prev) => {
      const next = [id, ...prev.filter((x) => x !== id)].slice(0, 5);
      localStorage.setItem("edr_recent_stations", JSON.stringify(next));
      return next;
    });
  }, []);

  const handleSwap = () => {
    if (!originId || !destId) return;
    setSwapping(true);
    setTimeout(() => {
      setValue("originStationId", destId);
      setValue("destinationStationId", originId);
      setSwapping(false);
    }, 300);
  };

  const onSubmit = (data: SearchForm) => {
    setHasInteracted(true);
    setIsSearching(true);
    // Clear previous booking selections and search cache before starting a new search
    clearBooking();
    setSearchCriteria(data);
    queryClient.removeQueries({ queryKey: ["search"] });
    if (data.originStationId) saveRecent(data.originStationId);
    if (data.destinationStationId) saveRecent(data.destinationStationId);
    const params = new URLSearchParams({
      tripType: data.tripType,
      origin: data.originStationId,
      destination: data.destinationStationId,
      date: data.departureDate,
      adults: data.adultCount.toString(),
      children: data.childCount.toString(),
      nationality: data.nationality,
      ...(data.tripType === "ROUND_TRIP" &&
        data.returnDate && { returnDate: data.returnDate }),
    });
    router.push(`/booking/results?${params}`);
  };

  // Validate the rest of the form first — only once every other field is already valid do
  // we surface the nationality error (opening the modal directly rather than leaving an
  // inline error to hunt for). Otherwise nationality's error would show at the same time as
  // origin/destination/date errors, which is noisier than fixing things one step at a time.
  const onInvalid = (formErrors: typeof errors) => {
    setHasInteracted(true);
    setIsSearching(false);
    const hasOtherErrors = Object.keys(formErrors).some(
      (k) => k !== "nationality",
    );
    if (formErrors.nationality && !hasOtherErrors) {
      setPassengerModalOpen(true);
    }
  };

  const getStationById = (id: string) => stations.find((s) => s.id === id);
  const originStation = getStationById(originId);
  const destStation = getStationById(destId);

  // Mirrors onInvalid's ordering: don't flag nationality (border/message/modal) while other
  // fields still have errors of their own to fix first.
  const showNationalityError =
    hasInteracted &&
    !!errors.nationality &&
    !Object.keys(errors).some((k) => k !== "nationality");

  // No default nationality anymore — only render a flag once one is actually picked, rather
  // than falling through to the "Other" 🌍 flag and implying a selection that hasn't happened.
  const nationalityFlag = (nat?: string) =>
    nat === "ETHIOPIAN"
      ? "🇪🇹"
      : nat === "DJIBOUTIAN"
        ? "🇩🇯"
        : nat === "OTHER"
          ? "🌍"
          : null;

  // Shared between the desktop layout and the mobile search modal — kept out of the
  // collapsed mobile view (see mobileSearchModalOpen).
  const renderTripTypeTabs = () => (
    <div className="mb-4">
      <div className="inline-flex rounded-xl bg-gray-100 dark:bg-gray-800 p-1 w-full md:w-auto">
        <button
          type="button"
          onClick={() => setValue("tripType", "ONE_WAY")}
          className={`flex-1 md:flex-none px-6 py-2.5 rounded-lg text-sm font-semibold transition-all ${
            tripType === "ONE_WAY"
              ? "bg-white dark:bg-gray-900 text-primary shadow-sm"
              : "text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200"
          }`}
        >
          One Way
        </button>
        <button
          type="button"
          onClick={() => setValue("tripType", "ROUND_TRIP")}
          className={`flex-1 md:flex-none px-6 py-2.5 rounded-lg text-sm font-semibold transition-all ${
            tripType === "ROUND_TRIP"
              ? "bg-white dark:bg-gray-900 text-primary shadow-sm"
              : "text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200"
          }`}
        >
          Round Trip
        </button>
      </div>
    </div>
  );

  // From/To fields — rendered both in the mobile collapsed view (so a station can be
  // picked without opening the full modal) and inside the modal itself (prefilled with
  // whatever was already picked). Tapping either still opens StationModal directly.
  // stacked: single column for the collapsed first view; the modal keeps the 2-column grid.
  const renderStationFields = (stacked = false) => (
    <div className={stacked ? "flex flex-col gap-3" : "grid grid-cols-2 gap-3"}>
      <div className="space-y-1.5 min-w-0">
        <div className="h-5 flex items-center">
          <label className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
            From
          </label>
        </div>
        <button
          type="button"
          onClick={() => {
            setHasInteracted(true);
            window.scrollTo({
              top: 0,
              behavior: "instant" as ScrollBehavior,
            });
            setStationModal("origin");
          }}
          className="w-full"
        >
          <div
            className={`flex items-center gap-2 px-2.5 py-3 border-2 rounded-xl transition-all ${
              hasInteracted && errors.originStationId
                ? "border-red-400"
                : originId
                  ? "border-primary bg-primary/5"
                  : "border-gray-200 dark:border-gray-700"
            }`}
            style={{ backgroundColor: originId ? undefined : undefined }}
          >
            <MapPin className="w-4 h-4 text-primary flex-shrink-0" />
            <span
              style={{
                color: originStation
                  ? dark
                    ? "#ffffff"
                    : "#111827"
                  : dark
                    ? "#6b7280"
                    : "#9ca3af",
              }}
              className={`text-sm truncate ${originStation ? "font-semibold" : ""}`}
            >
              {originStation?.name ??
                (stacked ? "Select departure station" : "Departure")}
            </span>
          </div>
        </button>
        {hasInteracted && errors.originStationId && (
          <p className="text-xs text-red-500">
            {errors.originStationId.message}
          </p>
        )}
      </div>
      <div className="space-y-1.5 min-w-0">
        <div className="h-5 flex items-center justify-between">
          <label className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
            To
          </label>
          <button
            type="button"
            onClick={handleSwap}
            disabled={!originId || !destId}
            aria-label="Swap origin and destination"
            className="flex items-center justify-center gap-1 text-xs text-primary font-medium disabled:opacity-30 p-0 h-5 w-5"
          >
            <ArrowLeftRight
              className={`w-3.5 h-3.5 transition-transform duration-300 ${swapping ? "rotate-180" : ""}`}
            />
          </button>
        </div>
        <button
          type="button"
          onClick={() => {
            setHasInteracted(true);
            window.scrollTo({
              top: 0,
              behavior: "instant" as ScrollBehavior,
            });
            setStationModal("destination");
          }}
          className="w-full"
        >
          <div
            className={`flex items-center gap-2 px-2.5 py-3 border-2 rounded-xl transition-all ${
              hasInteracted && errors.destinationStationId
                ? "border-red-400"
                : destId
                  ? "border-primary bg-primary/5"
                  : "border-gray-200 dark:border-gray-700"
            }`}
          >
            <MapPin className="w-4 h-4 text-primary flex-shrink-0" />
            <span
              style={{
                color: destStation
                  ? dark
                    ? "#ffffff"
                    : "#111827"
                  : dark
                    ? "#6b7280"
                    : "#9ca3af",
              }}
              className={`text-sm truncate ${destStation ? "font-semibold" : ""}`}
            >
              {destStation?.name ??
                (stacked ? "Select destination station" : "Destination")}
            </span>
          </div>
        </button>
        {hasInteracted && errors.destinationStationId && (
          <p className="text-xs text-red-500">
            {errors.destinationStationId.message}
          </p>
        )}
      </div>
    </div>
  );

  return (
    <div className="bg-gray-50 dark:bg-gray-950">
      {/* Passenger modal (mobile) */}
      {passengerModalOpen && (
        <PassengerModal
          adultCount={adultCount || 1}
          childCount={childCount || 0}
          nationality={watch("nationality")}
          onChangeAdult={(n) => setValue("adultCount", n)}
          onChangeChild={(n) => setValue("childCount", n)}
          onChangeNationality={(v) => {
            setValue("nationality", v as any);
            clearErrors("nationality");
          }}
          onClose={() => setPassengerModalOpen(false)}
          nationalityError={
            showNationalityError ? errors.nationality?.message : undefined
          }
        />
      )}

      {/* Station modals (mobile) */}
      {stationModal === "origin" && (
        <StationModal
          stations={stations}
          title="From — Departure"
          excludeId={destId}
          recentIds={recentStationIds}
          onSelect={(s) => {
            if (s.id) {
              setValue("originStationId", s.id);
              saveRecent(s.id);
              clearErrors("originStationId");
              clearErrors("destinationStationId");
            }
            setStationModal(null);
          }}
          onClose={() => setStationModal(null)}
        />
      )}
      {stationModal === "destination" && (
        <StationModal
          stations={stations}
          title="To — Destination"
          excludeId={originId}
          recentIds={recentStationIds}
          onSelect={(s) => {
            if (s.id) {
              setValue("destinationStationId", s.id);
              saveRecent(s.id);
              clearErrors("destinationStationId");
            }
            setStationModal(null);
          }}
          onClose={() => setStationModal(null)}
        />
      )}

      {/* ── Hero with banner image (desktop only — mobile is content-driven, no
          forced height, so it doesn't push the Packages section below the fold).
          Desktop height is intentionally short of a full viewport so the Packages
          section peeks into view without scrolling — a full 94vh hero was hiding
          it entirely on common screen sizes. ── */}
      <section className="relative md:h-[75vh] md:min-h-[500px]">
        {/* Background image with zoom - fully isolated */}
        <div className="absolute inset-0 overflow-hidden">
          <div
            className="w-full h-full bg-cover bg-center animate-bg-zoom"
            style={{
              backgroundImage: "url(/edr-banner.jpg)",
              position: "absolute",
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
            }}
          />
        </div>
        {/* Gradient overlay — desktop only (exists to keep the hero text readable over the image) */}
        <div className="hidden md:block absolute inset-0 bg-gradient-to-br from-black/70 via-black/40 to-transparent" />
        <div className="hidden md:block absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent" />

        {/* Hero headline — desktop only; removed on mobile along with the banner image */}
        <div className="hidden md:block relative z-10 pt-16 md:pt-20 px-6 md:px-12 max-w-6xl mx-auto">
          <h1 className="text-4xl md:text-5xl lg:text-6xl font-extrabold text-white leading-tight drop-shadow-lg max-w-2xl animate-fade-in-up">
            Where are you
            <br className="hidden sm:block" /> headed today?
          </h1>
          <p className="text-white/90 text-sm md:text-base mt-3 drop-shadow-lg animate-fade-in-up-delay">
            Book your train journey across East Africa
          </p>
        </div>

        {/* ── Widget — top-aligned, normal flow on mobile; absolutely positioned at
            bottom on desktop over the hero image. z-[35] sits above the floating
            support chat launcher (z-30) but below the sidebar/tab bar (z-40), so it
            never covers either. Modals opened from inside the widget (date picker
            etc.) are portaled to <body> — see ModernDatePicker — so they aren't
            capped by this wrapper's own stacking context. ── */}
        <div
          className="relative pt-4 pb-4 md:pt-0 md:pb-0 md:absolute md:bottom-8 md:left-0 md:right-0 z-[30] px-4 md:px-6"
          ref={widgetRef}
        >
          <div className="max-w-6xl mx-auto">
            {/* Mobile-only heading — desktop keeps the version overlaid on the hero image above */}
            <div className="md:hidden mb-3">
              <h1 className="text-lg font-extrabold text-gray-900 dark:text-gray-100 leading-tight">
                Where are you headed today?
              </h1>
            </div>
            <form onSubmit={handleSubmit(onSubmit, onInvalid)}>
              <div className="bg-white dark:bg-gray-900 rounded-2xl shadow-none md:shadow-2xl border border-white/20 overflow-visible">
                {error && (
                  <div className="flex items-center gap-2 px-5 py-3 bg-red-50 text-red-600 text-sm border-b border-red-100 rounded-t-2xl">
                    <span>⚠️</span>
                    <span>
                      Unable to load stations. Please check your connection.
                    </span>
                  </div>
                )}

                <div className="p-4 md:p-5">
                  {/* Trip Type Tabs — always visible on desktop; on mobile only inside the
                      search modal (hidden in the collapsed view). */}
                  <div
                    className={`${mobileSearchModalOpen ? "block" : "hidden"} md:block`}
                  >
                    {renderTripTypeTabs()}
                  </div>

                  {/* Mobile collapsed view — just From/To + Search. Tapping a station still
                      opens StationModal directly; tapping Search opens the full modal below
                      instead of submitting (validation happens inside that modal). */}
                  <div
                    className={`${mobileSearchModalOpen ? "hidden" : "flex"} flex-col gap-3 md:hidden`}
                  >
                    {renderStationFields(true)}
                    <button
                      type="button"
                      onClick={() => setMobileSearchModalOpen(true)}
                      className="btn-primary w-full text-sm flex items-center justify-center gap-2"
                    >
                      <Search className="w-5 h-5" />
                      Search
                    </button>
                  </div>

                  {/* Mobile search modal — full field set (trip type, From/To, dates,
                      passengers/nationality). Its Search button is the real form submit —
                      same onSubmit/onInvalid/validation as before, just relocated here. */}
                  {mobileSearchModalOpen && (
                    <div
                      className="fixed inset-0 z-[100] bg-white dark:bg-gray-900 flex flex-col md:hidden animate-slide-up"
                      role="dialog"
                      aria-modal="true"
                      aria-labelledby="mobile-search-modal-title"
                    >
                      <div className="flex items-center gap-3 px-4 py-4 border-b border-gray-100 dark:border-gray-800 flex-shrink-0">
                        <button
                          type="button"
                          onClick={() => setMobileSearchModalOpen(false)}
                          className="w-10 h-10 flex items-center justify-center rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
                          aria-label="Close"
                        >
                          <X className="w-5 h-5 text-gray-600 dark:text-gray-400" />
                        </button>
                        <h2
                          id="mobile-search-modal-title"
                          className="text-lg font-semibold text-gray-900 dark:text-white"
                        >
                          Plan and Book Your Trip
                        </h2>
                      </div>

                      <div className="flex-1 overflow-y-auto px-4 py-4 flex flex-col gap-3">
                        {renderTripTypeTabs()}
                        {renderStationFields()}
                        <div
                          className={
                            tripType === "ROUND_TRIP"
                              ? "grid grid-cols-2 gap-3"
                              : ""
                          }
                        >
                          <div className="space-y-1.5 min-w-0">
                            <label className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
                              Date
                            </label>
                            <div>
                              <ModernDatePicker
                                value={
                                  departureDate
                                    ? new Date(departureDate + "T00:00:00")
                                    : undefined
                                }
                                onChange={(date) => {
                                  setValue(
                                    "departureDate",
                                    `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`,
                                  );
                                  trigger("departureDate");
                                }}
                                minDate={new Date()}
                                placeholder="Departure date"
                                error={!!errors.departureDate}
                              />
                            </div>
                            {errors.departureDate && (
                              <p className="text-xs text-red-500">
                                {errors.departureDate.message}
                              </p>
                            )}
                          </div>
                          {tripType === "ROUND_TRIP" && (
                            <div className="space-y-1.5 min-w-0">
                              <label className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
                                Return Date
                              </label>
                              <div>
                                <ModernDatePicker
                                  value={
                                    returnDate
                                      ? new Date(returnDate + "T00:00:00")
                                      : undefined
                                  }
                                  onChange={(date) => {
                                    setValue(
                                      "returnDate",
                                      `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`,
                                    );
                                    trigger("returnDate");
                                  }}
                                  minDate={
                                    departureDate
                                      ? new Date(departureDate + "T00:00:00")
                                      : new Date()
                                  }
                                  placeholder="Return date"
                                  error={!!errors.returnDate}
                                />
                              </div>
                              {errors.returnDate && (
                                <p className="text-xs text-red-500">
                                  {errors.returnDate.message}
                                </p>
                              )}
                            </div>
                          )}
                        </div>
                        {/* Pax + Nationality combined trigger */}
                        <button
                          type="button"
                          onClick={() => setPassengerModalOpen(true)}
                          className={`w-full flex items-center justify-between px-3.5 py-3 border-2 rounded-xl bg-white dark:bg-gray-800 ${
                            showNationalityError
                              ? "border-red-400"
                              : "border-gray-200 dark:border-gray-700"
                          }`}
                        >
                          <span
                            className="flex items-center gap-2 text-sm font-medium"
                            style={{ color: dark ? "#ffffff" : "#111827" }}
                          >
                            <Users className="w-4 h-4 text-primary" />
                            {totalPassengers}{" "}
                            {totalPassengers === 1 ? "Passenger" : "Passengers"}
                            {nationalityFlag(watch("nationality"))
                              ? ` · ${nationalityFlag(watch("nationality"))}`
                              : " · Nationality"}
                          </span>
                          <ChevronDown className="w-4 h-4 text-primary" />
                        </button>
                        {showNationalityError && (
                          <p className="text-xs text-red-500">
                            {errors.nationality?.message}
                          </p>
                        )}
                        <button
                          type="submit"
                          disabled={isLoading || isSearching}
                          className="btn-primary w-full text-sm flex items-center justify-center gap-2 disabled:opacity-80"
                        >
                          {isSearching ? (
                            <>
                              <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                              Searching...
                            </>
                          ) : (
                            <>
                              <Search className="w-5 h-5" />
                              Search
                            </>
                          )}
                        </button>
                      </div>
                    </div>
                  )}

                  {/* Desktop: dynamic layout based on trip type */}
                  <div className={`hidden md:block`}>
                    {tripType === "ONE_WAY" ? (
                      // ONE WAY: Single row layout
                      <div className="flex items-end gap-2">
                        {/* From */}
                        <div className="flex-1 min-w-0 space-y-1">
                          <label className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
                            From
                          </label>
                          <StationDropdown
                            stations={stations}
                            value={originId}
                            excludeId={destId}
                            placeholder="Departure station"
                            recentIds={recentStationIds}
                            onSelect={(s) => {
                              setHasInteracted(true);
                              setValue("originStationId", s.id);
                              if (s.id) saveRecent(s.id);
                              clearErrors("originStationId");
                              clearErrors("destinationStationId");
                            }}
                            error={
                              hasInteracted
                                ? errors.originStationId?.message
                                : undefined
                            }
                            onOpen={scrollWidgetIntoView}
                          />
                          {hasInteracted && errors.originStationId && (
                            <p className="text-xs text-red-500">
                              {errors.originStationId.message}
                            </p>
                          )}
                        </div>
                        {/* Swap */}
                        <button
                          type="button"
                          onClick={handleSwap}
                          disabled={!originId || !destId}
                          className={`flex-shrink-0 mb-0.5 w-9 h-9 bg-gray-50 border-2 border-gray-200 rounded-full flex items-center justify-center hover:border-primary hover:bg-primary/5 transition-all disabled:opacity-30 ${swapping ? "rotate-180" : ""}`}
                        >
                          <ArrowLeftRight className="w-4 h-4 text-gray-500" />
                        </button>
                        {/* To */}
                        <div className="flex-1 min-w-0 space-y-1">
                          <label className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
                            To
                          </label>
                          <StationDropdown
                            stations={stations}
                            value={destId}
                            excludeId={originId}
                            placeholder="Destination station"
                            recentIds={recentStationIds}
                            onSelect={(s) => {
                              setHasInteracted(true);
                              setValue("destinationStationId", s.id);
                              if (s.id) saveRecent(s.id);
                              clearErrors("destinationStationId");
                            }}
                            error={
                              hasInteracted
                                ? errors.destinationStationId?.message
                                : undefined
                            }
                            onOpen={scrollWidgetIntoView}
                          />
                          {hasInteracted && errors.destinationStationId && (
                            <p className="text-xs text-red-500">
                              {errors.destinationStationId.message}
                            </p>
                          )}
                        </div>
                        {/* Date */}
                        <div className="w-44 flex-shrink-0 space-y-1">
                          <label className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
                            Date
                          </label>
                          <div>
                            <ModernDatePicker
                              value={
                                departureDate
                                  ? new Date(departureDate + "T00:00:00")
                                  : undefined
                              }
                              onChange={(date) => {
                                setValue(
                                  "departureDate",
                                  `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`,
                                );
                                trigger("departureDate");
                              }}
                              minDate={new Date()}
                              placeholder="Departure"
                              error={!!errors.departureDate}
                            />
                          </div>
                          {errors.departureDate && (
                            <p className="text-xs text-red-500">
                              {errors.departureDate.message}
                            </p>
                          )}
                        </div>
                        {/* Pax + Nationality */}
                        <div className="w-44 flex-shrink-0 space-y-1">
                          <label className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
                            Passengers
                          </label>
                          <button
                            type="button"
                            onClick={() => setPassengerModalOpen(true)}
                            className={`w-full flex items-center justify-between px-3 py-3.5 border-2 rounded-xl bg-white dark:bg-gray-800 hover:border-gray-300 dark:hover:border-gray-600 transition-all ${
                              showNationalityError
                                ? "border-red-400"
                                : "border-gray-200 dark:border-gray-700"
                            }`}
                          >
                            <span className="flex items-center gap-1.5 text-sm font-medium text-gray-900 dark:text-white truncate">
                              <Users className="w-4 h-4 text-primary flex-shrink-0" />
                              {totalPassengers}{" "}
                              {totalPassengers === 1
                                ? "Passenger"
                                : "Passengers"}
                              {nationalityFlag(watch("nationality"))
                                ? ` · ${nationalityFlag(watch("nationality"))}`
                                : " · Nationality"}
                            </span>
                            <ChevronDown className="w-4 h-4 text-primary flex-shrink-0" />
                          </button>
                          {showNationalityError && (
                            <p className="text-xs text-red-500">
                              {errors.nationality?.message}
                            </p>
                          )}
                        </div>
                        {/* Search */}
                        <button
                          type="submit"
                          disabled={isLoading || isSearching}
                          className="flex-shrink-0 flex items-center justify-center gap-2 px-5 py-3.5 bg-[rgb(20,113,76)] hover:bg-[rgb(16,89,60)] text-white font-bold text-sm rounded-xl transition-all transform hover:-translate-y-0.5 shadow-lg hover:shadow-xl disabled:opacity-80"
                        >
                          {isSearching ? (
                            <>
                              <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                              Searching...
                            </>
                          ) : (
                            <>
                              <Search className="w-5 h-5" />
                              Search
                            </>
                          )}
                        </button>
                      </div>
                    ) : (
                      // ROUND TRIP: Single row — From · Swap · To · Departure · Return · Passengers · Search
                      <div className="flex items-end gap-2">
                        {/* From */}
                        <div className="flex-1 min-w-0 space-y-1">
                          <label className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
                            From
                          </label>
                          <StationDropdown
                            stations={stations}
                            value={originId}
                            excludeId={destId}
                            placeholder="Departure"
                            recentIds={recentStationIds}
                            onSelect={(s) => {
                              setHasInteracted(true);
                              setValue("originStationId", s.id);
                              if (s.id) saveRecent(s.id);
                              clearErrors("originStationId");
                              clearErrors("destinationStationId");
                            }}
                            error={
                              hasInteracted
                                ? errors.originStationId?.message
                                : undefined
                            }
                            onOpen={scrollWidgetIntoView}
                          />
                          {hasInteracted && errors.originStationId && (
                            <p className="text-xs text-red-500">
                              {errors.originStationId.message}
                            </p>
                          )}
                        </div>
                        {/* Swap */}
                        <button
                          type="button"
                          onClick={handleSwap}
                          disabled={!originId || !destId}
                          className={`flex-shrink-0 mb-0.5 w-9 h-9 bg-gray-50 border-2 border-gray-200 rounded-full flex items-center justify-center hover:border-primary hover:bg-primary/5 transition-all disabled:opacity-30 ${swapping ? "rotate-180" : ""}`}
                        >
                          <ArrowLeftRight className="w-4 h-4 text-gray-500" />
                        </button>
                        {/* To */}
                        <div className="flex-1 min-w-0 space-y-1">
                          <label className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
                            To
                          </label>
                          <StationDropdown
                            stations={stations}
                            value={destId}
                            excludeId={originId}
                            placeholder="Destination"
                            recentIds={recentStationIds}
                            onSelect={(s) => {
                              setHasInteracted(true);
                              setValue("destinationStationId", s.id);
                              if (s.id) saveRecent(s.id);
                              clearErrors("destinationStationId");
                            }}
                            error={
                              hasInteracted
                                ? errors.destinationStationId?.message
                                : undefined
                            }
                            onOpen={scrollWidgetIntoView}
                          />
                          {hasInteracted && errors.destinationStationId && (
                            <p className="text-xs text-red-500">
                              {errors.destinationStationId.message}
                            </p>
                          )}
                        </div>
                        {/* Departure Date */}
                        <div className="w-40 flex-shrink-0 space-y-1">
                          <label className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
                            Departure
                          </label>
                          <ModernDatePicker
                            value={
                              departureDate
                                ? new Date(departureDate + "T00:00:00")
                                : undefined
                            }
                            onChange={(date) => {
                              setValue(
                                "departureDate",
                                `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`,
                              );
                              trigger("departureDate");
                              trigger("returnDate");
                            }}
                            minDate={new Date()}
                            placeholder="Departure date"
                          />
                          {errors.departureDate && (
                            <p className="text-xs text-red-500">
                              {errors.departureDate.message}
                            </p>
                          )}
                        </div>
                        {/* Return Date */}
                        <div className="w-40 flex-shrink-0 space-y-1">
                          <label className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
                            Return
                          </label>
                          <ModernDatePicker
                            value={
                              returnDate
                                ? new Date(returnDate + "T00:00:00")
                                : undefined
                            }
                            onChange={(date) => {
                              setValue(
                                "returnDate",
                                `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`,
                              );
                              trigger("returnDate");
                            }}
                            minDate={
                              departureDate
                                ? new Date(departureDate + "T00:00:00")
                                : new Date()
                            }
                            placeholder="Return date"
                          />
                          {errors.returnDate && (
                            <p className="text-xs text-red-500">
                              {errors.returnDate.message}
                            </p>
                          )}
                        </div>
                        {/* Passengers */}
                        <div className="w-44 flex-shrink-0 space-y-1">
                          <label className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
                            Passengers
                          </label>
                          <button
                            type="button"
                            onClick={() => setPassengerModalOpen(true)}
                            className={`w-full flex items-center justify-between px-3 py-3.5 border-2 rounded-xl bg-white dark:bg-gray-800 hover:border-gray-300 dark:hover:border-gray-600 transition-all ${
                              showNationalityError
                                ? "border-red-400"
                                : "border-gray-200 dark:border-gray-700"
                            }`}
                          >
                            <span className="flex items-center gap-1.5 text-sm font-medium text-gray-900 dark:text-white truncate">
                              <Users className="w-4 h-4 text-primary flex-shrink-0" />
                              {totalPassengers}{" "}
                              {totalPassengers === 1
                                ? "Passenger"
                                : "Passengers"}
                              {nationalityFlag(watch("nationality"))
                                ? ` · ${nationalityFlag(watch("nationality"))}`
                                : " · Nationality"}
                            </span>
                            <ChevronDown className="w-4 h-4 text-primary flex-shrink-0" />
                          </button>
                          {showNationalityError && (
                            <p className="text-xs text-red-500">
                              {errors.nationality?.message}
                            </p>
                          )}
                        </div>
                        {/* Search */}
                        <button
                          type="submit"
                          disabled={isLoading || isSearching}
                          className="flex-shrink-0 flex items-center justify-center gap-2 px-5 py-3.5 bg-[rgb(20,113,76)] hover:bg-[rgb(16,89,60)] text-white font-bold text-sm rounded-xl transition-all shadow-lg hover:shadow-xl disabled:opacity-80"
                        >
                          {isSearching ? (
                            <>
                              <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                              Searching...
                            </>
                          ) : (
                            <>
                              <Search className="w-5 h-5" />
                              Search
                            </>
                          )}
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </form>
          </div>
        </div>
      </section>

      <style jsx>{`
        @keyframes slide-up {
          from {
            transform: translateY(100%);
            opacity: 0;
          }
          to {
            transform: translateY(0);
            opacity: 1;
          }
        }
        .animate-slide-up {
          animation: slide-up 0.25s cubic-bezier(0.32, 0.72, 0, 1);
        }

        @keyframes fade-in-up {
          from {
            opacity: 0;
            transform: translateY(20px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
        .animate-fade-in-up {
          animation: fade-in-up 0.8s cubic-bezier(0.16, 1, 0.3, 1) forwards;
        }
        .animate-fade-in-up-delay {
          opacity: 0;
          animation: fade-in-up 0.8s cubic-bezier(0.16, 1, 0.3, 1) 0.2s forwards;
        }

        @keyframes bg-zoom {
          0% {
            transform: scale(1.08);
          }
          100% {
            transform: scale(1);
          }
        }
        .animate-bg-zoom {
          animation: bg-zoom 3s cubic-bezier(0.16, 1, 0.3, 1) forwards;
          will-change: transform;
        }
      `}</style>
    </div>
  );
}
