"use client";

import { useCallback, useEffect, useMemo, useState } from "react";

import Link from "next/link";
import { useRouter } from "next/navigation";

import { Check, ChevronLeft, ChevronRight } from "lucide-react";
import { toast } from "sonner";

import { CABIN_CATEGORIES } from "@/components/admin/cruise-admin-constants";
import { CabinGrid } from "@/components/cruise/deck-plan-viewer";
import { PaymentCloudCheckout, type PaymentCloudResult } from "@/components/payments/payment-cloud-checkout";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Progress } from "@/components/ui/progress";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { getAuthUser } from "@/lib/auth";
import { notifyPaymentFailure } from "@/lib/automations";
import { defaultPaymentPlanForSailing } from "@/lib/event-form-utils";
import {
  applyPromoDiscount,
  createBooking,
  getAddOnsForSailing,
  getCabinsBySailing,
  getGuestByEmail,
  getGuestById,
  getGuestByUserId,
  holdCabin,
  releaseCabinHold,
  saveGuest,
  validatePromoCode,
} from "@/lib/cruise-store";
import { cn, formatCurrency } from "@/lib/utils";
import type {
  AddOn,
  BookingAddOn,
  EmergencyContact,
  PaymentPlanType,
  Sailing,
  TravelerInfo,
  WaiverStatus,
} from "@/types/cruise";

const STEPS = [
  "Party & Cabin",
  "Select Cabin",
  "Add-ons",
  "Guest Info",
  "Travel Details",
  "Review",
  "Payment",
];

interface WizardState {
  step: number;
  partySize: number;
  cabinCategory: string;
  cabinAssignmentType: "specific" | "random";
  cabinId?: string;
  selectedAddOnIds: string[];
  travelers: TravelerInfo[];
  guestName: string;
  guestEmail: string;
  guestPhone: string;
  guestId?: string;
  emergencyContact: EmergencyContact;
  promoCode: string;
  promoCodeId?: string;
  referralCode: string;
  paymentPlanType: PaymentPlanType;
  paymentScheduleTemplateId?: string;
  autoPayEnabled: boolean;
  paymentComplete: boolean;
  depositPaid: number;
  waiverStatus: WaiverStatus;
  travelInfo: {
    flightNumber: string;
    arrivalDate: string;
    specialRequests: string;
  };
}

function defaultTravelers(count: number): TravelerInfo[] {
  return Array.from({ length: count }, (_, i) => ({
    id: `tr-${Date.now()}-${i}`,
    firstName: "",
    lastName: "",
    dateOfBirth: "",
    passportNumber: "",
    passportExpiry: "",
    passportCountry: "",
  }));
}

function defaultState(sailing: Sailing): WizardState {
  return {
    step: 1,
    partySize: 2,
    cabinCategory: "Interior",
    cabinAssignmentType: "random",
    selectedAddOnIds: [],
    travelers: defaultTravelers(2),
    guestName: "",
    guestEmail: "",
    guestPhone: "",
    emergencyContact: { name: "", phone: "", relationship: "" },
    promoCode: "",
    referralCode: "",
    paymentPlanType: defaultPaymentPlanForSailing(sailing),
    autoPayEnabled: true,
    paymentComplete: false,
    depositPaid: 0,
    waiverStatus: {
      termsAccepted: false,
      liabilityWaiver: false,
      photoRelease: false,
      medicalForm: false,
    },
    travelInfo: { flightNumber: "", arrivalDate: "", specialRequests: "" },
  };
}

function wizardKey(sailingId: string) {
  return `cruise_wizard_${sailingId}`;
}

function computeWizardPricing(
  wizardState: WizardState,
  sailing: Sailing,
  addOns: AddOn[],
) {
  let subtotal = sailing.basePrice * wizardState.partySize;
  if (wizardState.cabinAssignmentType === "specific") {
    subtotal += sailing.cabinSelectionUpgradeFee;
  }
  for (const id of wizardState.selectedAddOnIds) {
    const addon = addOns.find((a) => a.id === id);
    if (addon) subtotal += addon.price;
  }
  let discount = 0;
  let promoCodeId: string | undefined;
  if (wizardState.promoCode.trim()) {
    const result = validatePromoCode(wizardState.promoCode.trim(), sailing.id);
    if ("promo" in result) {
      discount = applyPromoDiscount(result.promo, subtotal);
      promoCodeId = result.promo.id;
    }
  }
  const total = Math.max(0, subtotal - discount);
  const depositPaid =
    wizardState.paymentComplete && wizardState.depositPaid > 0
      ? wizardState.depositPaid
      : wizardState.paymentPlanType === "full"
        ? total
        : sailing.depositAmount;
  return { subtotal, discount, total, depositPaid, promoCodeId };
}

interface BookingWizardProps {
  sailing: Sailing;
}

export function BookingWizard({ sailing }: BookingWizardProps) {
  const router = useRouter();
  const sessionId = useMemo(() => `sess-${sailing.id}-${Date.now()}`, [sailing.id]);
  const storageKey = wizardKey(sailing.id);

  const [state, setState] = useState<WizardState>(() => defaultState(sailing));
  const [hydrated, setHydrated] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  const addOns = useMemo(() => getAddOnsForSailing(sailing.id), [sailing.id]);
  const cabins = useMemo(() => getCabinsBySailing(sailing.id), [sailing.id]);
  const filteredCabins = useMemo(
    () => cabins.filter((c) => c.category === state.cabinCategory),
    [cabins, state.cabinCategory],
  );

  const persist = useCallback(
    (next: WizardState) => {
      setState(next);
      if (typeof window !== "undefined") {
        sessionStorage.setItem(storageKey, JSON.stringify(next));
      }
    },
    [storageKey],
  );

  useEffect(() => {
    const saved = sessionStorage.getItem(storageKey);
    if (saved) {
      try {
        setState(JSON.parse(saved) as WizardState);
      } catch {
        /* ignore */
      }
    }
    const user = getAuthUser();
    if (user?.role === "client") {
      const guest = getGuestByUserId(user.id) ?? getGuestByEmail(user.email);
      setState((prev) => ({
        ...prev,
        guestName: guest?.name ?? user.name,
        guestEmail: guest?.email ?? user.email,
        guestPhone: guest?.phone ?? prev.guestPhone,
        guestId: guest?.id,
      }));
    }
    setHydrated(true);
  }, [storageKey]);

  useEffect(() => {
    if (state.cabinId && state.cabinAssignmentType === "specific") {
      holdCabin(state.cabinId, sessionId);
    }
    return () => {
      if (state.cabinId) releaseCabinHold(state.cabinId, sessionId);
    };
  }, [state.cabinId, state.cabinAssignmentType, sessionId]);

  const pricing = useMemo(
    () => computeWizardPricing(state, sailing, addOns),
    [state, sailing, addOns],
  );

  const updatePartySize = (size: number) => {
    const travelers = [...state.travelers];
    while (travelers.length < size) {
      travelers.push({
        id: `tr-${Date.now()}-${travelers.length}`,
        firstName: "",
        lastName: "",
        dateOfBirth: "",
      });
    }
    while (travelers.length > size) travelers.pop();
    persist({ ...state, partySize: size, travelers });
  };

  const resolveGuestId = (wizardState: WizardState): string => {
    const email = wizardState.guestEmail.trim();
    const user = getAuthUser();
    const existing = getGuestByEmail(email);

    if (existing) {
      saveGuest({
        ...existing,
        name: wizardState.guestName.trim() || existing.name,
        phone: wizardState.guestPhone.trim() || existing.phone,
        userId: user?.role === "client" ? user.id : existing.userId,
      });
      return existing.id;
    }

    if (wizardState.guestId) {
      const linked = getGuestById(wizardState.guestId);
      if (linked && linked.email.toLowerCase() === email.toLowerCase()) {
        saveGuest({
          ...linked,
          name: wizardState.guestName.trim() || linked.name,
          phone: wizardState.guestPhone.trim() || linked.phone,
        });
        return linked.id;
      }
    }

    const id = `guest-${Date.now()}`;
    saveGuest({
      id,
      userId: user?.role === "client" ? user.id : undefined,
      name: wizardState.guestName.trim(),
      email,
      phone: wizardState.guestPhone.trim(),
      createdAt: new Date().toISOString().slice(0, 10),
    });
    return id;
  };

  const validateStep = (step: number): string | null => {
    switch (step) {
      case 1:
        if (state.partySize < 1) return "Select party size.";
        return null;
      case 2:
        if (state.cabinAssignmentType === "specific" && !state.cabinId) {
          return "Select a cabin or choose random assignment.";
        }
        return null;
      case 4:
        if (!state.guestName.trim() || !state.guestEmail.includes("@") || !state.guestPhone.trim()) {
          return "Complete guest contact information.";
        }
        for (const t of state.travelers) {
          if (!t.firstName.trim() || !t.lastName.trim() || !t.dateOfBirth) {
            return "Complete traveler names and dates of birth.";
          }
          if (!t.passportNumber?.trim()) {
            return "Passport number required for each traveler.";
          }
          if (!t.passportExpiry) {
            return "Passport expiry required for each traveler.";
          }
          if (!t.passportCountry?.trim()) {
            return "Passport country required for each traveler.";
          }
        }
        return null;
      case 5:
        if (!state.waiverStatus.termsAccepted) {
          return "Accept the terms and conditions to continue.";
        }
        if (!state.emergencyContact.name || !state.emergencyContact.phone) {
          return "Emergency contact is required.";
        }
        return null;
      case 6:
        return null;
      case 7:
        if (!state.paymentComplete) return "Complete payment to confirm your booking.";
        return null;
      default:
        return null;
    }
  };

  const goNext = () => {
    const err = validateStep(state.step);
    if (err) {
      toast.error(err);
      return;
    }
    persist({ ...state, step: Math.min(7, state.step + 1) });
  };

  const goBack = () => persist({ ...state, step: Math.max(1, state.step - 1) });

  const finalizeBooking = (wizardState: WizardState) => {
    setSubmitting(true);
    try {
      const guestId = resolveGuestId(wizardState);
      const bookingPricing = computeWizardPricing(wizardState, sailing, addOns);
      const bookingAddOns: BookingAddOn[] = wizardState.selectedAddOnIds
        .map((id) => {
          const addon = addOns.find((a) => a.id === id);
          return addon ? { addOnId: id, name: addon.name, price: addon.price, quantity: 1 } : null;
        })
        .filter(Boolean) as BookingAddOn[];

      const booking = createBooking({
        sailingId: sailing.id,
        guestId,
        partySize: wizardState.partySize,
        cabinCategory: wizardState.cabinCategory,
        cabinId: wizardState.cabinAssignmentType === "specific" ? wizardState.cabinId : undefined,
        cabinAssignmentType: wizardState.cabinAssignmentType,
        travelers: wizardState.travelers,
        addOns: bookingAddOns,
        subtotal: bookingPricing.subtotal,
        discount: bookingPricing.discount,
        total: bookingPricing.total,
        depositPaid: bookingPricing.depositPaid,
        paymentPlanType: wizardState.paymentPlanType,
        paymentScheduleTemplateId: wizardState.paymentScheduleTemplateId,
        promoCodeId: bookingPricing.promoCodeId,
        referralCode: wizardState.referralCode.trim() || undefined,
        contactEmail: wizardState.guestEmail.trim(),
        emergencyContact: wizardState.emergencyContact,
        travelInfo: {
          flightNumber: wizardState.travelInfo.flightNumber || undefined,
          arrivalDate: wizardState.travelInfo.arrivalDate || undefined,
          specialRequests: wizardState.travelInfo.specialRequests || undefined,
        },
        waiverStatus: {
          ...wizardState.waiverStatus,
          termsAcceptedAt: new Date().toISOString(),
        },
        autoPayEnabled: wizardState.autoPayEnabled,
      });

      sessionStorage.removeItem(storageKey);
      router.push(`/book/${sailing.id}/confirmation/${booking.bookingCode}`);
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Booking failed.");
      setSubmitting(false);
    }
  };

  const handlePaymentComplete = (result: PaymentCloudResult) => {
    if (!result.success) {
      persist({ ...state, paymentComplete: false });
      toast.error("Payment declined (mock Payment Cloud).");
      const guestId = state.guestId ?? getGuestByEmail(state.guestEmail)?.id;
      if (guestId) {
        notifyPaymentFailure(guestId, "checkout", result.depositAmount, "Booking checkout");
      }
      return;
    }
    const nextState: WizardState = {
      ...state,
      paymentComplete: true,
      depositPaid: result.depositAmount,
      paymentPlanType: result.planType,
      paymentScheduleTemplateId: result.templateId,
      autoPayEnabled: result.autoPayEnabled,
    };
    persist(nextState);
    toast.success("Payment successful — confirming your booking…");
    finalizeBooking(nextState);
  };

  const returnUrl = `/book/${sailing.id}`;

  if (!hydrated) {
    return <div className="py-12 text-center text-muted-foreground text-sm">Loading booking wizard…</div>;
  }

  return (
    <div className="mx-auto max-w-3xl space-y-6 px-4 py-8">
      <div>
        <h1 className="font-semibold text-2xl">Book: {sailing.name}</h1>
        <p className="text-muted-foreground text-sm">{sailing.ship} · {sailing.departurePort}</p>
      </div>

      <div className="space-y-2">
        <div className="flex justify-between text-sm">
          <span>
            Step {state.step} of 7 — {STEPS[state.step - 1]}
          </span>
          <span className="text-muted-foreground">{Math.round((state.step / 7) * 100)}%</span>
        </div>
        <Progress value={(state.step / 7) * 100} />
      </div>

      <Card>
        <CardContent className="pt-6">
          {state.step === 1 && (
            <div className="space-y-5">
              <div className="space-y-2">
                <Label>Party size</Label>
                <Select value={String(state.partySize)} onValueChange={(v) => updatePartySize(Number(v))}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {[1, 2, 3, 4].map((n) => (
                      <SelectItem key={n} value={String(n)}>
                        {n} guest{n > 1 ? "s" : ""}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Cabin category</Label>
                <Select
                  value={state.cabinCategory}
                  onValueChange={(v) => persist({ ...state, cabinCategory: v, cabinId: undefined })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {CABIN_CATEGORIES.map((cat) => (
                      <SelectItem key={cat} value={cat}>
                        {cat}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="rounded-lg bg-muted/40 p-4 text-sm">
                <p className="font-medium">Estimated subtotal</p>
                <p className="text-2xl font-bold">{formatCurrency(sailing.basePrice * state.partySize)}</p>
                <p className="text-muted-foreground text-xs">
                  {formatCurrency(sailing.basePrice)} × {state.partySize} guests (add-ons & fees in later steps)
                </p>
              </div>
            </div>
          )}

          {state.step === 2 && (
            <div className="space-y-5">
              <div className="flex items-center justify-between rounded-lg border p-3">
                <div>
                  <p className="font-medium text-sm">Choose specific cabin</p>
                  <p className="text-muted-foreground text-xs">
                    Random assignment is free · Specific adds {formatCurrency(sailing.cabinSelectionUpgradeFee)}
                  </p>
                </div>
                <Switch
                  checked={state.cabinAssignmentType === "specific"}
                  onCheckedChange={(checked) =>
                    persist({
                      ...state,
                      cabinAssignmentType: checked ? "specific" : "random",
                      cabinId: checked ? state.cabinId : undefined,
                    })
                  }
                />
              </div>
              {state.cabinAssignmentType === "specific" ? (
                <>
                  <p className="text-muted-foreground text-sm">
                    Available {state.cabinCategory} cabins — green = selectable
                  </p>
                  <CabinGrid
                    cabins={filteredCabins}
                    selectedId={state.cabinId}
                    onSelect={(cabin) => persist({ ...state, cabinId: cabin.id })}
                  />
                </>
              ) : (
                <p className="rounded-lg border border-dashed p-6 text-center text-muted-foreground text-sm">
                  We&apos;ll assign the best available {state.cabinCategory} cabin at confirmation.
                </p>
              )}
            </div>
          )}

          {state.step === 3 && (
            <div className="space-y-3">
              {addOns.length === 0 ? (
                <p className="text-muted-foreground text-sm">No add-ons available for this sailing.</p>
              ) : (
                addOns.map((addon) => {
                  const checked = state.selectedAddOnIds.includes(addon.id);
                  return (
                    <label
                      key={addon.id}
                      className={cn(
                        "flex cursor-pointer items-start gap-3 rounded-lg border p-3 transition",
                        checked && "border-primary bg-primary/5",
                      )}
                    >
                      <Checkbox
                        checked={checked}
                        onCheckedChange={(v) => {
                          const ids = v
                            ? [...state.selectedAddOnIds, addon.id]
                            : state.selectedAddOnIds.filter((id) => id !== addon.id);
                          persist({ ...state, selectedAddOnIds: ids });
                        }}
                      />
                      <div className="flex-1">
                        <div className="flex items-center justify-between gap-2">
                          <p className="font-medium text-sm">{addon.name}</p>
                          <Badge variant="secondary">{formatCurrency(addon.price)}</Badge>
                        </div>
                        <p className="text-muted-foreground text-xs">{addon.description}</p>
                      </div>
                    </label>
                  );
                })
              )}
            </div>
          )}

          {state.step === 4 && (
            <div className="space-y-4">
              <CardDescription>
                Primary guest contact.{" "}
                <Link href={`/login?return=${encodeURIComponent(returnUrl)}`} className="text-primary underline">
                  Sign in
                </Link>{" "}
                or{" "}
                <Link href={`/register?return=${encodeURIComponent(returnUrl)}`} className="text-primary underline">
                  register
                </Link>{" "}
                — your progress is saved in this browser session.
              </CardDescription>
              <div className="grid gap-3 sm:grid-cols-2">
                <div className="space-y-1.5 sm:col-span-2">
                  <Label>Full name</Label>
                  <Input value={state.guestName} onChange={(e) => persist({ ...state, guestName: e.target.value })} />
                </div>
                <div className="space-y-1.5">
                  <Label>Email</Label>
                  <Input
                    type="email"
                    value={state.guestEmail}
                    onChange={(e) => persist({ ...state, guestEmail: e.target.value })}
                  />
                </div>
                <div className="space-y-1.5">
                  <Label>Phone</Label>
                  <Input value={state.guestPhone} onChange={(e) => persist({ ...state, guestPhone: e.target.value })} />
                </div>
              </div>
              <Separator />
              <p className="font-medium text-sm">Travelers ({state.partySize})</p>
              {state.travelers.map((t, i) => (
                <div key={t.id} className="space-y-2 rounded-lg border p-3">
                  <p className="font-medium text-sm">Traveler {i + 1}</p>
                  <div className="grid gap-2 sm:grid-cols-3">
                    <div className="space-y-1.5">
                      <Label className="text-xs">First name</Label>
                      <Input
                        placeholder="First name"
                        value={t.firstName}
                        onChange={(e) => {
                          const travelers = [...state.travelers];
                          travelers[i] = { ...t, firstName: e.target.value };
                          persist({ ...state, travelers });
                        }}
                      />
                    </div>
                    <div className="space-y-1.5">
                      <Label className="text-xs">Last name</Label>
                      <Input
                        placeholder="Last name"
                        value={t.lastName}
                        onChange={(e) => {
                          const travelers = [...state.travelers];
                          travelers[i] = { ...t, lastName: e.target.value };
                          persist({ ...state, travelers });
                        }}
                      />
                    </div>
                    <div className="space-y-1.5">
                      <Label className="text-xs">Date of birth</Label>
                      <Input
                        type="date"
                        value={t.dateOfBirth}
                        onChange={(e) => {
                          const travelers = [...state.travelers];
                          travelers[i] = { ...t, dateOfBirth: e.target.value };
                          persist({ ...state, travelers });
                        }}
                      />
                    </div>
                  </div>
                  <div className="grid gap-2 sm:grid-cols-3">
                    <div className="space-y-1.5">
                      <Label className="text-xs">Passport number</Label>
                      <Input
                        placeholder="Passport number"
                        value={t.passportNumber ?? ""}
                        onChange={(e) => {
                          const travelers = [...state.travelers];
                          travelers[i] = { ...t, passportNumber: e.target.value };
                          persist({ ...state, travelers });
                        }}
                      />
                    </div>
                    <div className="space-y-1.5">
                      <Label className="text-xs">Passport expiry</Label>
                      <Input
                        type="date"
                        value={t.passportExpiry ?? ""}
                        onChange={(e) => {
                          const travelers = [...state.travelers];
                          travelers[i] = { ...t, passportExpiry: e.target.value };
                          persist({ ...state, travelers });
                        }}
                      />
                    </div>
                    <div className="space-y-1.5">
                      <Label className="text-xs">Passport country</Label>
                      <Input
                        placeholder="Country"
                        value={t.passportCountry ?? ""}
                        onChange={(e) => {
                          const travelers = [...state.travelers];
                          travelers[i] = { ...t, passportCountry: e.target.value };
                          persist({ ...state, travelers });
                        }}
                      />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}

          {state.step === 5 && (
            <div className="space-y-5">
              <label className="flex items-start gap-3">
                <Checkbox
                  checked={state.waiverStatus.termsAccepted}
                  onCheckedChange={(v) =>
                    persist({
                      ...state,
                      waiverStatus: { ...state.waiverStatus, termsAccepted: !!v },
                    })
                  }
                />
                <span className="text-sm">
                  I accept the{" "}
                  <Link href="/terms" className="text-primary underline" target="_blank">
                    Terms & Conditions
                  </Link>
                </span>
              </label>
              <div className="space-y-2">
                <Label>Emergency contact</Label>
                <div className="grid gap-2 sm:grid-cols-3">
                  <Input
                    placeholder="Name"
                    value={state.emergencyContact.name}
                    onChange={(e) =>
                      persist({
                        ...state,
                        emergencyContact: { ...state.emergencyContact, name: e.target.value },
                      })
                    }
                  />
                  <Input
                    placeholder="Phone"
                    value={state.emergencyContact.phone}
                    onChange={(e) =>
                      persist({
                        ...state,
                        emergencyContact: { ...state.emergencyContact, phone: e.target.value },
                      })
                    }
                  />
                  <Input
                    placeholder="Relationship"
                    value={state.emergencyContact.relationship}
                    onChange={(e) =>
                      persist({
                        ...state,
                        emergencyContact: { ...state.emergencyContact, relationship: e.target.value },
                      })
                    }
                  />
                </div>
              </div>
              <div className="space-y-2">
                <Label>Travel info (optional)</Label>
                <div className="grid gap-2 sm:grid-cols-2">
                  <Input
                    placeholder="Flight number"
                    value={state.travelInfo.flightNumber}
                    onChange={(e) =>
                      persist({ ...state, travelInfo: { ...state.travelInfo, flightNumber: e.target.value } })
                    }
                  />
                  <Input
                    type="date"
                    value={state.travelInfo.arrivalDate}
                    onChange={(e) =>
                      persist({ ...state, travelInfo: { ...state.travelInfo, arrivalDate: e.target.value } })
                    }
                  />
                </div>
                <Textarea
                  placeholder="Special requests"
                  value={state.travelInfo.specialRequests}
                  onChange={(e) =>
                    persist({ ...state, travelInfo: { ...state.travelInfo, specialRequests: e.target.value } })
                  }
                />
              </div>
              <div className="space-y-2">
                <p className="font-medium text-sm">Waivers (optional)</p>
                {(
                  [
                    ["liabilityWaiver", "Liability waiver"],
                    ["photoRelease", "Photo release"],
                    ["medicalForm", "Medical information form"],
                  ] as const
                ).map(([key, label]) => (
                  <label key={key} className="flex items-center gap-2 text-sm text-muted-foreground">
                    <Checkbox
                      checked={!!state.waiverStatus[key]}
                      onCheckedChange={(v) =>
                        persist({
                          ...state,
                          waiverStatus: { ...state.waiverStatus, [key]: !!v },
                        })
                      }
                    />
                    {label}
                  </label>
                ))}
              </div>
            </div>
          )}

          {state.step === 6 && (
            <div className="space-y-4 text-sm">
              <CardHeader className="px-0 pt-0">
                <CardTitle className="text-lg">Review your booking</CardTitle>
                <CardDescription>Check everything before payment.</CardDescription>
              </CardHeader>
              <div className="grid gap-2 rounded-lg bg-muted/40 p-4">
                <div className="flex justify-between">
                  <span>Subtotal</span>
                  <span>{formatCurrency(pricing.subtotal)}</span>
                </div>
                {pricing.discount > 0 && (
                  <div className="flex justify-between text-green-600">
                    <span>Discount</span>
                    <span>-{formatCurrency(pricing.discount)}</span>
                  </div>
                )}
                <div className="flex justify-between font-bold text-base">
                  <span>Total</span>
                  <span>{formatCurrency(pricing.total)}</span>
                </div>
                <div className="flex justify-between text-muted-foreground">
                  <span>Due today</span>
                  <span>{formatCurrency(pricing.depositPaid)}</span>
                </div>
              </div>
              <ul className="space-y-1 text-muted-foreground">
                <li>
                  {state.partySize} guests · {state.cabinCategory} ·{" "}
                  {state.cabinAssignmentType === "random"
                    ? "Random cabin"
                    : `Cabin ${cabins.find((c) => c.id === state.cabinId)?.number ?? "—"}`}
                </li>
                <li>Primary guest: {state.guestName}</li>
                <li>Email: {state.guestEmail}</li>
                <li>
                  Add-ons:{" "}
                  {state.selectedAddOnIds.length
                    ? state.selectedAddOnIds.map((id) => addOns.find((a) => a.id === id)?.name).join(", ")
                    : "None"}
                </li>
                <li>Payment plan: {state.paymentPlanType.replace(/_/g, " ")}</li>
              </ul>
              <div className="space-y-2">
                <p className="font-medium text-sm">Travelers & passport</p>
                <ul className="space-y-2 text-muted-foreground text-sm">
                  {state.travelers.map((t) => (
                    <li key={t.id} className="rounded-md border bg-muted/20 px-3 py-2">
                      <p className="font-medium text-foreground">
                        {t.firstName} {t.lastName}
                      </p>
                      <p>
                        DOB:{" "}
                        {t.dateOfBirth
                          ? new Date(`${t.dateOfBirth}T12:00:00`).toLocaleDateString()
                          : "—"}
                      </p>
                      <p>
                        Passport: {t.passportNumber ?? "—"}
                        {t.passportCountry ? ` · ${t.passportCountry}` : ""}
                        {t.passportExpiry
                          ? ` · exp ${new Date(`${t.passportExpiry}T12:00:00`).toLocaleDateString()}`
                          : ""}
                      </p>
                    </li>
                  ))}
                </ul>
              </div>
            </div>
          )}

          {state.step === 7 && (
            <div className="space-y-4">
              <div className="grid gap-3 sm:grid-cols-2">
                <div className="space-y-1.5">
                  <Label>Promo code</Label>
                  <Input
                    placeholder="GROOVE100"
                    value={state.promoCode}
                    onChange={(e) => persist({ ...state, promoCode: e.target.value.toUpperCase() })}
                  />
                  {state.promoCode && (() => {
                    const result = validatePromoCode(state.promoCode.trim(), sailing.id);
                    return (
                      <p className="text-xs">
                        {"error" in result ? (
                          <span className="text-destructive">{result.error}</span>
                        ) : (
                          <span className="text-green-600">Valid — saves {formatCurrency(pricing.discount)}</span>
                        )}
                      </p>
                    );
                  })()}
                </div>
                <div className="space-y-1.5">
                  <Label>Referral code</Label>
                  <Input
                    placeholder="REF-EMMA"
                    value={state.referralCode}
                    onChange={(e) => persist({ ...state, referralCode: e.target.value.toUpperCase() })}
                  />
                </div>
              </div>
              <PaymentCloudCheckout
                sailing={sailing}
                total={pricing.total}
                depositAmount={sailing.depositAmount}
                planType={state.paymentPlanType}
                templateId={state.paymentScheduleTemplateId}
                autoPayEnabled={state.autoPayEnabled}
                onPlanChange={(plan, templateId) =>
                  persist({
                    ...state,
                    paymentPlanType: plan,
                    paymentScheduleTemplateId: templateId,
                    paymentComplete: false,
                  })
                }
                onAutoPayChange={(enabled) => persist({ ...state, autoPayEnabled: enabled })}
                onPaymentComplete={handlePaymentComplete}
              />
              {state.paymentComplete && (
                <div className="flex items-center gap-2 text-green-600 text-sm">
                  <Check className="size-4" /> Payment authorized — confirming booking…
                </div>
              )}
              {submitting && (
                <p className="text-muted-foreground text-sm">Creating your reservation…</p>
              )}
            </div>
          )}
        </CardContent>
      </Card>

      <div className="flex justify-between gap-3">
        <Button type="button" variant="outline" onClick={goBack} disabled={state.step === 1 || submitting}>
          <ChevronLeft className="mr-1 size-4" /> Back
        </Button>
        {state.step < 7 && (
          <Button type="button" onClick={goNext} disabled={submitting}>
            {state.step === 6 ? "Continue to payment" : "Continue"} <ChevronRight className="ml-1 size-4" />
          </Button>
        )}
      </div>
    </div>
  );
}
