"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import {
  Bus,
  CalendarDays,
  Check,
  BedDouble,
  Box,
  Car,
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  ChevronUp,
  Clock3,
  Images,
  MapPin,
  Minus,
  Moon,
  Pencil,
  Plus,
  Route,
  Ship,
  Star,
  Sun,
  User,
  Users,
  Utensils,
  Wifi,
  X,
} from "lucide-react";
import { AiImage } from "@/components/AiImage";
import { CruiseCard } from "@/components/CruiseCard";
import type { CruiseDetail } from "@/data/cruise-detail";
import { cruiseImage } from "@/data/home";
import { checkoutBooking } from "@/lib/booking-api";
import type { DetailTour } from "@/lib/tours-api";

type CruiseView = CruiseDetail & {
  available_seats?: number;
};

type Props = {
  cruise: CruiseView | DetailTour;
  related: CruiseDetail[];
};

const gallerySeeds = [0, 1, 2, 3, 4, 5, 6, 7];
const facilityCards = [
  { label: "Accommodation", seed: 11 },
  { label: "Activity", seed: 22 },
  { label: "Bus transfer", seed: 33 },
  { label: "Food", seed: 44 },
  { label: "Overview", seed: 55 },
] as const;

type ContactField =
  | "name"
  | "pax"
  | "email"
  | "phone"
  | "pickup"
  | "departureDate"
  | "pickupBus"
  | "pickupAddress"
  | "dropoff"
  | "endDate"
  | "dropoffBus"
  | "dropoffAddress";

type ContactForm = Record<ContactField, string> & { messenger: string };

const contactFieldOrder: ContactField[] = [
  "name",
  "pax",
  "email",
  "phone",
  "pickup",
  "departureDate",
  "pickupBus",
  "pickupAddress",
  "dropoff",
  "endDate",
  "dropoffBus",
  "dropoffAddress",
];

type PaxCounts = { adult: number; child: number; infant: number };

function formatPaxLabel(adult: number, child: number, infant: number) {
  const adultLabel = adult === 1 ? "1 Adult" : `${adult} Adults`;
  return `${adultLabel} - ${child} Child - ${infant} Infant`;
}

function isValidEmail(value: string) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
}

const initialPaxCounts: PaxCounts = { adult: 2, child: 0, infant: 0 };

const initialContactForm: ContactForm = {
  name: "",
  pax: formatPaxLabel(initialPaxCounts.adult, initialPaxCounts.child, initialPaxCounts.infant),
  email: "",
  phone: "",
  pickup: "Hanoi Old Quarter",
  departureDate: "",
  pickupBus: "",
  pickupAddress: "",
  dropoff: "Hanoi Old Quarter",
  endDate: "",
  dropoffBus: "",
  dropoffAddress: "",
  messenger: "",
};

const contactErrorMessages: Record<ContactField, string> = {
  name: "Please enter your name",
  pax: "Please select number of passengers",
  email: "Please enter a valid email",
  phone: "Please enter your phone number",
  pickup: "Please select pick up location",
  departureDate: "Please select departure date",
  pickupBus: "Please select bus / time",
  pickupAddress: "Please select pick up address",
  dropoff: "Please select drop off location",
  endDate: "Please select end date",
  dropoffBus: "Please select bus / time",
  dropoffAddress: "Please select drop off address",
};

export function CruiseDetailView({ cruise, related }: Props) {
  const [tab, setTab] = useState<"overview" | "booking" | "faq">("overview");
  const [tourOption, setTourOption] = useState<"2d1n" | "3d2n">("2d1n");
  const [selectedRoom, setSelectedRoom] = useState(
    cruise.rooms.find((r) => r.pax === 2)?.id ?? cruise.rooms[0]?.id ?? "",
  );
  const [roomQty, setRoomQty] = useState<Record<string, number>>({});
  const [roomPaxFilter, setRoomPaxFilter] = useState<1 | 2 | 3 | 4>(2);
  const [roomSlide, setRoomSlide] = useState<Record<string, number>>({});
  const [bookingStep, setBookingStep] = useState(1);
  const [contactForm, setContactForm] = useState<ContactForm>(initialContactForm);
  const [contactErrors, setContactErrors] = useState<Partial<Record<ContactField, string>>>({});
  const [paxCounts, setPaxCounts] = useState<PaxCounts>(initialPaxCounts);
  const [paxOpen, setPaxOpen] = useState(false);
  const [stepsPinned, setStepsPinned] = useState(false);
  const [submittingBooking, setSubmittingBooking] = useState(false);
  const [bookingError, setBookingError] = useState("");
  const [openFaq, setOpenFaq] = useState<number | null>(0);
  const [galleryOpen, setGalleryOpen] = useState(false);
  const galleryScrollerRef = useRef<HTMLDivElement>(null);
  const bookingSentinelRef = useRef<HTMLDivElement>(null);
  const step3FormRef = useRef<HTMLFormElement>(null);
  const paxPickerRef = useRef<HTMLDivElement>(null);
  const paxTriggerRef = useRef<HTMLButtonElement>(null);
  const galleryDragRef = useRef({
    active: false,
    startX: 0,
    startScroll: 0,
    moved: false,
  });

  const paxLabel = contactForm.pax;
  const totalPax = paxCounts.adult + paxCounts.child + paxCounts.infant;
  const pickup = contactForm.pickup;
  const dropoff = contactForm.dropoff;

  const setPaxCount = (key: keyof PaxCounts, value: number) => {
    const nextValue = Math.max(0, Math.min(20, Number.isFinite(value) ? value : 0));
    const next = { ...paxCounts, [key]: nextValue };
    setPaxCounts(next);
    updateContactField("pax", formatPaxLabel(next.adult, next.child, next.infant));
  };

  const updateContactField = <K extends keyof ContactForm>(key: K, value: ContactForm[K]) => {
    setContactForm((prev) => ({ ...prev, [key]: value }));
    if (key !== "messenger" && contactErrors[key as ContactField]) {
      setContactErrors((prev) => {
        const next = { ...prev };
        delete next[key as ContactField];
        return next;
      });
    }
  };

  const validateContactForm = () => {
    const nextErrors: Partial<Record<ContactField, string>> = {};

    for (const field of contactFieldOrder) {
      const value = contactForm[field].trim();
      if (field === "email") {
        if (!value || !isValidEmail(value)) nextErrors.email = contactErrorMessages.email;
        continue;
      }
      if (field === "pax") {
        if (paxCounts.adult < 1) nextErrors.pax = contactErrorMessages.pax;
        continue;
      }
      if (!value) nextErrors[field] = contactErrorMessages[field];
    }

    setContactErrors(nextErrors);

    const firstInvalid = contactFieldOrder.find((field) => nextErrors[field]);
    if (firstInvalid) {
      setTab("booking");
      setBookingStep(3);
      if (firstInvalid === "pax") setPaxOpen(true);
      requestAnimationFrame(() => {
        step3FormRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
        if (firstInvalid === "pax") {
          paxTriggerRef.current?.focus();
          return;
        }
        const el = step3FormRef.current?.elements.namedItem(firstInvalid);
        if (el instanceof HTMLElement) el.focus();
      });
      return false;
    }

    return true;
  };

  const itinerary = tourOption === "2d1n" ? cruise.itinerary2d1n : cruise.itinerary3d2n;
  const filteredRooms = useMemo(
    () => cruise.rooms.filter((r) => r.pax === roomPaxFilter),
    [cruise.rooms, roomPaxFilter],
  );
  const room = cruise.rooms.find((r) => r.id === selectedRoom) ?? cruise.rooms[0];
  const selectedRoomsTotal = useMemo(() => {
    return cruise.rooms.reduce((sum, r) => {
      const qty = roomQty[r.id] ?? 0;
      return sum + qty * r.price;
    }, 0);
  }, [cruise.rooms, roomQty]);
  const gallery = useMemo(
    () =>
      gallerySeeds.map((i) =>
        cruiseImage(
          { ...cruise, seed: cruise.seed + i, prompt: `${cruise.prompt} gallery ${i}` },
          "wide",
        ),
      ),
    [cruise],
  );

  useEffect(() => {
    const sentinel = bookingSentinelRef.current;
    if (!sentinel) return;
    const onScroll = () => {
      const top = sentinel.getBoundingClientRect().top;
      // When booking reaches under sticky header (~84 + subnav), pin steps into header
      setStepsPinned(top <= 148);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, []);

  useEffect(() => {
    if (!paxOpen) return;
    const onPointerDown = (e: MouseEvent) => {
      if (!paxPickerRef.current?.contains(e.target as Node)) setPaxOpen(false);
    };
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") setPaxOpen(false);
    };
    document.addEventListener("mousedown", onPointerDown);
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("mousedown", onPointerDown);
      document.removeEventListener("keydown", onKeyDown);
    };
  }, [paxOpen]);

  useEffect(() => {
    const el = galleryScrollerRef.current;
    if (!el) return;

    const onPointerDown = (e: PointerEvent) => {
      if (e.pointerType === "touch") return;
      galleryDragRef.current = {
        active: true,
        startX: e.clientX,
        startScroll: el.scrollLeft,
        moved: false,
      };
      el.setPointerCapture(e.pointerId);
      el.classList.add("cursor-grabbing");
      el.classList.remove("cursor-grab");
    };

    const onPointerMove = (e: PointerEvent) => {
      const d = galleryDragRef.current;
      if (!d.active) return;
      const dx = e.clientX - d.startX;
      if (Math.abs(dx) > 4) d.moved = true;
      el.scrollLeft = d.startScroll - dx;
    };

    const endDrag = (e: PointerEvent) => {
      const d = galleryDragRef.current;
      if (!d.active) return;
      d.active = false;
      el.releasePointerCapture(e.pointerId);
      el.classList.remove("cursor-grabbing");
      el.classList.add("cursor-grab");
    };

    const onClickCapture = (e: MouseEvent) => {
      if (galleryDragRef.current.moved) {
        e.preventDefault();
        e.stopPropagation();
        galleryDragRef.current.moved = false;
      }
    };

    el.addEventListener("pointerdown", onPointerDown);
    el.addEventListener("pointermove", onPointerMove);
    el.addEventListener("pointerup", endDrag);
    el.addEventListener("pointercancel", endDrag);
    el.addEventListener("click", onClickCapture, true);

    return () => {
      el.removeEventListener("pointerdown", onPointerDown);
      el.removeEventListener("pointermove", onPointerMove);
      el.removeEventListener("pointerup", endDrag);
      el.removeEventListener("pointercancel", endDrag);
      el.removeEventListener("click", onClickCapture, true);
    };
  }, []);

  const scrollTo = (id: string) => {
    document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  const tourLabel = tourOption === "2d1n" ? "2 Days 1 Night" : "3 Days 2 Nights";
  const totalPrice = selectedRoomsTotal || room?.price || cruise.price || 0;
  const availableSeats = cruise.available_seats ?? 0;
  const seatsNeeded = paxCounts.adult + paxCounts.child;
  const tourClosed = availableSeats <= 0;

  const submitBooking = async () => {
    if (submittingBooking) return;
    if (tourClosed) {
      setBookingError("This tour is fully booked and closed.");
      return;
    }
    if (!validateContactForm()) return;
    if (seatsNeeded > availableSeats) {
      setBookingError(`Only ${availableSeats} seat(s) left for this tour.`);
      setTab("booking");
      setBookingStep(3);
      return;
    }

    const rooms = cruise.rooms
      .filter((r) => (roomQty[r.id] ?? 0) > 0)
      .map((r) => ({
        id: r.id,
        name: r.name,
        qty: roomQty[r.id] ?? 0,
        pax: r.pax,
        price: r.price,
      }));

    setSubmittingBooking(true);
    setBookingError("");
    try {
      const tourId = Number.parseInt(String(cruise.id), 10);
      const checkout = await checkoutBooking({
        tour_id: Number.isFinite(tourId) ? tourId : undefined,
        tour_slug: cruise.slug,
        tour_name: cruise.name,
        tour_option: tourLabel,
        rooms,
        name: contactForm.name.trim(),
        email: contactForm.email.trim(),
        phone: contactForm.phone.trim(),
        adults: paxCounts.adult,
        children: paxCounts.child,
        infants: paxCounts.infant,
        pax_label: paxLabel,
        pickup: contactForm.pickup,
        departure_date: contactForm.departureDate,
        pickup_bus: contactForm.pickupBus,
        pickup_address: contactForm.pickupAddress,
        dropoff: contactForm.dropoff,
        end_date: contactForm.endDate,
        dropoff_bus: contactForm.dropoffBus,
        dropoff_address: contactForm.dropoffAddress,
        messenger: contactForm.messenger.trim() || undefined,
        total_price: totalPrice,
      });
      window.location.href = checkout.payment_url;
    } catch (err) {
      setBookingError(err instanceof Error ? err.message : "Unable to start payment");
      setTab("booking");
      setBookingStep(3);
      setSubmittingBooking(false);
    }
  };

  const goTab = (key: "overview" | "booking" | "faq") => {
    setTab(key);
    scrollTo(key);
  };

  const changeRoomQty = (id: string, delta: number) => {
    setRoomQty((prev) => {
      const next = Math.max(0, (prev[id] ?? 0) + delta);
      return { ...prev, [id]: next };
    });
    setSelectedRoom(id);
    setBookingStep(2);
  };

  const roomImages = (roomId: string, seed: number) =>
    [0, 1, 2].map((i) =>
      cruiseImage(
        {
          ...cruise,
          seed: cruise.seed + seed + i * 17,
          prompt: `${cruise.prompt} luxury cruise cabin interior ${roomId} ${i}`,
        },
        "wide",
      ),
    );

  const bookingSteps = [
    { n: 1, label: "Option" },
    { n: 2, label: "Choose rooms" },
    { n: 3, label: "Fill pick up" },
    { n: 4, label: "Payment" },
  ] as const;

  const StepsBar = ({ compact = false }: { compact?: boolean }) => (
    <div className={`flex flex-wrap items-center ${compact ? "gap-1.5 sm:gap-2" : "gap-2 sm:gap-3"}`}>
      {bookingSteps.map((step, i) => {
        const active = bookingStep >= step.n;
        const current = bookingStep === step.n;
        return (
          <div key={step.n} className="flex items-center gap-1.5 sm:gap-2">
            <button
              type="button"
              onClick={() => {
                setBookingStep(step.n);
                setTab("booking");
                if (compact) scrollTo("booking");
              }}
              className={`inline-flex items-center gap-2 text-sm font-semibold transition ${
                active ? "text-accent" : "text-muted"
              }`}
            >
              <span
                className={`grid h-7 w-7 place-items-center rounded-full text-[11px] font-bold ${
                  active ? "bg-accent text-white" : "bg-[#d7e2e7] text-white"
                } ${current ? "ring-2 ring-accent/30" : ""}`}
              >
                {String(step.n).padStart(2, "0")}
              </span>
              <span className={compact ? "hidden md:inline" : ""}>{step.label}</span>
            </button>
            {i < bookingSteps.length - 1 && (
              <span
                className={`hidden h-px w-6 sm:block sm:w-8 ${
                  bookingStep > step.n ? "bg-accent" : "border-t border-dashed border-[#c5ced3]"
                }`}
              />
            )}
          </div>
        );
      })}
    </div>
  );

  return (
    <>
      {/* Gallery — full-width horizontal slider */}
      <section className="relative w-full bg-white">
        <div
          ref={galleryScrollerRef}
          className="flex w-full cursor-grab gap-1 overflow-x-auto overscroll-x-contain [-ms-overflow-style:none] [scrollbar-width:none] [scroll-snap-type:x_mandatory] [-webkit-overflow-scrolling:touch] [&::-webkit-scrollbar]:hidden"
        >
          {gallery.map((src, i) => (
            <button
              key={src + i}
              type="button"
              onClick={() => setGalleryOpen(true)}
              className="relative w-[88vw] shrink-0 overflow-hidden [scroll-snap-align:start] sm:w-[46vw] lg:w-[33.2vw]"
            >
              <AiImage
                src={src}
                alt={`${cruise.name} photo ${i + 1}`}
                className="aspect-[16/10] w-full sm:aspect-[5/4]"
              />
            </button>
          ))}
        </div>
        <button
          type="button"
          onClick={() => setGalleryOpen(true)}
          className="absolute right-4 bottom-4 z-10 inline-flex items-center gap-2 rounded-lg bg-white px-3.5 py-2 text-xs font-bold text-brand-deep shadow sm:right-6"
        >
          <Images className="h-4 w-4" />
          Gallery
        </button>
      </section>

      {/* Sticky subnav — swaps to booking steps when scrolled into booking */}
      <div className="sticky top-[92px] z-40 border-b border-[#e8eef1] bg-white/95 backdrop-blur">
        <div className="mx-auto flex w-[min(1180px,calc(100%-2rem))] flex-wrap items-center justify-between gap-3 py-3">
          {stepsPinned ? (
            <>
              <StepsBar compact />
              <div className="flex items-center gap-3 text-sm">
                <p>
                  <span className="text-muted">From </span>
                  <span className="text-lg font-bold text-[#e8845a]">
                    {totalPrice || "Updating"}
                    {totalPrice ? "$" : ""}
                  </span>
                </p>
                <button
                  type="button"
                  onClick={() => scrollTo("booking")}
                  className="hidden rounded-full bg-accent px-4 py-2 text-xs font-bold text-white sm:inline-flex"
                >
                  Book now
                </button>
              </div>
            </>
          ) : (
            <>
              <div className="flex items-center gap-6">
                {(
                  [
                    ["overview", "Overview"],
                    ["booking", "Booking"],
                    ["faq", "FAQ"],
                  ] as const
                ).map(([key, label]) => (
                  <button
                    key={key}
                    type="button"
                    onClick={() => goTab(key)}
                    className={`relative pb-1 text-sm font-bold transition ${
                      tab === key ? "text-[#1c2b33]" : "text-muted hover:text-brand-deep"
                    }`}
                  >
                    {label}
                    {tab === key && (
                      <span className="absolute inset-x-0 -bottom-3 h-[3px] rounded-full bg-[#e8845a]" />
                    )}
                  </button>
                ))}
              </div>
              <div className="flex items-center gap-4 text-sm">
                <p>
                  <span className="text-muted">From </span>
                  <span className="text-lg font-bold text-[#e8845a]">
                    {cruise.price == null ? "Updating" : `${cruise.price}$`}
                  </span>
                </p>
                <button
                  type="button"
                  onClick={() => {
                    window.dispatchEvent(new CustomEvent("vnsails:open-contact"));
                  }}
                  className="inline-flex items-center gap-2 font-semibold text-brand-deep"
                >
                  Need Help? <span className="text-accent underline">Contact us</span>
                  <span className="grid h-8 w-8 place-items-center overflow-hidden rounded-full bg-accent/15 text-xs font-bold text-accent">
                    VS
                  </span>
                </button>
              </div>
            </>
          )}
        </div>
      </div>

      {/* Overview */}
      <section id="overview" className="scroll-mt-36 bg-white text-brand-deep">
        <div className="mx-auto w-[min(1180px,calc(100%-2rem))] py-10 sm:py-12">
          <h1 className="font-[family-name:var(--font-display)] text-3xl font-bold sm:text-4xl">
            {cruise.name}
          </h1>
          <div className="mt-2 flex items-center gap-1">
            {Array.from({ length: 5 }).map((_, i) => (
              <Star
                key={i}
                className={`h-4 w-4 ${i < cruise.rating ? "text-amber-400" : "text-[#d7e2e7]"}`}
                fill="currentColor"
                strokeWidth={0}
              />
            ))}
          </div>

          <div className="mt-8 grid gap-5 lg:grid-cols-[1.4fr_0.9fr]">
            <div className="rounded-[28px] bg-[#7ec8c4] p-6 text-[#12343a] sm:p-8">
              <div className="flex items-start justify-between gap-3">
                <h2 className="text-xl font-extrabold tracking-wide uppercase">At a glance</h2>
                <span className="inline-flex items-center gap-1.5 rounded-full bg-white/75 px-3 py-1 text-xs font-semibold">
                  {cruise.duration === "Day tour" ? (
                    <Sun className="h-3.5 w-3.5" />
                  ) : (
                    <Moon className="h-3.5 w-3.5" fill="currentColor" strokeWidth={0} />
                  )}
                  {cruise.duration}
                </span>
              </div>
              <ul className="mt-6 space-y-3.5 text-sm sm:text-[15px]">
                <li className="flex gap-3">
                  <MapPin className="mt-0.5 h-4 w-4 shrink-0 text-accent" />
                  <span>Place to visit: {cruise.bay}</span>
                </li>
                <li className="flex gap-3">
                  <Ship className="mt-0.5 h-4 w-4 shrink-0 text-accent" />
                  <span>Cabin: {cruise.cabins}</span>
                </li>
                <li className="flex gap-3">
                  <Users className="mt-0.5 h-4 w-4 shrink-0 text-accent" />
                  <span>
                    Seats left:{" "}
                    <strong>{availableSeats > 0 ? availableSeats : "Sold out"}</strong>
                  </span>
                </li>
                <li className="flex gap-3">
                  <Route className="mt-0.5 h-4 w-4 shrink-0 text-accent" />
                  <span>Sea route: {cruise.seaRoute}</span>
                </li>
                <li className="flex gap-3">
                  <Users className="mt-0.5 h-4 w-4 shrink-0 text-accent" />
                  <span>Suitable for: {cruise.types.join(", ")}, Groups</span>
                </li>
                <li className="flex gap-3">
                  <Bus className="mt-0.5 h-4 w-4 shrink-0 text-accent" />
                  <span>We pick up: {cruise.pickup}</span>
                </li>
              </ul>
              <div className="mt-7 flex justify-end">
                <button
                  type="button"
                  className="inline-flex items-center gap-2 rounded-full bg-accent px-4 py-2.5 text-sm font-bold text-white"
                >
                  View cruise travel map
                  <ChevronRight className="h-4 w-4" />
                </button>
              </div>
            </div>

            <div className="space-y-4">
              <article className="rounded-[28px] bg-white p-6 text-brand-deep shadow-lg">
                <div className="flex items-center gap-2">
                  <span className="grid h-7 w-7 place-items-center rounded-full bg-[#00aa6c] text-[10px] font-black text-white">
                    TA
                  </span>
                  <p className="text-xs font-bold tracking-[0.14em] text-muted uppercase">
                    Tripadvisor
                  </p>
                </div>
                <h3 className="mt-2 text-sm font-bold uppercase">{cruise.name}</h3>
                <div className="mt-3 flex items-center gap-1.5">
                  {Array.from({ length: 5 }).map((_, i) => (
                    <span key={i} className="h-3.5 w-3.5 rounded-full bg-[#00aa6c]" />
                  ))}
                </div>
                <p className="mt-2 text-sm font-bold">{cruise.reviews} REVIEW</p>
                <p className="mt-3 text-sm leading-relaxed text-muted">
                  With a combined experience of over twenty years in luxury cruising, this vessel is
                  built to high international standards for comfort and safety on {cruise.bay}.
                </p>
                <button
                  type="button"
                  onClick={() => goTab("faq")}
                  className="mt-4 text-sm font-semibold text-accent underline"
                >
                  Read reviews
                </button>
              </article>

              <article className="rounded-[28px] bg-white p-6 text-brand-deep shadow-lg">
                <h3 className="font-bold">Facilities</h3>
                <ul className="mt-3 space-y-2.5 text-sm text-muted">
                  {cruise.facilities.slice(0, 6).map((item) => (
                    <li key={item} className="flex items-center gap-2">
                      {item.toLowerCase().includes("wifi") ? (
                        <Wifi className="h-4 w-4 text-accent" />
                      ) : item.toLowerCase().includes("food") ||
                        item.toLowerCase().includes("restaurant") ? (
                        <Utensils className="h-4 w-4 text-accent" />
                      ) : (
                        <Check className="h-4 w-4 text-accent" />
                      )}
                      {item}
                    </li>
                  ))}
                </ul>
              </article>
            </div>
          </div>

          <div className="mt-10 grid gap-5 lg:grid-cols-2">
            <article className="rounded-2xl border border-[var(--line)] bg-[#f4fbfb] p-5">
              <h3 className="font-bold text-accent">Tour included</h3>
              <ul className="mt-3 space-y-2">
                {cruise.included.slice(0, 8).map((item) => (
                  <li key={item} className="flex gap-2 text-sm text-muted">
                    <Check className="mt-0.5 h-4 w-4 shrink-0 text-[#e8845a]" />
                    {item}
                  </li>
                ))}
              </ul>
            </article>
            <article className="rounded-2xl border border-[var(--line)] bg-white p-5 text-brand-deep">
              <h3 className="font-bold">Tour does not include</h3>
              <ul className="mt-3 space-y-2">
                {cruise.excluded.map((item) => (
                  <li key={item} className="flex gap-2 text-sm text-muted">
                    <X className="mt-0.5 h-4 w-4 shrink-0 text-[#e8845a]" />
                    {item}
                  </li>
                ))}
              </ul>
            </article>
          </div>

          <div className="mt-10">
            <h2 className="text-xl font-semibold text-brand-deep">Overview</h2>
            <p className="mt-3 max-w-3xl text-sm leading-relaxed text-muted sm:text-base">
              {cruise.overview}
            </p>
            <h3 className="mt-8 text-lg font-semibold text-brand-deep">Highlights</h3>
            <ul className="mt-3 space-y-2">
              {cruise.highlights.map((item) => (
                <li key={item} className="flex gap-2 text-sm text-muted">
                  <Check className="mt-0.5 h-4 w-4 shrink-0 text-[#e8845a]" />
                  {item}
                </li>
              ))}
            </ul>
          </div>

          <div className="mt-10 flex gap-3 overflow-x-auto pb-1 [-ms-overflow-style:none] [scrollbar-width:none] md:grid md:grid-cols-5 md:overflow-visible [&::-webkit-scrollbar]:hidden">
            {facilityCards.map((card) => (
              <div
                key={card.label}
                className="relative h-[240px] w-[150px] shrink-0 overflow-hidden rounded-2xl md:w-auto"
              >
                <AiImage
                  src={cruiseImage(
                    {
                      ...cruise,
                      seed: cruise.seed + card.seed,
                      prompt: `${card.label} ${cruise.prompt}`,
                    },
                    "card",
                  )}
                  alt={card.label}
                  className="h-full w-full"
                />
                <div className="absolute inset-0 bg-gradient-to-t from-black/75 via-black/10 to-transparent" />
                <p className="absolute inset-x-0 bottom-3 text-center text-sm font-semibold text-white">
                  {card.label}
                </p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Booking */}
      <section id="booking" className="scroll-mt-40 bg-white py-10 sm:py-12">
        <div ref={bookingSentinelRef} className="h-px w-full" aria-hidden />
        <div className="mx-auto w-[min(1180px,calc(100%-2rem))]">
          {!stepsPinned && (
            <div className="mb-8">
              <StepsBar />
            </div>
          )}

          <div className="grid gap-6 lg:grid-cols-[1.35fr_0.85fr]">
            <div className="space-y-6">
              {/* Step 1 */}
              <div className="overflow-hidden rounded-2xl border border-[var(--line)] bg-white">
                <div className="flex flex-wrap items-center justify-between gap-3 bg-[#dff3f2] px-5 py-4 sm:px-6">
                  <h2 className="inline-flex items-center gap-2 text-base font-bold text-brand-deep">
                    STEP 1
                    <MapPin className="h-4 w-4 text-accent" fill="currentColor" strokeWidth={0} />
                    Choose your tour
                  </h2>
                  <div className="flex flex-wrap gap-3">
                    {(
                      [
                        ["2d1n", "2 Days 1 Night"],
                        ["3d2n", "3 Days 2 Nights"],
                      ] as const
                    ).map(([key, label]) => (
                      <button
                        key={key}
                        type="button"
                        onClick={() => {
                          setTourOption(key);
                          setBookingStep(1);
                        }}
                        className={`inline-flex items-center gap-2 text-sm font-semibold ${
                          tourOption === key ? "text-accent" : "text-muted"
                        }`}
                      >
                        <span
                          className={`grid h-5 w-5 place-items-center rounded-full border-2 ${
                            tourOption === key
                              ? "border-accent bg-accent text-white"
                              : "border-[#c5ced3]"
                          }`}
                        >
                          {tourOption === key && <Check className="h-3 w-3" strokeWidth={3} />}
                        </span>
                        {label}
                      </button>
                    ))}
                  </div>
                </div>
                <div className="space-y-4 p-5 sm:p-6">
                  {itinerary.map((day) => (
                    <article key={day.title}>
                      <h3 className="text-base font-bold text-brand-deep">{day.title}</h3>
                      <ul className="mt-3 space-y-2.5">
                        {day.items.map((item) => (
                          <li key={item} className="text-sm leading-relaxed text-muted">
                            {item}
                          </li>
                        ))}
                      </ul>
                    </article>
                  ))}
                  <button
                    type="button"
                    onClick={() => setBookingStep(2)}
                    className="btn-accent mt-2 px-5 py-2.5 text-sm"
                  >
                    Continue to rooms
                  </button>
                </div>
              </div>

              {/* Step 2 rooms */}
              <div className="overflow-hidden rounded-2xl border border-[var(--line)] bg-white shadow-[0_8px_24px_rgba(13,58,77,0.05)]">
                <div className="flex flex-wrap items-center justify-between gap-3 bg-[#dff3f2] px-5 py-4 sm:px-6">
                  <h2 className="inline-flex items-center gap-2 text-base font-bold text-brand-deep">
                    <span className="text-accent">STEP 2</span>
                    <Ship className="h-4 w-4 text-accent" />
                    Choose your room on cruise
                    <span className="text-[#e8845a]">*</span>
                  </h2>
                  <div className="flex items-center gap-2">
                    <p className="text-[11px] font-bold tracking-wide text-brand-deep uppercase">
                      {cruise.name}
                    </p>
                    <span className="inline-flex items-center gap-1 rounded-md bg-[#e8845a] px-1.5 py-0.5 text-[11px] font-bold text-white">
                      {cruise.rating}
                      <Star className="h-3 w-3" fill="currentColor" strokeWidth={0} />
                    </span>
                  </div>
                </div>

                <div className="flex flex-wrap gap-2 border-b border-[var(--line)] px-5 py-3 sm:px-6">
                  {([1, 2, 3, 4] as const).map((pax) => {
                    const active = roomPaxFilter === pax;
                    return (
                      <button
                        key={pax}
                        type="button"
                        onClick={() => {
                          setRoomPaxFilter(pax);
                          setBookingStep(2);
                          const first = cruise.rooms.find((r) => r.pax === pax);
                          if (first) setSelectedRoom(first.id);
                        }}
                        className={`inline-flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-semibold transition ${
                          active
                            ? "bg-accent text-white"
                            : "text-brand-deep hover:bg-[#f3fafc]"
                        }`}
                      >
                        <User className="h-3.5 w-3.5" />
                        {pax} pax/Room
                      </button>
                    );
                  })}
                </div>

                <div className="p-5 sm:p-6">
                  <div className="mb-4 flex flex-wrap items-center justify-between gap-2">
                    <p className="inline-flex items-center gap-2 text-sm font-bold text-brand-deep">
                      <Users className="h-4 w-4 text-accent" />
                      {roomPaxFilter} pax/Room
                    </p>
                    <span className="rounded-full bg-[#eef2f3] px-3 py-1 text-xs font-semibold text-muted">
                      {tourLabel}
                    </span>
                  </div>

                  {filteredRooms.length === 0 ? (
                    <p className="rounded-xl border border-dashed border-[var(--line)] px-4 py-10 text-center text-sm text-muted">
                      No rooms available for {roomPaxFilter} pax.
                    </p>
                  ) : (
                    <div className="grid gap-4 md:grid-cols-2">
                      {filteredRooms.map((option, idx) => {
                        const imgs = roomImages(option.id, idx * 40 + option.pax * 9);
                        const slide = roomSlide[option.id] ?? 0;
                        const qty = roomQty[option.id] ?? 0;
                        const active = selectedRoom === option.id || qty > 0;
                        return (
                          <article
                            key={option.id}
                            className={`overflow-hidden rounded-2xl border transition ${
                              active ? "border-accent shadow-[0_8px_24px_rgba(43,152,186,0.12)]" : "border-[var(--line)]"
                            }`}
                          >
                            <div className="relative aspect-[16/11] bg-[#e8f2f4]">
                              <AiImage
                                src={imgs[slide] ?? imgs[0]}
                                alt={option.name}
                                className="h-full w-full"
                              />
                              <button
                                type="button"
                                aria-label="Previous photo"
                                onClick={() =>
                                  setRoomSlide((prev) => ({
                                    ...prev,
                                    [option.id]: (slide - 1 + imgs.length) % imgs.length,
                                  }))
                                }
                                className="absolute top-1/2 left-2 grid h-8 w-8 -translate-y-1/2 place-items-center rounded-full bg-black/45 text-white"
                              >
                                <ChevronLeft className="h-4 w-4" />
                              </button>
                              <button
                                type="button"
                                aria-label="Next photo"
                                onClick={() =>
                                  setRoomSlide((prev) => ({
                                    ...prev,
                                    [option.id]: (slide + 1) % imgs.length,
                                  }))
                                }
                                className="absolute top-1/2 right-2 grid h-8 w-8 -translate-y-1/2 place-items-center rounded-full bg-black/45 text-white"
                              >
                                <ChevronRight className="h-4 w-4" />
                              </button>
                              <div className="absolute inset-x-0 bottom-2 flex justify-center gap-1.5">
                                {imgs.map((_, i) => (
                                  <span
                                    key={i}
                                    className={`h-1.5 w-1.5 rounded-full ${
                                      i === slide ? "bg-white" : "bg-white/45"
                                    }`}
                                  />
                                ))}
                              </div>
                            </div>

                            <div className="p-4">
                              <h3 className="text-base font-bold text-brand-deep">{option.name}</h3>
                              <div className="mt-2 flex flex-wrap gap-3 text-xs text-muted">
                                <span className="inline-flex items-center gap-1">
                                  <User className="h-3.5 w-3.5" />
                                  {option.pax} pax
                                </span>
                                <span className="inline-flex items-center gap-1">
                                  <Box className="h-3.5 w-3.5" />
                                  {option.size}
                                </span>
                                <span className="inline-flex items-center gap-1">
                                  <BedDouble className="h-3.5 w-3.5" />
                                  {option.feature}
                                </span>
                              </div>

                              <div className="mt-4 flex items-center justify-between gap-3">
                                <div className="inline-flex items-center overflow-hidden rounded-lg bg-[#eef2f3]">
                                  <button
                                    type="button"
                                    aria-label="Decrease rooms"
                                    onClick={() => changeRoomQty(option.id, -1)}
                                    className="grid h-9 w-9 place-items-center text-brand-deep hover:bg-[#e2e8ea]"
                                  >
                                    <Minus className="h-4 w-4" />
                                  </button>
                                  <span className="min-w-[4.5rem] text-center text-sm font-semibold text-brand-deep">
                                    {qty} Room
                                  </span>
                                  <button
                                    type="button"
                                    aria-label="Increase rooms"
                                    onClick={() => changeRoomQty(option.id, 1)}
                                    className="grid h-9 w-9 place-items-center text-brand-deep hover:bg-[#e2e8ea]"
                                  >
                                    <Plus className="h-4 w-4" />
                                  </button>
                                </div>
                                <p className="text-right">
                                  <span className="text-lg font-bold text-[#e8845a]">
                                    {option.price}$
                                  </span>{" "}
                                  <span className="text-xs text-muted">/pax</span>
                                </p>
                              </div>
                            </div>
                          </article>
                        );
                      })}
                    </div>
                  )}

                  <button
                    type="button"
                    onClick={() => setBookingStep(3)}
                    className="btn-accent mt-5 px-5 py-2.5 text-sm"
                  >
                    Continue to pickup
                  </button>
                </div>
              </div>

              {/* Step 3 form */}
              <form
                ref={step3FormRef}
                noValidate
                className="overflow-hidden rounded-2xl border border-[var(--line)] bg-white shadow-[0_8px_24px_rgba(13,58,77,0.05)]"
                onSubmit={(e) => {
                  e.preventDefault();
                  void submitBooking();
                }}
              >
                <div className="bg-[#dff3f2] px-5 py-4 sm:px-6">
                  <h2 className="text-base font-bold text-brand-deep">
                    <span className="text-accent">STEP 3</span> Enter contact and pick up point
                  </h2>
                </div>

                <div className="space-y-5 p-5 sm:p-6">
                  <div className="grid gap-4 md:grid-cols-2">
                    <label className="block text-sm">
                      <span className="mb-1.5 block font-semibold text-brand-deep">
                        Your Name <span className="text-[#e8845a]">*</span>
                      </span>
                      <input
                        name="name"
                        value={contactForm.name}
                        onChange={(e) => updateContactField("name", e.target.value)}
                        placeholder="Eg. Kylan"
                        aria-invalid={Boolean(contactErrors.name)}
                        className={`h-11 w-full rounded-lg border bg-white px-3 outline-none focus:border-accent ${
                          contactErrors.name ? "border-red-400" : "border-[var(--line)]"
                        }`}
                      />
                      {contactErrors.name && (
                        <span className="mt-1 block text-xs font-medium text-red-500">
                          {contactErrors.name}
                        </span>
                      )}
                    </label>
                    <div className="block text-sm">
                      <span className="mb-1.5 block font-semibold text-brand-deep">
                        No of Pax <span className="text-[#e8845a]">*</span>
                      </span>
                      <div ref={paxPickerRef} className="relative">
                        <input type="hidden" name="pax" value={contactForm.pax} />
                        <button
                          ref={paxTriggerRef}
                          type="button"
                          aria-expanded={paxOpen}
                          aria-haspopup="dialog"
                          aria-invalid={Boolean(contactErrors.pax)}
                          onClick={() => setPaxOpen((open) => !open)}
                          className={`flex h-11 w-full items-center rounded-lg border bg-white text-left outline-none focus:border-accent ${
                            contactErrors.pax ? "border-red-400" : "border-[var(--line)]"
                          }`}
                        >
                          <span className="min-w-0 flex-1 truncate px-3 text-sm font-semibold text-brand-deep">
                            {paxLabel}
                          </span>
                          <span className="flex h-full w-11 shrink-0 items-center justify-center border-l border-[var(--line)] text-muted">
                            <User className="h-4 w-4" />
                          </span>
                        </button>

                        {paxOpen && (
                          <div className="absolute left-0 z-30 mt-2 w-[min(100%,280px)] rounded-xl border border-[#e6ecef] bg-white p-4 shadow-[0_12px_28px_rgba(13,58,77,0.12)]">
                            {(
                              [
                                { key: "adult", label: "Adult (> 11)" },
                                { key: "child", label: "Child (5 - 11)" },
                                { key: "infant", label: "Infant (0 - 4)" },
                              ] as const
                            ).map((row) => (
                              <div
                                key={row.key}
                                className="flex items-center justify-between gap-3 py-2 first:pt-0 last:pb-0"
                              >
                                <span className="text-sm font-medium text-brand-deep">
                                  {row.label}
                                </span>
                                <div className="flex h-9 w-[72px] overflow-hidden rounded-md border border-[var(--line)] bg-white">
                                  <input
                                    type="number"
                                    min={0}
                                    max={20}
                                    value={paxCounts[row.key]}
                                    onChange={(e) =>
                                      setPaxCount(row.key, Number.parseInt(e.target.value || "0", 10))
                                    }
                                    className="h-full w-full border-0 bg-transparent px-2 text-center text-sm font-semibold text-brand-deep outline-none [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
                                  />
                                  <div className="flex w-6 shrink-0 flex-col border-l border-[var(--line)]">
                                    <button
                                      type="button"
                                      aria-label={`Increase ${row.label}`}
                                      onClick={() => setPaxCount(row.key, paxCounts[row.key] + 1)}
                                      className="flex flex-1 items-center justify-center text-muted hover:bg-[#f3f6f7] hover:text-brand-deep"
                                    >
                                      <ChevronUp className="h-3 w-3" />
                                    </button>
                                    <button
                                      type="button"
                                      aria-label={`Decrease ${row.label}`}
                                      onClick={() => setPaxCount(row.key, paxCounts[row.key] - 1)}
                                      className="flex flex-1 items-center justify-center border-t border-[var(--line)] text-muted hover:bg-[#f3f6f7] hover:text-brand-deep"
                                    >
                                      <ChevronDown className="h-3 w-3" />
                                    </button>
                                  </div>
                                </div>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                      {contactErrors.pax && (
                        <span className="mt-1 block text-xs font-medium text-red-500">
                          {contactErrors.pax}
                        </span>
                      )}
                    </div>
                    <label className="block text-sm">
                      <span className="mb-1.5 block font-semibold text-brand-deep">
                        Email <span className="text-[#e8845a]">*</span>
                      </span>
                      <input
                        name="email"
                        type="email"
                        value={contactForm.email}
                        onChange={(e) => updateContactField("email", e.target.value)}
                        placeholder="Eg. you@email.com"
                        aria-invalid={Boolean(contactErrors.email)}
                        className={`h-11 w-full rounded-lg border bg-white px-3 outline-none focus:border-accent ${
                          contactErrors.email ? "border-red-400" : "border-[var(--line)]"
                        }`}
                      />
                      {contactErrors.email && (
                        <span className="mt-1 block text-xs font-medium text-red-500">
                          {contactErrors.email}
                        </span>
                      )}
                    </label>
                    <label className="block text-sm">
                      <span className="mb-1.5 block font-semibold text-brand-deep">
                        Phone (WhatsApp) <span className="text-[#e8845a]">*</span>
                      </span>
                      <input
                        name="phone"
                        value={contactForm.phone}
                        onChange={(e) => updateContactField("phone", e.target.value)}
                        placeholder="Eg. 928-338-843"
                        aria-invalid={Boolean(contactErrors.phone)}
                        className={`h-11 w-full rounded-lg border bg-white px-3 outline-none focus:border-accent ${
                          contactErrors.phone ? "border-red-400" : "border-[var(--line)]"
                        }`}
                      />
                      {contactErrors.phone && (
                        <span className="mt-1 block text-xs font-medium text-red-500">
                          {contactErrors.phone}
                        </span>
                      )}
                    </label>
                  </div>

                  {/* Pick up box */}
                  <div className="rounded-2xl bg-[#dff3f2] p-4 sm:p-5">
                    <div className="grid gap-4 md:grid-cols-3">
                      <label className="block text-sm">
                        <span className="mb-1.5 block font-semibold text-brand-deep">
                          Pick up to cruise <span className="text-[#e8845a]">*</span>
                        </span>
                        <select
                          name="pickup"
                          value={contactForm.pickup}
                          onChange={(e) => updateContactField("pickup", e.target.value)}
                          aria-invalid={Boolean(contactErrors.pickup)}
                          className={`h-11 w-full rounded-lg border bg-white px-3 outline-none focus:border-accent ${
                            contactErrors.pickup ? "border-red-400" : "border-[var(--line)]"
                          }`}
                        >
                          <option value="">Select pick up *</option>
                          <option value="Hanoi Old Quarter">Hanoi Old Quarter</option>
                          <option value="Ninh Binh">Ninh Binh</option>
                          <option value="Halong City">Halong City</option>
                        </select>
                        {contactErrors.pickup && (
                          <span className="mt-1 block text-xs font-medium text-red-500">
                            {contactErrors.pickup}
                          </span>
                        )}
                      </label>
                      <label className="block text-sm">
                        <span className="mb-1.5 block font-semibold text-brand-deep">
                          Departure date <span className="text-[#e8845a]">*</span>
                        </span>
                        <input
                          name="departureDate"
                          type="date"
                          value={contactForm.departureDate}
                          onChange={(e) => updateContactField("departureDate", e.target.value)}
                          aria-invalid={Boolean(contactErrors.departureDate)}
                          className={`h-11 w-full rounded-lg border bg-white px-3 outline-none focus:border-accent ${
                            contactErrors.departureDate ? "border-red-400" : "border-[var(--line)]"
                          }`}
                        />
                        {contactErrors.departureDate && (
                          <span className="mt-1 block text-xs font-medium text-red-500">
                            {contactErrors.departureDate}
                          </span>
                        )}
                      </label>
                      <label className="block text-sm">
                        <span className="mb-1.5 block font-semibold text-brand-deep">
                          Bus/time <span className="text-[#e8845a]">*</span>
                        </span>
                        <select
                          name="pickupBus"
                          value={contactForm.pickupBus}
                          onChange={(e) => updateContactField("pickupBus", e.target.value)}
                          aria-invalid={Boolean(contactErrors.pickupBus)}
                          className={`h-11 w-full rounded-lg border bg-white px-3 outline-none focus:border-accent ${
                            contactErrors.pickupBus ? "border-red-400" : "border-[var(--line)]"
                          }`}
                        >
                          <option value="">Select bus - time *</option>
                          <option value="07:45 - Shared bus">07:45 - Shared bus</option>
                          <option value="08:00 - Shared bus">08:00 - Shared bus</option>
                          <option value="08:30 - Private transfer">08:30 - Private transfer</option>
                        </select>
                        {contactErrors.pickupBus && (
                          <span className="mt-1 block text-xs font-medium text-red-500">
                            {contactErrors.pickupBus}
                          </span>
                        )}
                      </label>
                    </div>
                    <label className="mt-4 block text-sm">
                      <span className="mb-1.5 block font-semibold text-brand-deep">
                        Address <span className="text-[#e8845a]">*</span>
                      </span>
                      <select
                        name="pickupAddress"
                        value={contactForm.pickupAddress}
                        onChange={(e) => updateContactField("pickupAddress", e.target.value)}
                        aria-invalid={Boolean(contactErrors.pickupAddress)}
                        className={`h-11 w-full rounded-lg border bg-white px-3 outline-none focus:border-accent ${
                          contactErrors.pickupAddress ? "border-red-400" : "border-[var(--line)]"
                        }`}
                      >
                        <option value="">Select pick up *</option>
                        <option value="Hotel lobby - Old Quarter">Hotel lobby - Old Quarter</option>
                        <option value="Near Hoan Kiem Lake">Near Hoan Kiem Lake</option>
                        <option value="Custom address (note in Messenger)">
                          Custom address (note in Messenger)
                        </option>
                      </select>
                      {contactErrors.pickupAddress && (
                        <span className="mt-1 block text-xs font-medium text-red-500">
                          {contactErrors.pickupAddress}
                        </span>
                      )}
                    </label>
                  </div>

                  <div className="flex items-center justify-center gap-2 py-1">
                    <p className="font-[family-name:var(--font-script)] text-2xl text-brand-deep sm:text-[1.75rem]">
                      Enjoy your time on Cruise
                    </p>
                    <Ship className="h-5 w-5 text-accent" />
                  </div>

                  {/* Drop off box */}
                  <div className="rounded-2xl bg-[#dff3f2] p-4 sm:p-5">
                    <div className="grid gap-4 md:grid-cols-3">
                      <label className="block text-sm">
                        <span className="mb-1.5 block font-semibold text-brand-deep">
                          Drop off <span className="text-[#e8845a]">*</span>
                        </span>
                        <select
                          name="dropoff"
                          value={contactForm.dropoff}
                          onChange={(e) => updateContactField("dropoff", e.target.value)}
                          aria-invalid={Boolean(contactErrors.dropoff)}
                          className={`h-11 w-full rounded-lg border bg-white px-3 outline-none focus:border-accent ${
                            contactErrors.dropoff ? "border-red-400" : "border-[var(--line)]"
                          }`}
                        >
                          <option value="">Select drop off *</option>
                          <option value="Hanoi Old Quarter">Hanoi Old Quarter</option>
                          <option value="Ninh Binh">Ninh Binh</option>
                          <option value="Halong City">Halong City</option>
                        </select>
                        {contactErrors.dropoff && (
                          <span className="mt-1 block text-xs font-medium text-red-500">
                            {contactErrors.dropoff}
                          </span>
                        )}
                      </label>
                      <label className="block text-sm">
                        <span className="mb-1.5 block font-semibold text-brand-deep">
                          End date <span className="text-[#e8845a]">*</span>
                        </span>
                        <input
                          name="endDate"
                          type="date"
                          value={contactForm.endDate}
                          onChange={(e) => updateContactField("endDate", e.target.value)}
                          aria-invalid={Boolean(contactErrors.endDate)}
                          className={`h-11 w-full rounded-lg border bg-white px-3 outline-none focus:border-accent ${
                            contactErrors.endDate ? "border-red-400" : "border-[var(--line)]"
                          }`}
                        />
                        {contactErrors.endDate && (
                          <span className="mt-1 block text-xs font-medium text-red-500">
                            {contactErrors.endDate}
                          </span>
                        )}
                      </label>
                      <label className="block text-sm">
                        <span className="mb-1.5 block font-semibold text-brand-deep">
                          Bus/time <span className="text-[#e8845a]">*</span>
                        </span>
                        <select
                          name="dropoffBus"
                          value={contactForm.dropoffBus}
                          onChange={(e) => updateContactField("dropoffBus", e.target.value)}
                          aria-invalid={Boolean(contactErrors.dropoffBus)}
                          className={`h-11 w-full rounded-lg border bg-white px-3 outline-none focus:border-accent ${
                            contactErrors.dropoffBus ? "border-red-400" : "border-[var(--line)]"
                          }`}
                        >
                          <option value="">Select bus - time *</option>
                          <option value="12:00 - Shared bus">12:00 - Shared bus</option>
                          <option value="13:00 - Shared bus">13:00 - Shared bus</option>
                          <option value="14:00 - Private transfer">14:00 - Private transfer</option>
                        </select>
                        {contactErrors.dropoffBus && (
                          <span className="mt-1 block text-xs font-medium text-red-500">
                            {contactErrors.dropoffBus}
                          </span>
                        )}
                      </label>
                    </div>
                    <label className="mt-4 block text-sm">
                      <span className="mb-1.5 block font-semibold text-brand-deep">
                        Address <span className="text-[#e8845a]">*</span>
                      </span>
                      <select
                        name="dropoffAddress"
                        value={contactForm.dropoffAddress}
                        onChange={(e) => updateContactField("dropoffAddress", e.target.value)}
                        aria-invalid={Boolean(contactErrors.dropoffAddress)}
                        className={`h-11 w-full rounded-lg border bg-white px-3 outline-none focus:border-accent ${
                          contactErrors.dropoffAddress ? "border-red-400" : "border-[var(--line)]"
                        }`}
                      >
                        <option value="">Select pick up *</option>
                        <option value="Hotel lobby - Old Quarter">Hotel lobby - Old Quarter</option>
                        <option value="Near Hoan Kiem Lake">Near Hoan Kiem Lake</option>
                        <option value="Custom address (note in Messenger)">
                          Custom address (note in Messenger)
                        </option>
                      </select>
                      {contactErrors.dropoffAddress && (
                        <span className="mt-1 block text-xs font-medium text-red-500">
                          {contactErrors.dropoffAddress}
                        </span>
                      )}
                    </label>
                  </div>

                  <label className="block text-sm">
                    <span className="mb-1.5 block font-semibold text-brand-deep">Messenger</span>
                    <textarea
                      name="messenger"
                      rows={4}
                      value={contactForm.messenger}
                      onChange={(e) => updateContactField("messenger", e.target.value)}
                      placeholder="Tell us your hotel address, other questions"
                      className="w-full resize-y rounded-lg border border-[var(--line)] bg-white px-3 py-2.5 outline-none focus:border-accent"
                    />
                  </label>

                  {bookingError ? (
                    <p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
                      {bookingError}
                    </p>
                  ) : null}

                  <button
                    type="submit"
                    disabled={submittingBooking || tourClosed}
                    className="btn-accent px-6 py-3 text-sm disabled:opacity-70"
                  >
                    {tourClosed
                      ? "Tour closed"
                      : submittingBooking
                        ? "Redirecting to OnePay…"
                        : "Pay with OnePay"}
                  </button>
                </div>
              </form>
            </div>

            {/* Confirmed booking sidebar */}
            <aside className="h-fit overflow-hidden rounded-2xl border border-[#e6ecef] bg-white shadow-[0_12px_32px_rgba(13,58,77,0.08)] lg:sticky lg:top-36">
              <div className="px-5 pt-5 pb-3">
                <h3 className="text-[17px] font-bold text-[#1c2b33]">Confirmed Tour Booking</h3>
              </div>

              <div className="space-y-3 px-4 pb-4">
                {/* Information */}
                <div className="rounded-xl bg-[#e6f4f1] p-4">
                  <div className="mb-3 flex items-center justify-between gap-2">
                    <p className="text-sm font-bold text-[#1c2b33]">Information</p>
                    <button
                      type="button"
                      className="text-accent"
                      aria-label="Edit booking information"
                      onClick={() => setBookingStep(1)}
                    >
                      <Pencil className="h-4 w-4" />
                    </button>
                  </div>
                  <p className="text-sm font-medium text-accent">{paxLabel}</p>
                  <div className="my-3 border-t border-dashed border-accent/30" />
                  <div className="flex flex-wrap items-center gap-3 text-sm text-accent">
                    <span className="inline-flex items-center gap-1.5">
                      <CalendarDays className="h-4 w-4" />
                      <span>{contactForm.departureDate || "…"}</span>
                    </span>
                    <span className="inline-flex items-center gap-1.5">
                      <Clock3 className="h-4 w-4" />
                      {tourLabel}
                    </span>
                  </div>
                </div>

                {/* Room class */}
                <div className="rounded-xl bg-[#f8f9f9] px-4 py-3">
                  <p className="border-b border-[#e6ecef] pb-2 text-sm font-bold text-[#1c2b33]">
                    Room class
                  </p>
                  <div className="mt-2 space-y-2 text-sm text-muted">
                    {cruise.rooms.some((r) => (roomQty[r.id] ?? 0) > 0) ? (
                      cruise.rooms
                        .filter((r) => (roomQty[r.id] ?? 0) > 0)
                        .map((r) => (
                          <div key={r.id} className="flex items-center justify-between gap-2">
                            <span className="font-semibold text-brand-deep">
                              {roomQty[r.id]}× {r.name}
                            </span>
                            <span className="font-bold text-accent">
                              {r.price * (roomQty[r.id] ?? 0)}$
                            </span>
                          </div>
                        ))
                    ) : (
                      <p className="min-h-[28px] text-muted/70">—</p>
                    )}
                  </div>
                </div>

                {/* Transport */}
                <div className="rounded-xl bg-[#f8f9f9] px-4 py-3">
                  <p className="mb-3 text-sm font-bold text-[#1c2b33]">Transport Add On</p>
                  <div className="space-y-3 text-sm">
                    <div className="flex items-start justify-between gap-3">
                      <div className="min-w-0">
                        <p className="font-semibold text-accent">Pick up</p>
                        <p className="mt-0.5 text-muted">
                          {pickup || "…"} from {pickup || "…"} at -
                        </p>
                        <p className="mt-1 inline-flex items-center gap-1.5 text-muted">
                          <Car className="h-3.5 w-3.5" />x {totalPax} pax
                        </p>
                      </div>
                      <span className="shrink-0 font-semibold text-accent">Free</span>
                    </div>
                    <div className="flex items-start justify-between gap-3">
                      <div className="min-w-0">
                        <p className="font-semibold text-accent">Drop off</p>
                        <p className="mt-0.5 text-muted">
                          {dropoff || "…"} from {dropoff || "…"} at -
                        </p>
                        <p className="mt-1 inline-flex items-center gap-1.5 text-muted">
                          <Car className="h-3.5 w-3.5" />x {totalPax} pax
                        </p>
                      </div>
                      <span className="shrink-0 font-semibold text-accent">Free</span>
                    </div>
                  </div>
                </div>

                {/* Total */}
                <div className="rounded-xl bg-[#e6f4f1] px-4 py-3 text-center">
                  <p className="text-sm font-bold text-[#1c2b33]">
                    Total about ${totalPrice || 0}
                  </p>
                </div>

                <button
                  type="button"
                  onClick={() => void submitBooking()}
                  disabled={submittingBooking || bookingStep >= 4 || tourClosed}
                  className="w-full rounded-xl bg-accent py-3.5 text-sm font-bold text-white transition hover:bg-accent-hover disabled:opacity-70"
                >
                  {tourClosed
                    ? "Tour closed"
                    : submittingBooking
                      ? "Redirecting to OnePay…"
                      : bookingStep >= 4
                        ? "Payment completed"
                        : "Pay with OnePay"}
                </button>
                {bookingError ? (
                  <p className="text-center text-xs font-semibold text-red-500">{bookingError}</p>
                ) : null}
                {bookingStep >= 4 && (
                  <p className="text-center text-xs font-semibold text-accent">
                    Payment completed — your booking is confirmed.
                  </p>
                )}
              </div>
            </aside>
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section id="faq" className="scroll-mt-36 bg-white py-10 sm:py-12">
        <div className="mx-auto w-[min(900px,calc(100%-2rem))]">
          <h2 className="font-[family-name:var(--font-display)] text-2xl font-semibold text-brand-deep">
            FAQ
          </h2>
          <div className="mt-5 space-y-3">
            {cruise.faqs.map((faq, i) => {
              const open = openFaq === i;
              return (
                <div key={faq.q} className="rounded-2xl border border-[var(--line)]">
                  <button
                    type="button"
                    onClick={() => setOpenFaq(open ? null : i)}
                    className="flex w-full items-center justify-between gap-3 px-4 py-3 text-left text-sm font-semibold text-brand-deep sm:px-5"
                  >
                    {faq.q}
                    <ChevronDown
                      className={`h-4 w-4 shrink-0 transition ${open ? "rotate-180" : ""}`}
                    />
                  </button>
                  {open && (
                    <p className="border-t border-[var(--line)] px-4 py-3 text-sm leading-relaxed text-muted sm:px-5">
                      {faq.a}
                    </p>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* Related */}
      <section className="bg-white py-12">
        <div className="mx-auto w-[min(1180px,calc(100%-2rem))]">
          <div className="mb-6 flex items-end justify-between gap-3">
            <h2 className="font-[family-name:var(--font-display)] text-2xl font-semibold text-brand-deep">
              You May Also Like...
            </h2>
            <a href="/cruise-tours" className="text-sm font-semibold text-accent">
              See All
            </a>
          </div>
          <div className="grid gap-5 sm:grid-cols-2 xl:grid-cols-4">
            {related.map((item) => (
              <CruiseCard key={item.id} cruise={item} />
            ))}
          </div>
        </div>
      </section>

      {galleryOpen && (
        <div className="fixed inset-0 z-[80] bg-black/80 p-4 sm:p-8">
          <button
            type="button"
            onClick={() => setGalleryOpen(false)}
            className="absolute top-4 right-4 grid h-10 w-10 place-items-center rounded-full bg-white text-brand-deep"
            aria-label="Close gallery"
          >
            <X className="h-5 w-5" />
          </button>
          <div className="mx-auto grid h-full max-w-5xl grid-cols-2 content-center gap-3 overflow-y-auto md:grid-cols-3">
            {gallery.map((src, i) => (
              <div key={src + i} className="overflow-hidden rounded-xl">
                <AiImage src={src} alt="" className="aspect-square w-full" />
              </div>
            ))}
          </div>
        </div>
      )}
    </>
  );
}
