"use client";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Calendar as DateCalendar } from "@/components/ui/calendar";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Input } from "@/components/ui/input";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Label } from "@/components/ui/label";
import type {
  ApiFixPackage,
  ApiFixPackageDetail,
  ApiFixPackageItinerary,
} from "@/core/api/services/fix-packages/fix-packages.types";
import type {
  ItineraryDayData,
  PackageDetailCustomer,
} from "@/features/fixed-packages/types/package-detail.types";
import { getClientSession, validateSessionData } from "@/features/auth";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import { getStorageUrl } from "@/lib/utils";
import { PACKAGE_DETAIL } from "@/lib/strings";
import {
  PackageDetailTabs,
  stripHtml,
  htmlToList,
  calculatePartyPricing as calcPartyPricing,
  getAgeCategory,
} from "@/components/shared/package-detail";
import { ErrorState } from "@/components/shared/error-state";
import { PassengerDetailsCard } from "@/components/shared/package-detail";
import {
  ArrowLeft,
  Calendar,
  CalendarIcon,
  Camera,
  Car,
  Check,
  Clock4,
  ChevronDown,
  ChevronUp,
  Coffee,
  Crown,
  FileText,
  Hotel,
  IndianRupee,
  Info,
  Landmark,
  Loader2,
  MapPin,
  Package,
  Percent,
  Settings,
  Sparkles,
  Star,
  UtensilsCrossed,
  Wine,
  X,
} from "lucide-react";
import { addDays, differenceInCalendarDays, format, subDays } from "date-fns";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useRef, useState } from "react";

import {
  addBookingPassengersAction,
  deletePassengerAction,
  getBookingPassengersAction,
  updatePassengersAction,
} from "@/features/fixed-packages/actions/passenger-actions";
import "react-quill-new/dist/quill.snow.css";

export default function FixedPackageDetailClient({
  id: _id,
  initialData,
}: {
  id: string;
  initialData?: ApiFixPackage | null;
}) {
  const router = useRouter();
  const { success, error } = useToastEnhanced();

  // Default initial customer
  const [customers, setCustomers] = useState<PackageDetailCustomer[]>([
    {
      id: "1",
      passenger_name: "",
      age: 0,
      gender: "",
      phone_number: "",
      email: "",
      document_id_no: "",
      alternate_contact: "",
      adults_count: 1,
      children_count: 0,
      children_ages: [],
    },
  ]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [hasAttemptedBooking, setHasAttemptedBooking] = useState(false);
  const [start_date, setstart_date] = useState<string>("");
  /** Date picker value in header; applied to start_date when user clicks Apply. */
  const [datePickerValue, setDatePickerValue] = useState<Date | undefined>(
    undefined
  );
  useEffect(() => {
    if (start_date) {
      const d = new Date(start_date);
      if (!Number.isNaN(d.getTime())) setDatePickerValue(d);
    } else {
      setDatePickerValue(undefined);
    }
  }, [start_date]);
  /** Which itinerary section is expanded; key e.g. "1-travel". Default open (true). */
  const [itineraryOpen, setItineraryOpen] = useState<Record<string, boolean>>(
    {}
  );
  const isSectionOpen = (key: string) => itineraryOpen[key] !== false;
  const setSectionOpen = (key: string, open: boolean) =>
    setItineraryOpen((prev) => ({ ...prev, [key]: open }));
  /** Which day cards are expanded. Default open (true). */
  const [dayCardOpen, setDayCardOpen] = useState<Record<number, boolean>>({});
  const [activeItineraryDay, setActiveItineraryDay] = useState<number | null>(
    null
  );
  const isDayCardOpen = (day: number) =>
    activeItineraryDay !== null
      ? dayCardOpen[day] === true
      : dayCardOpen[day] === true;
  const setDayCardOpenState = (day: number, open: boolean) =>
    setDayCardOpen((prev) => ({ ...prev, [day]: open }));

  /** Refs for each itinerary day card keyed by day number, used for scroll-into-view. */
  const dayCardRefs = useRef<Record<number, HTMLDivElement | null>>({});
  const dateStripRef = useRef<HTMLDivElement>(null);

  const scrollToDay = useCallback((day: number) => {
    setActiveItineraryDay(day);
    setDayCardOpen({ [day]: true });
    requestAnimationFrame(() => {
      dayCardRefs.current[day]?.scrollIntoView({
        behavior: "smooth",
        block: "start",
      });
    });
  }, []);

  /** Things to know: which extra cards are expanded. First (0) open by default. */
  const [thingsOpenIndices, setThingsOpenIndices] = useState<Set<number>>(
    new Set([0])
  );
  const setThingsOpen = (idx: number, open: boolean) =>
    setThingsOpenIndices((prev) => {
      const next = new Set(prev);
      if (open) next.add(idx);
      else next.delete(idx);
      return next;
    });

  const pkg = initialData as ApiFixPackageDetail | null | undefined;
  const _rawItinerary =
    pkg?.Itinerary_detail || "Itinerary details not available.";

  /** Normalize price from API (may be string or number). */
  const priceNum =
    pkg?.price != null
      ? typeof pkg.price === "string"
        ? parseFloat(pkg.price) || 0
        : Number(pkg.price)
      : 0;
  const discountPriceNum =
    pkg?.discount_price != null && pkg.discount_price !== ""
      ? typeof pkg.discount_price === "string"
        ? parseFloat(pkg.discount_price) || priceNum
        : Number(pkg.discount_price)
      : null;

  const displayImages = (pkg?.images ?? []).slice(0, 6);
  const galleryCount = displayImages.length;
  // For 3 or 5 images: banner 100% width @ 60% height, then images in one row @ 40%
  const useStackedLayout35 = galleryCount === 3 || galleryCount === 5;
  // Layout for side-by-side (banner | grid): 1–2 stack vertically; 4,6 use 2 cols
  const gridClass =
    galleryCount <= 1
      ? "grid-cols-1 grid-rows-1"
      : galleryCount === 2
        ? "grid-cols-1 grid-rows-2"
        : galleryCount === 4
          ? "grid-cols-2 grid-rows-2"
          : "grid-cols-2 grid-rows-3";
  const galleryRowCols =
    galleryCount === 3
      ? "grid-cols-3"
      : galleryCount === 5
        ? "grid-cols-5"
        : null;
  const locationDetail = pkg?.location_detail?.trim() ?? "";
  const otherDetail = pkg?.other_detail?.trim();
  const extras = pkg?.extras ?? [];

  /** Inclusions and exclusions from API (inclusion/exclusion); strip HTML. */
  const inclusionRaw = (
    pkg as { inclusion?: string | null }
  )?.inclusion?.trim();
  const exclusionRaw = (
    pkg as { exclusion?: string | null }
  )?.exclusion?.trim();
  const inclusionList = htmlToList(inclusionRaw ?? "");
  const exclusionList = htmlToList(exclusionRaw ?? "");
  const _vehicles = pkg?.vehicles ?? [];
  const _hotels = pkg?.hotels ?? [];

  /** Build itinerary day cards from API itineraries or fallback to package-level data. */
  const apiItineraries = pkg?.itineraries;
  const totalDays = Math.max(
    1,
    Number(pkg?.total_days) || Number((pkg as ApiFixPackage)?.no_of_days) || 1
  );

  /** Normalize to start of day for comparison. */
  const toDayStart = (d: Date) => {
    const x = new Date(d);
    x.setHours(0, 0, 0, 0);
    return x;
  };

  /** Date selector bounds: current date for first enabled; end_date, total_days from API. */
  const pkgStartDate = pkg?.start_date
    ? toDayStart(new Date(pkg.start_date))
    : null;
  const todayStart = toDayStart(new Date());
  const pkgEndDate = pkg?.end_date ? toDayStart(new Date(pkg.end_date)) : null;
  /** Reference date for batch interval alignment (original package start_date or today). */
  const batchReferenceDate = pkgStartDate ?? todayStart;
  /**
   * First enabled date: use start_date from API if available and not in the past.
   * If start_date is in the past, find the next valid batch start >= today.
   * Falls back to current date when start_date is not available.
   */
  const firstEnabledDate = (() => {
    if (pkgStartDate && pkgStartDate.getTime() >= todayStart.getTime()) {
      return pkgStartDate;
    }
    if (pkgStartDate) {
      const diffDays = differenceInCalendarDays(todayStart, pkgStartDate);
      const batchesPassed = Math.ceil(diffDays / totalDays);
      return toDayStart(addDays(pkgStartDate, batchesPassed * totalDays));
    }
    return todayStart;
  })();
  /** Last enabled start date: so that start + (total_days - 1) <= end_date. */
  const lastEnabledStartDate =
    pkgEndDate && totalDays >= 1
      ? toDayStart(subDays(pkgEndDate, totalDays - 1))
      : (pkgEndDate ?? null);
  /** Calendar shows up to package end_date only. */
  const calendarToDate = pkgEndDate ?? undefined;

  /** Display day/night count: prefer API no_of_days / no_of_nights, coerce to number. */
  const daysVal = (pkg as ApiFixPackage)?.no_of_days ?? pkg?.total_days;
  const displayDays = Math.max(
    1,
    daysVal != null ? Number(daysVal) : totalDays
  );
  const nightsVal = (pkg as ApiFixPackage)?.no_of_nights;
  const displayNights = Math.max(
    0,
    nightsVal != null ? Number(nightsVal) : displayDays - 1
  );
  const locationName =
    typeof pkg?.name === "string"
      ? pkg.name.replace(/\s*[-–|].*$/, "").trim() || "Destination"
      : "Destination";

  const itineraryDays: ItineraryDayData[] =
    apiItineraries && apiItineraries.length > 0
      ? apiItineraries.map((itin: ApiFixPackageItinerary) => {
          const loc =
            itin.night_stay_location?.trim() ||
            itin.city?.name?.trim() ||
            locationName;
          const vehicle = itin.vehicles?.[0];
          const hotel = itin.hotels?.[0];
        const sightList = itin.sight_seeing_details ?? [];
          const mealsList: ItineraryDayData["meals"] = [];
          if (itin.is_breakfast) {
            mealsList.push({
              type: "Breakfast",
              location: loc,
              description: itin.breakfast_detail ?? undefined,
              includedWith: "Hotel" as const,
            });
          }
          if (itin.is_lunch) {
            mealsList.push({
              type: "Lunch",
              location: loc,
              description: itin.lunch_detail ?? undefined,
              includedWith: "Activity" as const,
            });
          }
          if (itin.is_dinner) {
            mealsList.push({
              type: "Dinner",
              location: loc,
              description: itin.dinner_detail ?? undefined,
              includedWith: "Hotel" as const,
            });
          }
          return {
            day: itin.day,
            dayTitle: itin.title?.trim() || undefined,
            description: itin.description ?? null,
            locationLabel: loc,
            travel: vehicle
              ? {
                  from: itin.day === 1 ? "Departure City" : loc,
                  to: itin.day === totalDays ? "Return" : loc,
                  pickupPoint:
                    (itin as { pickup_point?: string | null }).pickup_point ??
                    null,
                  dropPoint:
                    (itin as { drop_point?: string | null }).drop_point ?? null,
                  vehicleName: vehicle.name,
                  vehicleType: vehicle.vehicle_type ?? null,
                  image: vehicle.image ?? null,
                  specs:
                    (vehicle as { description?: string | null }).description ??
                    null,
                }
              : null,
            hotel: hotel
              ? {
                  name: hotel.name,
                  hotelType: hotel.hotel_type ?? null,
                  star: (hotel as { star?: string | null }).star ?? null,
                  landmark:
                    (hotel as { landmark_detail?: string | null })
                      .landmark_detail ?? null,
                  description:
                    (hotel as { description?: string | null }).description ??
                    null,
                  checkIn:
                    (hotel as { check_in?: string | null }).check_in ?? "",
                  checkOut:
                    (hotel as { check_out?: string | null }).check_out ?? "",
                  nights: itin.day === totalDays ? 0 : 1,
                  image: hotel.image ?? null,
                }
              : null,
            sightseeings: sightList.map((s) => ({
              title: s.location_detail || "Sightseeing",
              duration: "8 Hours",
              places: [s.location_detail].filter(Boolean),
              image: s.image ?? null,
            })),
            meals: mealsList.length > 0 ? mealsList : [],
          } satisfies ItineraryDayData;
        })
      : [];

  /** Per meal type: which days include/exclude it (from itinerary). */
  const mealDaysByType: Record<
    "Breakfast" | "Lunch" | "Dinner",
    { included: number[]; excluded: number[] }
  > = (() => {
    const types: Array<"Breakfast" | "Lunch" | "Dinner"> = [
      "Breakfast",
      "Lunch",
      "Dinner",
    ];
    const result = {
      Breakfast: { included: [] as number[], excluded: [] as number[] },
      Lunch: { included: [] as number[], excluded: [] as number[] },
      Dinner: { included: [] as number[], excluded: [] as number[] },
    };
    for (const dayData of itineraryDays) {
      const day = dayData.day;
      const mealTypes = new Set(
        dayData.meals.map((m) => m.type as "Breakfast" | "Lunch" | "Dinner")
      );
      for (const type of types) {
        if (mealTypes.has(type)) result[type].included.push(day);
        else result[type].excluded.push(day);
      }
    }
    return result;
  })();

  /** Unique sightseeing names from itinerary (for Overview). */
  const sightseeingList = (() => {
    const set = new Set<string>();
    itineraryDays.forEach((dayData) => {
      dayData.sightseeings.forEach((s) => {
        const t = (s.title || s.places?.[0])?.trim();
        if (t) set.add(t);
      });
    });
    return Array.from(set);
  })();

  const renderGalleryCell = (
    img: {
      image?: string | null;
      name?: string | null;
      description?: string | null;
    },
    idx: number
  ) => {
    const rawUrl = img.image ?? "";
    const src = !rawUrl
      ? "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='300' viewBox='0 0 400 300'%3E%3Crect fill='%23e2e8f0' width='400' height='300'/%3E%3Ctext fill='%2394a3b8' x='50%25' y='50%25' dominant-baseline='middle' text-anchor='middle' font-family='sans-serif' font-size='16'%3EView " +
        (idx + 1) +
        "%3C/text%3E%3C/svg%3E"
      : rawUrl.startsWith("http://") || rawUrl.startsWith("https://")
        ? rawUrl
        : getStorageUrl(rawUrl) || rawUrl;
    const _isLast = idx === displayImages.length - 1 && galleryCount >= 4;
    const isFifthOfFive =
      !useStackedLayout35 && galleryCount === 5 && idx === 4;
    return (
      <div
        key={idx}
        className={`relative min-h-0 h-full w-full rounded-xl overflow-hidden bg-muted group ${
          isFifthOfFive ? "lg:col-span-2" : ""
        }`}
      >
        <img
          src={src}
          alt={img.name || `Gallery ${idx + 1}`}
          className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
          loading="lazy"
          onError={(e) => {
            const t = e.currentTarget;
            if (!t.dataset.fallback) {
              t.dataset.fallback = "1";
              t.src =
                "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='300' viewBox='0 0 400 300'%3E%3Crect fill='%23e2e8f0' width='400' height='300'/%3E%3Ctext fill='%2394a3b8' x='50%25' y='50%25' dominant-baseline='middle' text-anchor='middle' font-family='sans-serif' font-size='14'%3EView " +
                (idx + 1) +
                "%3C/text%3E%3C/svg%3E";
            }
          }}
        />
      </div>
    );
  };

  const _fetchBookingPassengers = async (bookingId: string) => {
    const result = await getBookingPassengersAction(bookingId);
    if (result.success && result.data) {
      // Map passengers to Customer state
      const mappedCustomers: PackageDetailCustomer[] = result.data.map((p) => ({
        id: p.id.toString(),
        passenger_name: p.passenger_name,
        age: p.age,
        gender: p.gender,
        phone_number: p.phone_number,
        email: p.email,
        document_id_no: p.document_id_no,
        alternate_contact: "",
        adults_count: 1,
        children_count: 0,
        children_ages: [],
      }));
      setCustomers(mappedCustomers);
    }
  };

  const handleDeletePassenger = async (customerId: string) => {
    // If ID is numeric (real ID from DB), call API
    // Timestamps from Date.now() are 13 digits, real DB IDs are smaller
    const isNewPassenger = customerId.length > 10;

    if (!isNaN(Number(customerId)) && !isNewPassenger) {
      try {
        const result = await deletePassengerAction(Number(customerId));
        if (!result.success) {
          error({
            title: PACKAGE_DETAIL.ERROR,
            description: result.error || PACKAGE_DETAIL.FAILED_DELETE_PASSENGER,
          });
          return;
        }
        success({
          title: PACKAGE_DETAIL.SUCCESS,
          description: PACKAGE_DETAIL.PASSENGER_DELETED,
        });
      } catch {
        // Handle error silently or show toast
      }
    }

    if (customers.length > 1) {
      setCustomers(customers.filter((c) => c.id !== customerId));
    } else {
      // If it's the last one and we deleted it from DB, we might want to reset it to empty
      // But logic says we always keep 1.
      // If we deleted it from DB, we should probably clear fields.
      if (!isNaN(Number(customerId)) && !isNewPassenger) {
        setCustomers([
          {
            id: Date.now().toString(),
            passenger_name: "",
            age: 0,
            gender: "",
            phone_number: "",
            email: "",
            document_id_no: "",
            alternate_contact: "",
            adults_count: 1,
            children_count: 0,
            children_ages: [],
          },
        ]);
      }
    }
  };

  const _handleUpdatePassenger = async (customer: PackageDetailCustomer) => {
    // Only update if it has a real ID
    if (!isNaN(Number(customer.id))) {
      try {
        const result = await updatePassengersAction(Number(customer.id), {
          passengers: [
            {
              id: Number(customer.id),
              passenger_name: customer.passenger_name,
              age: Number(customer.age),
              gender: customer.gender as "Male" | "Female" | "Other",
              email: customer.email,
              user_id: 0, // Placeholder
              document_id_no: customer.document_id_no || "",
              phone_number: customer.phone_number,
            },
          ],
        });

        if (result.success) {
          success({
            title: PACKAGE_DETAIL.SUCCESS,
            description: PACKAGE_DETAIL.PASSENGER_UPDATE_SUCCESS,
          });
        }
      } catch {
        error({
          title: PACKAGE_DETAIL.ERROR,
          description: PACKAGE_DETAIL.FAILED_UPDATE_PASSENGER,
        });
      }
    }
  };

  /** Which passenger cards are expanded. When empty, first card is open. Add passenger collapses first and opens new. */
  const [passengerCardOpen, setPassengerCardOpen] = useState<Set<string>>(
    new Set()
  );
  const isPassengerCardOpen = (customerId: string, index: number) =>
    passengerCardOpen.has(customerId) ||
    (passengerCardOpen.size === 0 && index === 0);

  const addCustomer = () => {
    const newId = Date.now().toString();
    setCustomers([
      ...customers,
      {
        id: newId,
        passenger_name: "",
        age: 0,
        gender: "",
        phone_number: "",
        email: "",
        document_id_no: "",
        alternate_contact: "",
        adults_count: 1,
        children_count: 0,
        children_ages: [],
      },
    ]);
    setPassengerCardOpen(new Set([newId]));
  };

  const removeCustomer = (customerId: string) => {
    handleDeletePassenger(customerId);
  };

  const updateCustomer = (
    customerId: string,
    field: keyof PackageDetailCustomer,
    value: string | number | number[]
  ) => {
    setCustomers((prev) =>
      prev.map((c) => (c.id === customerId ? { ...c, [field]: value } : c))
    );
  };

  const calculatePricing = () => {
    if (!pkg)
      return {
        adultsCount: 0,
        adultPrice: 0,
        adultTotal: 0,
        childrenCount: 0,
        childPrice: 0,
        childTotal: 0,
        childAdultsCount: 0,
        childAdultTotal: 0,
        infantsCount: 0,
        subtotal: 0,
        gst: 0,
        total: 0,
      };

    const price = discountPriceNum ?? priceNum;
    const primary = customers[0];
    return calcPartyPricing(
      price,
      primary?.adults_count ?? 1,
      primary?.children_ages ?? []
    );
  };

  const handleBooking = async () => {
    // 1. Session Check First
    const session = getClientSession("customer_session");
    if (
      !session ||
      !validateSessionData(session) ||
      session.role !== "customer"
    ) {
      error({
        title: PACKAGE_DETAIL.LOGIN_REQUIRED_TITLE,
        description: PACKAGE_DETAIL.LOGIN_REQUIRED_DESCRIPTION,
      });
      router.push("/login");
      return;
    }

    // 2. Package Check
    if (!pkg) return;

    setHasAttemptedBooking(true);

    // 2.5. Validate Date
    if (!start_date) {
      error({
        title: PACKAGE_DETAIL.MISSING_START_DATE,
        description: PACKAGE_DETAIL.SELECT_START_DATE,
      });
      return;
    }

    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const selectedDate = new Date(start_date);

    if (selectedDate < today) {
      error({
        title: PACKAGE_DETAIL.INVALID_DATE,
        description: PACKAGE_DETAIL.START_DATE_PAST,
      });
      return;
    }

    if (pkg.end_date) {
      const packageEndDate = new Date(pkg.end_date);
      if (selectedDate > packageEndDate) {
        error({
          title: PACKAGE_DETAIL.INVALID_DATE,
          description: `${PACKAGE_DETAIL.START_DATE_AFTER_END}${pkg.end_date}).`,
        });
        return;
      }
    }

    const diffFromRef = differenceInCalendarDays(
      toDayStart(selectedDate),
      batchReferenceDate
    );
    if (diffFromRef % totalDays !== 0) {
      error({
        title: PACKAGE_DETAIL.INVALID_DATE,
        description: PACKAGE_DETAIL.START_DATE_NOT_VALID_BATCH,
      });
      return;
    }

    // 3. Validate Passengers
    const PHONE_REGEX = /^\d{10,12}$/;
    const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const c = customers[0];
    const hasValidName = !!c.passenger_name.trim();
    const hasValidPhone = PHONE_REGEX.test(c.phone_number);
    const hasValidEmail = !c.email.trim() || EMAIL_REGEX.test(c.email.trim());
    const hasValidAltContact =
      !(c.alternate_contact ?? "").trim() ||
      PHONE_REGEX.test(c.alternate_contact ?? "");
    const childrenAges = c.children_ages ?? [];
    const hasValidChildAges =
      childrenAges.length === 0 || childrenAges.every((age) => age > 0);

    if (
      !hasValidName ||
      !hasValidPhone ||
      !hasValidEmail ||
      !hasValidAltContact ||
      !hasValidChildAges
    ) {
      error({
        title: PACKAGE_DETAIL.INCOMPLETE_DETAILS,
        description: PACKAGE_DETAIL.FILL_CUSTOMER_DETAILS,
      });
      return;
    }

    setIsSubmitting(true);

    try {
      // 4. Booking Logic
      const pricing = calculatePricing();
      const pricePerPerson = discountPriceNum ?? priceNum;

      const AGE_LABEL_MAP: Record<string, string> = {
        infant: PACKAGE_DETAIL.CHILD_AGE_RANGE_INFANT,
        child: PACKAGE_DETAIL.CHILD_AGE_RANGE_CHILD,
        adult: PACKAGE_DETAIL.CHILD_AGE_RANGE_ADULT,
      };

      const childrenJson = childrenAges.map((age) => ({
        age: AGE_LABEL_MAP[getAgeCategory(age)] ?? String(age),
      }));

      const result = await addBookingPassengersAction({
        fix_package_id: Number(pkg.id),
        start_date,
        total_price: pricing.total,
        adult_price: pricing.adultTotal,
        child_price: pricing.childTotal + pricing.childAdultTotal,
        infant_price: 0,
        package_price: pricePerPerson,
        discount_price: discountPriceNum ? priceNum - discountPriceNum : 0,
        tax: pricing.gst,
        passenger_detail: {
          passenger_name: c.passenger_name.trim(),
          phone_number: c.phone_number.trim(),
          alternate_phone_number: (c.alternate_contact ?? "").trim(),
          email: c.email?.trim() || "",
          total_adult: c.adults_count ?? 1,
          total_child: c.children_count ?? 0,
          children_json: childrenJson,
        },
      });

      if (!result.success) {
        throw new Error(
          result.error || PACKAGE_DETAIL.UNEXPECTED_ERROR_BOOKING
        );
      }

      // 5. Success Handling

      // Check if we have a payment URL to redirect to
      // The result.data is typed as unknown in ActionResult, so we cast it or check it safely
      const responseData = result.data as
        | { payment_url?: string; razor_pay_url?: string }
        | undefined;
      const paymentUrl =
        responseData?.payment_url || responseData?.razor_pay_url;

      if (paymentUrl) {
        success({
          title: PACKAGE_DETAIL.INITIATING_PAYMENT,
          description: PACKAGE_DETAIL.REDIRECTING_PAYMENT,
        });
        window.location.replace(paymentUrl);
        return;
      }

      // If no payment URL, treat as direct confirmation
      success({
        title: PACKAGE_DETAIL.BOOKING_CONFIRMED,
        description: `${PACKAGE_DETAIL.BOOKING_CONFIRMED_DESCRIPTION} ${pkg.name} ${PACKAGE_DETAIL.HAS_BEEN_CONFIRMED}`,
      });
      router.push("/user/fixed-bookings");
    } catch (err: unknown) {
      console.error("Booking Error:", err);
      const errObj = err as {
        response?: { data?: { message?: string } };
        message?: string;
      };
      const errorMessage =
        errObj.response?.data?.message ||
        errObj.message ||
        PACKAGE_DETAIL.UNEXPECTED_ERROR_BOOKING;

      error({
        title: PACKAGE_DETAIL.BOOKING_FAILED,
        description: errorMessage,
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!pkg) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-purple-50 via-white to-blue-50 flex items-center justify-center">
        <ErrorState
          icon={Package}
          title={PACKAGE_DETAIL.PACKAGE_NOT_FOUND}
          description={PACKAGE_DETAIL.PACKAGE_NOT_FOUND_DESCRIPTION}
        >
          <Button asChild>
            <Link href="/fixed-packages">
              <ArrowLeft className="mr-2 h-4 w-4" />
              {PACKAGE_DETAIL.BACK_TO_PACKAGES}
            </Link>
          </Button>
        </ErrorState>
      </div>
    );
  }

  const originalPrice = priceNum;
  const discountedPrice = discountPriceNum ?? priceNum;
  const discount =
    originalPrice > discountedPrice
      ? Math.round(((originalPrice - discountedPrice) / originalPrice) * 100)
      : 0;
  const pricing = calculatePricing();

  const isLoggedIn = !!(
    getClientSession("customer_session") &&
    validateSessionData(getClientSession("customer_session")) &&
    getClientSession("customer_session")?.role === "customer"
  );

  const handlePassengerCardOpenChange = (customerId: string, open: boolean) => {
    setPassengerCardOpen((prev) => {
      const next = new Set(prev);
      if (open) next.add(customerId);
      else next.delete(customerId);
      return next;
    });
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-purple-50 via-white to-blue-50">
      <main className="container mx-auto p-4 md:p-6 lg:p-8">
        {/* Back (3/12), date picker (6/12), Apply (3/12) — grid enforces column widths */}
        <div
          className="mb-6 grid gap-4"
          style={{ gridTemplateColumns: "2fr 8fr 2fr" }}
        >
          <div className="min-w-0">
            <Button
              variant="outline"
              asChild
              className="gap-2 w-full justify-center bg-transparent"
            >
              <Link href="/fixed-packages">
                <ArrowLeft className="h-4 w-4" />
                {PACKAGE_DETAIL.BACK_TO_PACKAGES}
              </Link>
            </Button>
          </div>
          <div className="min-w-0 w-full">
            <Popover>
              <PopoverTrigger asChild>
                <button
                  type="button"
                  style={{
                    width: "100%",
                    minWidth: 0,
                    boxSizing: "border-box",
                  }}
                  className={`flex h-9 items-center justify-start rounded-md border bg-background px-4 py-2 text-left text-sm font-normal shadow-xs outline-none hover:bg-accent/50 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 overflow-hidden ${hasAttemptedBooking && !datePickerValue ? "border-red-400 ring-1 ring-red-400" : "border-input"}`}
                >
                  <CalendarIcon className="mr-2 h-4 w-4 shrink-0" />
                  <span className="truncate min-w-0">
                    {datePickerValue
                      ? format(datePickerValue, "PPP")
                      : PACKAGE_DETAIL.SELECT_DATE}
                  </span>
                </button>
              </PopoverTrigger>
              <PopoverContent className="w-auto p-0 z-[100]" align="center">
                <DateCalendar
                  mode="single"
                  selected={datePickerValue ?? undefined}
                  onSelect={(date) => {
                    setDatePickerValue(date);
                    if (date) {
                      setstart_date(format(date, "yyyy-MM-dd"));
                    }
                  }}
                  fromDate={firstEnabledDate}
                  toDate={calendarToDate}
                  defaultMonth={firstEnabledDate}
                  disabled={(date) => {
                    const dayStart = toDayStart(date);
                    if (dayStart.getTime() < todayStart.getTime()) return true;
                    if (
                      pkgStartDate &&
                      dayStart.getTime() < pkgStartDate.getTime()
                    )
                      return true;
                    if (pkgEndDate && dayStart.getTime() > pkgEndDate.getTime())
                      return true;
                    return false;
                  }}
                  initialFocus
                />
              </PopoverContent>
            </Popover>
          </div>
          <div className="min-w-0">
            <Button
              variant="default"
              className="w-full"
              onClick={() => {
                if (datePickerValue) {
                  setstart_date(format(datePickerValue, "yyyy-MM-dd"));
                }
              }}
              disabled={!datePickerValue}
            >
              {PACKAGE_DETAIL.APPLY}
            </Button>
          </div>
        </div>

        {/* 70% left: gallery + tabs | 30% right: booking summary */}
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-[7fr_3fr]">
          {/* Left 70%: gallery + all 5 tabs (first on mobile, bottom is booking summary) */}
          <div className="min-w-0 space-y-6 order-1">
            {/* Full-width image gallery: banner (first block) + 6-image grid on right */}
            <Card className="shadow-lg overflow-hidden">
              {/* Title row: package name + Days/Night pill */}
              <div className="flex flex-wrap items-center justify-between gap-2 px-4 md:px-6">
                <h1 className="text-xl md:text-2xl font-bold text-gray-900">
                  {pkg.name}
                </h1>
                <span className="inline-flex flex-shrink-0 whitespace-nowrap rounded px-2 py-2 frontend-btn text-white text-[11px] font-semibold text-white">
                  {[
                    displayDays > 0
                      ? `${displayDays} ${displayDays === 1 ? "Day" : "Days"}`
                      : "",
                    displayNights > 0
                      ? `${displayNights} ${displayNights === 1 ? "Night" : "Nights"}`
                      : "",
                  ]
                    .filter(Boolean)
                    .join(" / ")}
                </span>
              </div>

              {galleryCount === 0 ? (
                <div className="p-4 pt-2 md:p-6 md:pt-2">
                  <div className="relative w-full min-h-[280px] md:min-h-[360px] rounded-xl overflow-hidden bg-gradient-to-br from-purple-100 to-blue-100">
                    {pkg.banner_image ? (
                      <img
                        src={
                          getStorageUrl(pkg.banner_image) || "/placeholder.png"
                        }
                        alt={pkg.name}
                        className="w-full h-full min-h-[280px] md:min-h-[360px] object-cover transition-transform duration-300 hover:scale-[1.02]"
                      />
                    ) : (
                      <div className="absolute inset-0 flex items-center justify-center">
                        <Sparkles className="h-20 w-20 text-blue-300 min-h-[360px]" />
                      </div>
                    )}
                    <div className="absolute top-3 left-3 flex flex-wrap gap-2">
                      <Badge className="bg-gradient-to-r frontend-btn text-white backdrop-blur-sm">
                        <Sparkles className="h-3 w-3 mr-1" />
                        Fixed Package
                      </Badge>
                      {pkg.status === "inactive" && (
                        <Badge
                          variant="destructive"
                          className="backdrop-blur-sm"
                        >
                          Inactive
                        </Badge>
                      )}
                      {discount > 0 && (
                        <Badge className="bg-[#68b90a] text-white">
                          {discount}
                          {PACKAGE_DETAIL.PERCENT_OFF}
                        </Badge>
                      )}
                      {pkg.package_type === "premium" && (
                        <Badge className="bg-[#f84200] text-white border-0 backdrop-blur-sm flex items-center gap-1 shadow-md">
                          <Crown className="h-3 w-3" />
                          Premium
                        </Badge>
                      )}
                    </div>
                  </div>
                </div>
              ) : useStackedLayout35 ? (
                /* 3 or 5 images: banner 100% width @ 60% height, then one row of images @ 40% */
                <div className="grid grid-rows-[5fr_2fr] min-h-[280px] md:min-h-[340px] gap-2 p-4 pt-2 md:p-6 md:pt-2">
                  {/* Banner: 100% width, 60% height */}
                  <div className="relative w-full min-h-0 rounded-xl overflow-hidden bg-gradient-to-br from-purple-100 to-blue-100">
                    {pkg.banner_image ? (
                      <img
                        src={
                          getStorageUrl(pkg.banner_image) || "/placeholder.png"
                        }
                        alt={pkg.name}
                        className="w-full h-full object-cover transition-transform duration-300 hover:scale-[1.02]"
                      />
                    ) : (
                      <div className="absolute inset-0 flex items-center justify-center">
                        <Sparkles className="h-20 w-20 text-purple-300" />
                      </div>
                    )}
                    <div className="absolute top-3 left-3 flex flex-wrap gap-2">
                      {pkg.status === "inactive" && (
                        <Badge
                          variant="destructive"
                          className="backdrop-blur-sm"
                        >
                          Inactive
                        </Badge>
                      )}
                      {discount > 0 && (
                        <Badge className="bg-[#68b90a] text-white">
                          {discount}
                          {PACKAGE_DETAIL.PERCENT_OFF}
                        </Badge>
                      )}
                      {pkg.package_type === "premium" && (
                        <Badge className="bg-gradient-to-r frontend-btn text-white border-0 backdrop-blur-sm flex items-center gap-1 shadow-md">
                          <Crown className="h-3 w-3" />
                          Premium
                        </Badge>
                      )}
                    </div>
                  </div>
                  {/* Gallery: one row, 100% width, 40% height */}
                  <div
                    className={`grid ${galleryRowCols} gap-2 min-h-0 h-full w-full`}
                  >
                    {displayImages.map((img, idx) =>
                      renderGalleryCell(img, idx)
                    )}
                  </div>
                </div>
              ) : (
                <div className="grid grid-cols-1 lg:grid-cols-[1.4fr_1fr] gap-2 p-4 pt-2 md:p-6 md:pt-2 items-stretch">
                  {/* First block: banner image (large, full height of row) */}
                  <div className="relative w-full min-h-[280px] md:min-h-[360px] rounded-xl overflow-hidden bg-gradient-to-br from-purple-100 to-blue-100">
                    {pkg.banner_image ? (
                      <img
                        src={
                          getStorageUrl(pkg.banner_image) || "/placeholder.png"
                        }
                        alt={pkg.name}
                        className="w-full h-full min-h-[280px] md:min-h-[360px] object-cover transition-transform duration-300 hover:scale-[1.02]"
                      />
                    ) : (
                      <div className="absolute inset-0 flex items-center justify-center">
                        <Sparkles className="h-20 w-20 text-purple-300" />
                      </div>
                    )}
                    <div className="absolute top-3 left-3 flex flex-wrap gap-2">
                      <Badge className="bg-white/90 text-purple-900 border-white/30 backdrop-blur-sm">
                        <Sparkles className="h-3 w-3 mr-1" />
                        Fixed Package
                      </Badge>
                      {pkg.status === "inactive" && (
                        <Badge
                          variant="destructive"
                          className="backdrop-blur-sm"
                        >
                          Inactive
                        </Badge>
                      )}
                      {discount > 0 && (
                        <Badge className="bg-[#68b90a] text-white">
                          <Percent className="h-3 w-3 mr-1" />
                          {discount}
                          {PACKAGE_DETAIL.PERCENT_OFF}
                        </Badge>
                      )}
                      {pkg.package_type === "premium" && (
                        <Badge className="bg-gradient-to-r frontend-btn text-white border-0 backdrop-blur-sm flex items-center gap-1 shadow-md">
                          <Crown className="h-3 w-3" />
                          Premium
                        </Badge>
                      )}
                    </div>
                  </div>

                  {/* Right side: gallery grid - fills 40% height, layout adapts to count (1–6) */}
                  <div
                    className={`grid gap-2 min-h-[280px] lg:min-h-[360px] h-full ${gridClass}`}
                  >
                    {displayImages.map((img, idx) =>
                      renderGalleryCell(img, idx)
                    )}
                  </div>
                </div>
              )}
            </Card>

            {/* Price card: on small screens only, between gallery and tabs */}
            <div className="block w-full lg:hidden">
              <Card className="w-full overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm">
                <CardContent className="flex w-full items-center justify-between gap-4">
                  <p className="text-sm font-medium text-gray-600">
                    {PACKAGE_DETAIL.EXCLUDING_APPLICABLE_TAXES}
                  </p>
                  <div className="flex flex-wrap items-baseline justify-end gap-2 text-right">
                    {discount > 0 && (
                      <>
                        <span className="text-base text-gray-500 line-through">
                          ₹{originalPrice.toLocaleString()}
                        </span>
                        <span className="text-base font-semibold text-red-600">
                          {discount}
                          {PACKAGE_DETAIL.PERCENT_OFF}
                        </span>
                      </>
                    )}
                    <span className="text-2xl font-bold text-gray-900">
                      ₹{discountedPrice.toLocaleString()}
                    </span>
                    <span className="text-base text-gray-600">
                      {PACKAGE_DETAIL.PER_PERSON}
                    </span>
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* Tabs card below gallery */}
            <Card className="mt-6 shadow-lg">
              <CardContent className="p-0">
                <PackageDetailTabs
                  overviewContent={
                    <div className="space-y-4">
                      {/* Top: Package Name, Days/Night, Overview */}
                      <Card className="overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm">
                        <div className="space-y-4 px-4 pb-4 pt-4">
                          <div>
                            <p className="mb-1 flex items-center gap-2 text-sm font-medium text-[#023047]">
                              <Package className="h-4 w-4 shrink-0 text-primary" />
                              {PACKAGE_DETAIL.PACKAGE_NAME}
                            </p>
                            <p className="text-gray-900">{pkg?.name ?? "—"}</p>
                          </div>
                          <div className="border-t border-gray-100 pt-4">
                            <p className="mb-2 flex items-center gap-2 text-sm font-medium text-[#023047]">
                              <Info className="h-4 w-4 shrink-0 text-primary" />
                              {PACKAGE_DETAIL.OVERVIEW}
                            </p>
                            <p className="text-justify text-sm text-gray-700">
                              {locationDetail}
                            </p>
                          </div>
                        </div>
                      </Card>
                      {/* Tags: single row of cards */}
                      <div className="flex flex-nowrap gap-4 overflow-x-auto">
                        {((pkg as ApiFixPackageDetail)?.tag_names?.length
                          ? (pkg as ApiFixPackageDetail).tag_names!
                          : pkg?.package_theme
                            ? [pkg.package_theme]
                            : []
                        ).map((tagName, idx) => (
                          <Card
                            key={idx}
                            className="relative flex min-w-[5rem] w-max shrink-0 flex-col items-center justify-center rounded-lg border border-gray-200 bg-white px-4 py-3 shadow-sm"
                          >
                            <span className="whitespace-nowrap text-center text-xs font-medium text-gray-900">
                              {tagName}
                            </span>
                          </Card>
                        ))}
                      </div>
                      {/* Other Services: full-width row */}
                      <Card className="overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm">
                        <div className="px-4 pb-4">
                          <p className="mb-2 flex items-center gap-2 text-sm font-medium text-[#023047]">
                            <Settings className="h-4 w-4 shrink-0 text-primary" />
                            {PACKAGE_DETAIL.OTHER_SERVICES}
                          </p>
                          <ul className="flex flex-wrap gap-x-4 gap-y-2">
                            {(
                              (pkg?.other_services?.length
                                ? pkg.other_services
                                : (pkg as ApiFixPackageDetail)
                                    ?.service_names) ?? []
                            ).map((s, idx) => (
                              <li
                                key={idx}
                                className="flex items-center gap-2 text-sm text-gray-700"
                              >
                                <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-green-600">
                                  <Check className="h-3 w-3" />
                                </span>
                                <span>{s}</span>
                              </li>
                            ))}
                          </ul>
                        </div>
                      </Card>
                      {/* Sightseeing: full-width row */}
                      <Card className="overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm">
                        <div className="px-4 pb-4">
                          <p className="mb-2 flex items-center gap-2 text-sm font-medium text-[#023047]">
                            <Camera className="h-4 w-4 shrink-0 text-primary" />
                            {PACKAGE_DETAIL.SIGHTSEEING_LABEL}
                          </p>
                          <ul className="flex flex-wrap gap-x-4 gap-y-2">
                            {sightseeingList.map((name, idx) => (
                              <li
                                key={idx}
                                className="flex items-center gap-2 text-sm text-gray-700"
                              >
                                <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-green-600">
                                  <Check className="h-3 w-3" />
                                </span>
                                <span>{name}</span>
                              </li>
                            ))}
                          </ul>
                        </div>
                      </Card>

                      {/* Food: meal cards */}
                      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                        {(
                          [
                            {
                              label: PACKAGE_DETAIL.BREAKFAST,
                              Icon: Coffee,
                              key: "Breakfast" as const,
                              iconBg: "bg-orange-50 text-orange-500",
                            },
                            {
                              label: PACKAGE_DETAIL.LUNCH,
                              Icon: UtensilsCrossed,
                              key: "Lunch" as const,
                              iconBg: "bg-orange-50 text-orange-500",
                            },
                            {
                              label: PACKAGE_DETAIL.DINNER,
                              Icon: Wine,
                              key: "Dinner" as const,
                              iconBg: "bg-orange-50 text-orange-500",
                            },
                          ] as const
                        ).map(({ label, Icon, key, iconBg }) => {
                          const { included, excluded } = mealDaysByType[key];
                          const total = included.length + excluded.length;

                          return (
                            <div
                              key={label}
                              className="rounded-xl border border-gray-200 bg-white shadow-sm hover:shadow-md transition-shadow duration-200"
                            >
                              <div className="px-3 py-3 flex flex-col gap-2.5">
                                {/* Header row */}
                                <div className="flex items-center gap-2.5">
                                  <div
                                    className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${iconBg}`}
                                  >
                                    <Icon
                                      className="h-4 w-4"
                                      strokeWidth={1.8}
                                    />
                                  </div>
                                  <div className="min-w-0">
                                    <p className="text-sm font-semibold text-gray-900 leading-tight">
                                      {label}
                                    </p>
                                    <p className="text-[11px] text-gray-400">
                                      {included.length}/{total} days included
                                    </p>
                                  </div>
                                </div>

                                {/* Day info */}
                                {included.length > 0 ? (
                                  <div className="flex flex-wrap gap-1.5">
                                    {included.map((day) => (
                                      <span
                                        key={`inc-${day}`}
                                        className="rounded-full px-1.5 py-px text-[9px] font-medium bg-green-50 text-green-700 ring-1 ring-green-200"
                                      >
                                        Day {day}
                                      </span>
                                    ))}
                                  </div>
                                ) : (
                                  <p className="text-xs text-gray-400 italic">
                                    Not Included
                                  </p>
                                )}
                              </div>
                            </div>
                          );
                        })}
                      </div>

                      {/* Things to know: collapsible extras */}
                      <div className="space-y-3">
                        {extras.map((extra, idx) => (
                          <Card
                            key={idx}
                            className="overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm"
                          >
                            <Collapsible
                              open={thingsOpenIndices.has(idx)}
                              onOpenChange={(open) => setThingsOpen(idx, open)}
                            >
                              <CollapsibleTrigger asChild>
                                <button
                                  type="button"
                                  className="flex w-full items-center gap-2 px-4 py-3 text-left hover:bg-gray-50/80"
                                >
                                  <span className="flex flex-1 items-center gap-2 font-semibold text-gray-900">
                                    <Info className="h-4 w-4 shrink-0 text-primary" />
                                    <span className="text-[#023047]">
                                      {extra.title}
                                    </span>
                                  </span>
                                  {thingsOpenIndices.has(idx) ? (
                                    <ChevronUp className="h-4 w-4 shrink-0 text-gray-400" />
                                  ) : (
                                    <ChevronDown className="h-4 w-4 shrink-0 text-gray-400" />
                                  )}
                                </button>
                              </CollapsibleTrigger>
                              <CollapsibleContent>
                                <div className="border-t border-gray-100 px-4 pb-4 pt-3">
                                  <div className="text-sm text-gray-700 text-justify">
                                    <div className="quill">
                                      <div className="ql-editor">
                                        {extra.description ? (
                                          <div
                                            dangerouslySetInnerHTML={{
                                              __html: extra.description,
                                            }}
                                          />
                                        ) : (
                                          "—"
                                        )}
                                      </div>
                                    </div>
                                  </div>
                                </div>
                              </CollapsibleContent>
                            </Collapsible>
                          </Card>
                        ))}
                        {otherDetail ? (
                          <Card className="overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm">
                            <div className="px-4 pb-4 pt-4">
                              <h4 className="mb-2 font-semibold text-gray-900">
                                {PACKAGE_DETAIL.OTHER_DETAILS}
                              </h4>
                              <p className="text-justify text-sm text-gray-700">
                                {otherDetail}
                              </p>
                            </div>
                          </Card>
                        ) : null}
                      </div>
                    </div>
                  }
                  itineraryContent={
                    <>
                      {/* Horizontal date strip for itinerary days */}
                      {itineraryDays.length > 0 && (
                        <div
                          ref={dateStripRef}
                          className="mb-4 flex gap-2 overflow-x-auto pb-2 scrollbar-thin"
                        >
                          {itineraryDays.map((dayData) => {
                            const dayDate = start_date
                              ? addDays(new Date(start_date), dayData.day - 1)
                              : null;
                            const isActive = activeItineraryDay === dayData.day;
                            return (
                              <button
                                key={dayData.day}
                                type="button"
                                onClick={() => scrollToDay(dayData.day)}
                                className={`flex shrink-0 flex-col items-center rounded-lg border px-3 py-2 text-xs transition-colors ${
                                  isActive
                                    ? "border-[#023047] bg-[#023047] text-white shadow-md"
                                    : "border-gray-200 bg-white text-gray-700 hover:border-[#023047]/40 hover:bg-[#023047]/5"
                                }`}
                              >
                                {dayDate ? (
                                  <>
                                    <span className="font-medium leading-tight">
                                      {format(dayDate, "EEE")}
                                    </span>
                                    <span className="text-[11px] leading-tight">
                                      {format(dayDate, "d/M")}
                                    </span>
                                  </>
                                ) : (
                                  <span className="font-medium leading-tight whitespace-nowrap">
                                    {PACKAGE_DETAIL.DAY} {dayData.day}
                                  </span>
                                )}
                              </button>
                            );
                          })}
                        </div>
                      )}
                      <div className="space-y-6">
                        {itineraryDays.map((dayData) => (
                          <Card
                            key={dayData.day}
                            ref={(el) => {
                              dayCardRefs.current[dayData.day] = el;
                            }}
                            className="overflow-hidden border border-gray-200 shadow-sm scroll-mt-24"
                          >
                            <Collapsible
                              open={isDayCardOpen(dayData.day)}
                              onOpenChange={(o) =>
                                setDayCardOpenState(dayData.day, o)
                              }
                            >
                              {/* Day header - clickable to expand/collapse */}
                              <CollapsibleTrigger asChild>
                                <button
                                  type="button"
                                  className="flex w-full flex-wrap items-center gap-2 border-gray-100 bg-gray-50/80 px-4 py-2 text-left"
                                >
                                  <Badge
                                    className="rounded-sm px-2.5 py-2.5 bg-gradient-to-r frontend-btn text-white backdrop-blur-sm"
                                    style={{
                                      fontSize: "14px",
                                      fontWeight: "500",
                                    }}
                                  >
                                    Day {dayData.day}
                                    {start_date && (
                                      <span>
                                        {" - "}
                                        {format(
                                          addDays(
                                            new Date(start_date),
                                            dayData.day - 1
                                          ),
                                          "d MMM"
                                        )}
                                      </span>
                                    )}
                                  </Badge>
                                  <span className="font-bold text-secondary-foreground">
                                    {dayData.dayTitle ?? dayData.locationLabel}
                                  </span>
                                  <span className="ml-auto text-sm text-gray-500">
                                    {dayData.hotel
                                      ? `1 ${PACKAGE_DETAIL.HOTEL}`
                                      : `0 ${PACKAGE_DETAIL.HOTEL}`}
                                    {" · "}
                                    {dayData.travel
                                      ? `1 ${PACKAGE_DETAIL.TRAVEL}`
                                      : `0 ${PACKAGE_DETAIL.TRAVEL}`}
                                    {" · "}
                                    {dayData.sightseeings.length}{" "}
                                    {dayData.sightseeings.length === 1
                                      ? PACKAGE_DETAIL.SIGHTSEEING
                                      : PACKAGE_DETAIL.SIGHTSEEINGS}
                                    {" · "}
                                    {dayData.meals.length}{" "}
                                    {dayData.meals.length === 1
                                      ? PACKAGE_DETAIL.MEAL
                                      : PACKAGE_DETAIL.MEALS}
                                  </span>
                                  {isDayCardOpen(dayData.day) ? (
                                    <ChevronUp className="h-4 w-4 shrink-0 text-gray-400" />
                                  ) : (
                                    <ChevronDown className="h-4 w-4 shrink-0 text-gray-400" />
                                  )}
                                </button>
                              </CollapsibleTrigger>

                              <CollapsibleContent>
                                <div className="divide-y divide-gray-100 border-b border-gray-100 px-4 pb-4 pt-2">
                                  {dayData.description?.trim() && (
                                    <div className="mb-2 rounded-lg bg-white px-3 py-2">
                                      <p className="mb-1 text-sm font-semibold text-gray-900">
                                        {PACKAGE_DETAIL.DAY}{" "}
                                        {PACKAGE_DETAIL.OVERVIEW}
                                      </p>
                                      <div className="quill text-xs">
                                        <div className="ql-editor p-0">
                                          {dayData.description ? (
                                            <div
                                              dangerouslySetInnerHTML={{
                                                __html: dayData.description,
                                              }}
                                            />
                                          ) : (
                                            "—"
                                          )}
                                        </div>
                                      </div>
                                    </div>
                                  )}
                                  {/* Travel (label "Travel" not "Transfer") */}
                                  {dayData.travel && (
                                    <Collapsible
                                      open={isSectionOpen(
                                        `${dayData.day}-travel`
                                      )}
                                      onOpenChange={(o) =>
                                        setSectionOpen(
                                          `${dayData.day}-travel`,
                                          o
                                        )
                                      }
                                      className="border-t border-gray-100"
                                    >
                                      <div className="flex border-l-2 border-gray-200 px-4">
                                        <CollapsibleTrigger className="flex w-full items-start gap-3 py-3 text-left">
                                          <Car className="mt-0.5 h-4 w-4 shrink-0 text-gray-600" />
                                          <div className="min-w-0 flex-1">
                                            <span className="font-semibold uppercase tracking-wide text-gray-900">
                                              {PACKAGE_DETAIL.TRAVEL}
                                            </span>
                                          </div>
                                          {isSectionOpen(
                                            `${dayData.day}-travel`
                                          ) ? (
                                            <ChevronUp className="h-4 w-4 shrink-0 text-gray-400" />
                                          ) : (
                                            <ChevronDown className="h-4 w-4 shrink-0 text-gray-400" />
                                          )}
                                        </CollapsibleTrigger>
                                      </div>
                                      <CollapsibleContent>
                                        <div className="border-t border-gray-100 px-4 pb-4 pt-2">
                                          <div className="flex flex-col gap-3 rounded-2xl border border-gray-100 bg-slate-50/80 p-3 shadow-sm sm:flex-row sm:items-center sm:gap-4">
                                            <div className="flex items-center gap-3 sm:w-2/3">
                                              <div className="h-14 w-16 shrink-0 overflow-hidden rounded-lg bg-gray-200 shadow-xs">
                                                {dayData.travel.image ? (
                                                  <img
                                                    src={getStorageUrl(
                                                      dayData.travel.image
                                                    )}
                                                    alt=""
                                                    className="h-full w-full object-cover"
                                                  />
                                                ) : (
                                                  <div className="flex h-full items-center justify-center">
                                                    <Car className="h-5 w-5 text-gray-400" />
                                                  </div>
                                                )}
                                              </div>
                                              <div className="min-w-0 flex-1">
                                                <p className="text-sm font-semibold leading-tight text-gray-900">
                                                  {dayData.travel.vehicleName}
                                                </p>
                                                <div className="flex flex-wrap items-center gap-2 text-[11px] text-gray-600">
                                                  {dayData.travel
                                                    .vehicleType && (
                                                    <span className="font-medium text-gray-700">
                                                      {
                                                        dayData.travel
                                                          .vehicleType
                                                      }
                                                    </span>
                                                  )}
                                                </div>
                                                {(dayData.travel.pickupPoint ||
                                                  dayData.travel.dropPoint) && (
                                                  <div className="mt-2 flex flex-wrap gap-2">
                                                    {dayData.travel
                                                      .pickupPoint && (
                                                      <span className="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-1 text-[11px] text-gray-700">
                                                        <MapPin className="h-3 w-3 text-gray-500" />
                                                        Pickup:{" "}
                                                        {
                                                          dayData.travel
                                                            .pickupPoint
                                                        }
                                                      </span>
                                                    )}
                                                    {dayData.travel
                                                      .dropPoint && (
                                                      <span className="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-1 text-[11px] text-gray-700">
                                                        <MapPin className="h-3 w-3 text-gray-500" />
                                                        Drop:{" "}
                                                        {
                                                          dayData.travel
                                                            .dropPoint
                                                        }
                                                      </span>
                                                    )}
                                                  </div>
                                                )}
                                              </div>
                                            </div>
                                            {dayData.travel.specs && (
                                              <div className="flex items-start gap-2 rounded-xl bg-blue-50 px-3 py-2 sm:w-3/5">
                                                <Sparkles className="mt-0.5 h-4 w-4 text-[#0f3c71]" />
                                                <div className="min-w-0">
                                                  <p className="text-xs font-semibold text-gray-900">
                                                    Add Transfers to your day
                                                  </p>
                                                  <p className="text-[11px] leading-snug text-gray-700 line-clamp-2">
                                                    {dayData.travel.specs}
                                                  </p>
                                                </div>
                                              </div>
                                            )}
                                          </div>
                                        </div>
                                      </CollapsibleContent>
                                    </Collapsible>
                                  )}

                                  {/* Hotel - show whenever hotel data exists */}
                                  {dayData.hotel && (
                                    <Collapsible
                                      open={isSectionOpen(
                                        `${dayData.day}-hotel`
                                      )}
                                      onOpenChange={(o) =>
                                        setSectionOpen(
                                          `${dayData.day}-hotel`,
                                          o
                                        )
                                      }
                                    >
                                      <div className="flex border-l-2 border-gray-200 px-4">
                                        <CollapsibleTrigger className="flex w-full items-start gap-3 py-3 text-left">
                                          <Hotel className="mt-0.5 h-4 w-4 shrink-0 text-gray-600" />
                                          <div className="min-w-0 flex-1">
                                            <span className="font-semibold uppercase tracking-wide text-gray-900">
                                              {PACKAGE_DETAIL.HOTEL}
                                            </span>
                                          </div>
                                          {isSectionOpen(
                                            `${dayData.day}-hotel`
                                          ) ? (
                                            <ChevronUp className="h-4 w-4 shrink-0 text-gray-400" />
                                          ) : (
                                            <ChevronDown className="h-4 w-4 shrink-0 text-gray-400" />
                                          )}
                                        </CollapsibleTrigger>
                                      </div>
                                      <CollapsibleContent>
                                        {(() => {
                                          const hotel = dayData.hotel!;
                                          return (
                                            <div className="border-t border-gray-100 px-4 pb-4 pt-2">
                                              <div className="flex flex-col gap-3 rounded-2xl border border-gray-100 bg-slate-50/80 p-3 shadow-sm sm:flex-row sm:items-center sm:gap-4">
                                                <div className="flex items-center gap-3 sm:w-2/3">
                                                  <div className="h-16 w-20 shrink-0 overflow-hidden rounded-lg bg-gray-200 shadow-xs">
                                                    {hotel.image ? (
                                                      <img
                                                        src={getStorageUrl(
                                                          hotel.image
                                                        )}
                                                        alt=""
                                                        className="h-full w-full object-cover"
                                                      />
                                                    ) : (
                                                      <div className="flex h-full w-full items-center justify-center text-gray-500">
                                                        <Hotel className="h-5 w-5 text-gray-400" />
                                                      </div>
                                                    )}
                                                  </div>
                                                  <div className="min-w-0 flex-1">
                                                    <p className="text-sm font-semibold leading-tight text-gray-900 line-clamp-2">
                                                      {hotel.name?.trim() ||
                                                        "Hotel"}
                                                    </p>
                                                    <div className="flex items-center gap-2 text-[11px] italic text-gray-600">
                                                      {hotel.star && (
                                                        <div className="flex items-center gap-0.5 not-italic">
                                                          {Array.from(
                                                            { length: 5 },
                                                            (_, idx) => {
                                                              const starCount =
                                                                Number(
                                                                  hotel.star?.match(
                                                                    /\d+/
                                                                  )?.[0] ?? 0
                                                                );
                                                              const active =
                                                                idx < starCount;
                                                              return (
                                                                <Star
                                                                  key={idx}
                                                                  className={`h-3 w-3 ${
                                                                    active
                                                                      ? "fill-amber-400 text-amber-400"
                                                                      : "text-gray-300"
                                                                  }`}
                                                                />
                                                              );
                                                            }
                                                          )}
                                                        </div>
                                                      )}
                                                      <span>
                                                        {hotel.hotelType}
                                                      </span>
                                                    </div>
                                                    <div className="mt-1 flex flex-wrap items-center gap-2 text-[11px] text-gray-600">
                                                      {hotel.landmark && (
                                                        <span className="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-1">
                                                          <MapPin className="h-3 w-3 text-gray-500" />
                                                          {hotel.landmark}
                                                        </span>
                                                      )}
                                                      {hotel.checkIn && (
                                                        <span className="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-1">
                                                          <Clock4 className="h-3 w-3 text-gray-500" />
                                                          Check-in{" "}
                                                          {hotel.checkIn}
                                                        </span>
                                                      )}
                                                      {hotel.checkOut && (
                                                        <span className="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-1">
                                                          <Clock4 className="h-3 w-3 text-gray-500" />
                                                          Check-out{" "}
                                                          {hotel.checkOut}
                                                        </span>
                                                      )}
                                                    </div>
                                                  </div>
                                                </div>
                                                {hotel.description && (
                                                  <div className="flex items-start gap-2 rounded-xl bg-gray-100 px-3 py-2 sm:w-1/3">
                                                    <FileText className="mt-0.5 h-4 w-4 text-[#0f3c71]" />
                                                    <div className="min-w-0">
                                                      <p className="text-xs font-semibold text-gray-900">
                                                        Nearby & Stay Info
                                                      </p>

                                                      <p className="text-[11px] leading-snug text-gray-700 line-clamp-2">
                                                        {hotel.description?.trim() ||
                                                          ""}
                                                      </p>
                                                    </div>
                                                  </div>
                                                )}
                                              </div>
                                            </div>
                                          );
                                        })()}
                                      </CollapsibleContent>
                                    </Collapsible>
                                  )}

                                  {/* Sightseeings */}
                                  {dayData.sightseeings.length > 0 && (
                                    <Collapsible
                                      open={isSectionOpen(
                                        `${dayData.day}-sightseeing`
                                      )}
                                      onOpenChange={(o) =>
                                        setSectionOpen(
                                          `${dayData.day}-sightseeing`,
                                          o
                                        )
                                      }
                                    >
                                      <div className="flex border-l-2 border-gray-200 px-4">
                                        <CollapsibleTrigger className="flex w-full items-start gap-3 py-3 text-left">
                                          <Landmark className="mt-0.5 h-4 w-4 shrink-0 text-gray-600" />
                                          <div className="min-w-0 flex-1">
                                            <span className="font-semibold uppercase tracking-wide text-gray-900">
                                              {PACKAGE_DETAIL.SIGHTSEEING}
                                            </span>
                                          </div>
                                          {isSectionOpen(
                                            `${dayData.day}-sightseeing`
                                          ) ? (
                                            <ChevronUp className="h-4 w-4 shrink-0 text-gray-400" />
                                          ) : (
                                            <ChevronDown className="h-4 w-4 shrink-0 text-gray-400" />
                                          )}
                                        </CollapsibleTrigger>
                                      </div>
                                      <CollapsibleContent>
                                        <div className="border-t border-gray-100 px-4 pb-4 pt-2">
                                          <div className="flex flex-nowrap gap-3 overflow-x-auto">
                                            {dayData.sightseeings.map(
                                              (s, idx) => (
                                                <div
                                                  key={idx}
                                                  className="relative h-32 w-40 shrink-0 overflow-hidden rounded-lg bg-gray-200"
                                                >
                                                  {s.image ? (
                                                    <img
                                                      src={getStorageUrl(
                                                        s.image
                                                      )}
                                                      alt=""
                                                      className="h-full w-full object-cover"
                                                    />
                                                  ) : (
                                                    <div className="flex h-full w-full items-center justify-center">
                                                      <Landmark className="h-10 w-10 text-gray-400" />
                                                    </div>
                                                  )}
                                                  <div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2">
                                                    <p className="text-sm font-semibold text-white line-clamp-2">
                                                      {s.title}
                                                    </p>
                                                  </div>
                                                </div>
                                              )
                                            )}
                                          </div>
                                        </div>
                                      </CollapsibleContent>
                                    </Collapsible>
                                  )}

                                  {/* Meals - combined into one section when we have breakfast, lunch, dinner */}
                                  {dayData.meals.length > 0 && (
                                    <Collapsible
                                      open={isSectionOpen(
                                        `${dayData.day}-meals`
                                      )}
                                      onOpenChange={(o) =>
                                        setSectionOpen(
                                          `${dayData.day}-meals`,
                                          o
                                        )
                                      }
                                      className="border-b border-gray-100"
                                    >
                                      <div className="flex border-l-2 border-gray-200 px-4">
                                        <CollapsibleTrigger className="flex w-full items-start gap-3 py-3 text-left">
                                          <UtensilsCrossed className="mt-0.5 h-4 w-4 shrink-0 text-gray-600" />
                                          <div className="min-w-0 flex-1">
                                            <span className="font-semibold uppercase tracking-wide text-gray-900">
                                              {PACKAGE_DETAIL.MEALS}
                                            </span>
                                          </div>
                                          {isSectionOpen(
                                            `${dayData.day}-meals`
                                          ) ? (
                                            <ChevronUp className="h-4 w-4 shrink-0 text-gray-400" />
                                          ) : (
                                            <ChevronDown className="h-4 w-4 shrink-0 text-gray-400" />
                                          )}
                                        </CollapsibleTrigger>
                                      </div>
                                      <CollapsibleContent>
                                        <div className="border-l-2 border-gray-200 border-t border-gray-100 pl-4 pb-3 pt-2">
                                          <div className="flex flex-nowrap gap-4 overflow-x-auto">
                                            {dayData.meals.map((meal, idx) => (
                                              <div
                                                key={idx}
                                                className="min-w-0 shrink-0 flex-1 rounded-xl border border-gray-200 bg-white p-4 shadow-sm"
                                              >
                                                <p className="font-medium text-gray-900">
                                                  {meal.type}
                                                </p>
                                                {meal.description && (
                                                  <p className="mt-1 text-sm text-gray-600 line-clamp-2">
                                                    {meal.description}
                                                  </p>
                                                )}
                                                <p
                                                  className="mt-2 flex items-center gap-2 text-sm font-medium"
                                                  style={{ color: "#023047" }}
                                                >
                                                  <Check className="h-4 w-4 shrink-0" />
                                                  {PACKAGE_DETAIL.INCLUDED_WITH}{" "}
                                                  {meal.includedWith}
                                                </p>
                                              </div>
                                            ))}
                                          </div>
                                        </div>
                                      </CollapsibleContent>
                                    </Collapsible>
                                  )}
                                </div>
                              </CollapsibleContent>
                            </Collapsible>
                          </Card>
                        ))}
                      </div>
                    </>
                  }
                  servicesContent={
                    <div className="space-y-4">
                      <Card className="overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm">
                        <div className="px-4 pb-4">
                          <p className="mb-2 flex items-center gap-2 text-sm font-medium text-[#023047]">
                            <Settings className="h-4 w-4 shrink-0" />
                            {PACKAGE_DETAIL.OTHER_SERVICES}
                          </p>
                          <ul className="flex flex-wrap gap-x-4 gap-y-2">
                            {(
                              (pkg?.other_services?.length
                                ? pkg.other_services
                                : (pkg as ApiFixPackageDetail)
                                    ?.service_names) ?? []
                            ).map((s, idx) => (
                              <li
                                key={idx}
                                className="flex items-center gap-2 text-sm text-gray-700"
                              >
                                <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-green-600">
                                  <Check className="h-3 w-3" />
                                </span>
                                <span>{s}</span>
                              </li>
                            ))}
                          </ul>
                        </div>
                      </Card>
                      <Card className="overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm">
                        <h3 className="border-b border-gray-100 px-4 pb-3 pt-2 text-lg font-semibold text-gray-900">
                          {PACKAGE_DETAIL.WHATS_INSIDE}
                        </h3>
                        <div className="grid grid-cols-1 gap-6 px-4 pb-4 pt-2 md:grid-cols-2">
                          <div>
                            <h4 className="mb-3 font-semibold text-gray-900">
                              {PACKAGE_DETAIL.INCLUSIONS}
                            </h4>
                            <ul className="space-y-2">
                              {inclusionList.map((item, idx) => (
                                <li
                                  key={idx}
                                  className="flex items-start gap-2 text-sm text-gray-700"
                                >
                                  <span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-green-100 text-green-600">
                                    <Check className="h-3 w-3" />
                                  </span>
                                  <span>{item}</span>
                                </li>
                              ))}
                            </ul>
                          </div>
                          <div>
                            <h4 className="mb-3 font-semibold text-gray-900">
                              {PACKAGE_DETAIL.EXCLUSIONS}
                            </h4>
                            <ul className="space-y-2">
                              {exclusionList.map((item, idx) => (
                                <li
                                  key={idx}
                                  className="flex items-start gap-2 text-sm text-gray-700"
                                >
                                  <span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-red-100 text-red-600">
                                    <X className="h-3 w-3" />
                                  </span>
                                  <span>{item}</span>
                                </li>
                              ))}
                            </ul>
                          </div>
                        </div>
                      </Card>
                    </div>
                  }
                  foodContent={
                    <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                      {(
                        [
                          {
                            label: PACKAGE_DETAIL.BREAKFAST,
                            Icon: Coffee,
                            key: "Breakfast" as const,
                            iconBg: "bg-orange-50 text-orange-500",
                          },
                          {
                            label: PACKAGE_DETAIL.LUNCH,
                            Icon: UtensilsCrossed,
                            key: "Lunch" as const,
                            iconBg: "bg-orange-50 text-orange-500",
                          },
                          {
                            label: PACKAGE_DETAIL.DINNER,
                            Icon: Wine,
                            key: "Dinner" as const,
                            iconBg: "bg-orange-50 text-orange-500",
                          },
                        ] as const
                      ).map(({ label, Icon, key, iconBg }) => {
                        const { included, excluded } = mealDaysByType[key];
                        const total = included.length + excluded.length;

                        return (
                          <div
                            key={label}
                            className="rounded-xl border border-gray-200 bg-white shadow-sm hover:shadow-md transition-shadow duration-200"
                          >
                            <div className="px-3 py-3 flex flex-col gap-2.5">
                              {/* Header row */}
                              <div className="flex items-center gap-2.5">
                                <div
                                  className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${iconBg}`}
                                >
                                  <Icon className="h-4 w-4" strokeWidth={1.8} />
                                </div>
                                <div className="min-w-0">
                                  <p className="text-sm font-semibold text-gray-900 leading-tight">
                                    {label}
                                  </p>
                                  <p className="text-[11px] text-gray-400">
                                    {included.length}/{total} days included
                                  </p>
                                </div>
                              </div>

                              {/* Day info */}
                              {included.length > 0 ? (
                                <div className="flex flex-wrap gap-1.5">
                                  {included.map((day) => (
                                    <span
                                      key={`inc-${day}`}
                                      className="rounded-full px-1.5 py-px text-[9px] font-medium bg-green-50 text-green-700 ring-1 ring-green-200"
                                    >
                                      Day {day}
                                    </span>
                                  ))}
                                </div>
                              ) : (
                                <p className="text-xs text-gray-400 italic">
                                  Not Included
                                </p>
                              )}
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  }
                  thingsToKnowContent={
                    <div className="space-y-3">
                      {extras.map((extra, idx) => (
                        <Card
                          key={idx}
                          className="overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm"
                        >
                          <Collapsible
                            open={thingsOpenIndices.has(idx)}
                            onOpenChange={(open) => setThingsOpen(idx, open)}
                          >
                            <CollapsibleTrigger asChild>
                              <button
                                type="button"
                                className="flex w-full items-center gap-2 px-4 py-3 text-left hover:bg-gray-50/80"
                              >
                                <span className="flex flex-1 items-center gap-2 font-semibold text-gray-900">
                                  <Info className="h-4 w-4 shrink-0 text-primary" />
                                  <span className="text-[#023047]">
                                    {extra.title}
                                  </span>
                                </span>
                                {thingsOpenIndices.has(idx) ? (
                                  <ChevronUp className="h-4 w-4 shrink-0 text-gray-400" />
                                ) : (
                                  <ChevronDown className="h-4 w-4 shrink-0 text-gray-400" />
                                )}
                              </button>
                            </CollapsibleTrigger>
                            <CollapsibleContent>
                              <div className="border-t border-gray-100 px-4 pb-4 pt-3">
                                <div className="text-sm text-gray-700 text-justify">
                                  <div className="quill">
                                    <div className="ql-editor">
                                      {extra.description ? (
                                        <div
                                          dangerouslySetInnerHTML={{
                                            __html: extra.description,
                                          }}
                                        />
                                      ) : (
                                        "—"
                                      )}
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </CollapsibleContent>
                          </Collapsible>
                        </Card>
                      ))}
                    </div>
                  }
                />
              </CardContent>
            </Card>
          </div>

          {/* Right 30%: Price card (lg only) + Passenger Details + Booking Summary (sticky on desktop; bottom on small screens) */}
          <div className="order-2 space-y-6">
            {/* Price card: desktop only, above Passenger Details — discount left, actual price right */}
            <div className="hidden w-full lg:block">
              <Card className="w-full overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm">
                <CardContent className="flex w-full items-center justify-between gap-3 px-4">
                  <div className="flex flex-wrap items-baseline gap-1.5">
                    <span
                      className={
                        discount > 0
                          ? "text-base font-medium text-gray-500 line-through"
                          : "text-base font-medium text-gray-700"
                      }
                    >
                      ₹{originalPrice.toLocaleString()}
                    </span>
                    {discount > 0 && (
                      <span className="text-sm font-semibold text-red-600">
                        {discount}
                        {PACKAGE_DETAIL.PERCENT_OFF}
                      </span>
                    )}
                  </div>
                  <div className="flex flex-wrap items-baseline gap-1.5">
                    <span className="text-2xl font-bold text-gray-900">
                      ₹{discountedPrice.toLocaleString()}
                    </span>
                    <span className="text-xs text-gray-600">
                      {PACKAGE_DETAIL.PER_PERSON}
                    </span>
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* Passenger Details */}
            <PassengerDetailsCard
              customer={customers[0]}
              isLoggedIn={isLoggedIn}
              loginUrl="/login"
              onUpdate={(field, value) =>
                updateCustomer(customers[0].id, field, value)
              }
              showAllErrors={hasAttemptedBooking}
            />

            <Card className="sticky top-24 overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm">
              <div className="border-b border-gray-100 px-4 py-3">
                <h3 className="flex items-center gap-2 text-lg font-semibold text-gray-900">
                  <FileText className="h-5 w-5 text-primary" />
                  {PACKAGE_DETAIL.BOOKING_SUMMARY}
                </h3>
              </div>
              <CardContent className="space-y-5 p-4">
                <div className="space-y-2">
                  <div className="flex items-center justify-between gap-2">
                    <span className="shrink-0 text-sm text-gray-600">
                      {PACKAGE_DETAIL.SELECT_CHECKIN_DATE}
                    </span>
                    <div className="min-w-0">
                      <Popover>
                        <PopoverTrigger asChild>
                          <button
                            type="button"
                            className={`flex h-8 items-center rounded-md border bg-background px-3 py-1.5 text-sm font-medium text-gray-900 shadow-xs outline-none hover:bg-accent/50 focus-visible:ring-2 focus-visible:ring-ring [&_svg]:pointer-events-none [&_svg]:shrink-0 ${hasAttemptedBooking && !datePickerValue ? "border-red-400 ring-1 ring-red-400" : "border-input"}`}
                          >
                            <CalendarIcon className="mr-1.5 h-3.5 w-3.5 shrink-0 text-gray-500" />
                            <span className="whitespace-nowrap">
                              {datePickerValue
                                ? format(datePickerValue, "PPP")
                                : PACKAGE_DETAIL.SELECT_DATE}
                            </span>
                          </button>
                        </PopoverTrigger>
                        <PopoverContent
                          className="w-auto p-0 z-[100]"
                          align="center"
                        >
                          <DateCalendar
                            mode="single"
                            selected={datePickerValue ?? undefined}
                            onSelect={(date) => {
                              setDatePickerValue(date);
                              if (date) {
                                setstart_date(format(date, "yyyy-MM-dd"));
                              }
                            }}
                            fromDate={firstEnabledDate}
                            toDate={calendarToDate}
                            defaultMonth={firstEnabledDate}
                            disabled={(date) => {
                              const dayStart = toDayStart(date);
                              if (dayStart.getTime() < todayStart.getTime())
                                return true;
                              if (
                                pkgStartDate &&
                                dayStart.getTime() < pkgStartDate.getTime()
                              )
                                return true;
                              if (
                                pkgEndDate &&
                                dayStart.getTime() > pkgEndDate.getTime()
                              )
                                return true;
                              return false;
                            }}
                            initialFocus
                          />
                        </PopoverContent>
                      </Popover>
                    </div>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">
                      {PACKAGE_DETAIL.ADULTS_LABEL} &times;{" "}
                      {pricing.adultsCount}
                    </span>
                    <span className="font-medium text-gray-900">
                      ₹{pricing.adultTotal.toLocaleString()}
                    </span>
                  </div>
                  {pricing.childAdultsCount > 0 && (
                    <div className="flex items-center justify-between text-sm">
                      <span className="flex items-center gap-1.5 text-gray-600">
                        {PACKAGE_DETAIL.CHILDREN_LABEL} &times;{" "}
                        {pricing.childAdultsCount}
                        <Badge variant="softInfo" size="sm">
                          {PACKAGE_DETAIL.ADULT_FULL}
                        </Badge>
                      </span>
                      <span className="font-medium text-gray-900">
                        ₹{pricing.childAdultTotal.toLocaleString()}
                      </span>
                    </div>
                  )}
                  {pricing.childrenCount > 0 && (
                    <div className="flex items-center justify-between text-sm">
                      <span className="flex items-center gap-1.5 text-gray-600">
                        {PACKAGE_DETAIL.CHILDREN_LABEL} &times;{" "}
                        {pricing.childrenCount}
                        <Badge variant="softWarning" size="sm">
                          {PACKAGE_DETAIL.CHILD_50}
                        </Badge>
                      </span>
                      <span className="font-medium text-gray-900">
                        ₹{pricing.childTotal.toLocaleString()}
                      </span>
                    </div>
                  )}
                  {pricing.infantsCount > 0 && (
                    <div className="flex items-center justify-between text-sm">
                      <span className="flex items-center gap-1.5 text-gray-600">
                        {PACKAGE_DETAIL.INFANTS_LABEL} &times;{" "}
                        {pricing.infantsCount}
                        <Badge variant="softSuccess" size="sm">
                          {PACKAGE_DETAIL.FREE}
                        </Badge>
                      </span>
                      <span className="font-medium text-gray-900">₹0</span>
                    </div>
                  )}
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">
                      {PACKAGE_DETAIL.DURATION}
                    </span>
                    <span className="font-medium text-gray-900">
                      {displayDays} {PACKAGE_DETAIL.DAYS}
                    </span>
                  </div>
                </div>

                <div className="space-y-2 border-t border-gray-200 pt-4">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">
                      {PACKAGE_DETAIL.PACKAGE_COST}
                    </span>
                    <span className="font-medium text-gray-900">
                      ₹{pricing.subtotal.toLocaleString()}
                    </span>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">
                      {PACKAGE_DETAIL.GST_18}
                    </span>
                    <span className="font-medium text-gray-900">
                      ₹{pricing.gst.toLocaleString()}
                    </span>
                  </div>
                </div>

                <div className="border-t-2 border-gray-200 pt-4">
                  <div className="flex items-center justify-between gap-2">
                    <span className="text-base font-bold text-gray-900">
                      {PACKAGE_DETAIL.TOTAL_AMOUNT}
                    </span>
                    <div className="flex items-center gap-1 text-xl font-bold text-primary">
                      <IndianRupee className="h-5 w-5 shrink-0" />
                      <span>{pricing.total.toLocaleString()}</span>
                    </div>
                  </div>
                </div>

                <Button
                  onClick={handleBooking}
                  disabled={isSubmitting}
                  className="w-full h-12 text-base text-white shadow-sm transition-opacity hover:opacity-95"
                  style={{ backgroundColor: "#023047" }}
                >
                  {isSubmitting ? (
                    <>
                      <Loader2 className="mr-2 h-5 w-5 animate-spin" />
                      {PACKAGE_DETAIL.PROCESSING}
                    </>
                  ) : (
                    <>
                      <Check className="mr-2 h-5 w-5" />
                      {PACKAGE_DETAIL.CONFIRM_BOOKING}
                    </>
                  )}
                </Button>

                <p className="text-center text-xs text-gray-500">
                  {PACKAGE_DETAIL.TERMS_DISCLAIMER}
                </p>
              </CardContent>
            </Card>
          </div>
        </div>
      </main>
    </div>
  );
}
