
import React, { useState, useEffect, useRef, useCallback } from "react";
import { Link, router, useForm } from "@inertiajs/react";
// import { VEHICLES, VehicleOption, calculateVehiclePrice } from "@/lib/vehicles";
// import RatingModal from "../components/RatingModal";
import RouteMap from "@/components/RouteMap";
import { calculateVehiclePrice, VEHICLES } from "@/lib/vehicule";
import RatingModal from "@/components/RatingModal";
import LogoMark from "@/components/LogoMark";
import { getMapSuggestionsLocal } from "@/lib/utils";
import { toast } from "sonner";

// Dynamically import Leaflet map to avoid SSR window errors

// ─────────────────────────────────────────────────────────────
// TYPES
// ─────────────────────────────────────────────────────────────
interface GeoSuggestion {
    label: string;
    lat: number;
    lon: number;
}

interface RouteInfo {
    distanceKm: string;
    durationMin: number;
    geometry: GeoJSON.LineString;
}

// ─────────────────────────────────────────────────────────────
// ICONS
// ─────────────────────────────────────────────────────────────
const PersonIcon = () => (
    <svg className="w-3.5 h-3.5 text-navy/40" fill="currentColor" viewBox="0 0 20 20">
        <path fillRule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clipRule="evenodd" />
    </svg>
);

const LuggageIcon = () => (
    <svg className="w-3.5 h-3.5 text-navy/40" fill="currentColor" viewBox="0 0 24 24">
        <path d="M19 8h-2V5c0-.55-.45-1-1-1h-8c-.55 0-1 .45-1 1v3H5c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zM9 6h6v2H9V6zm10 14H5V10h14v10z" />
    </svg>
);

const BriefcaseIcon = () => (
    <svg className="w-3.5 h-3.5 text-navy/40" fill="currentColor" viewBox="0 0 24 24">
        <path d="M20 6h-4V4c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-6 0h-4V4h4v2z" />
    </svg>
);

const PinIcon = () => (
    <svg className="w-4 h-4 text-navy" fill="currentColor" viewBox="0 0 24 24">
        <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z" />
    </svg>
);

const ArrowLeftIcon = () => (
    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
    </svg>
);

const ArrowRightIcon = () => (
    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M14 5l7 7m0 0l-7 7m7-7H3" />
    </svg>
);

const SpinnerIcon = ({ small = false }: { small?: boolean }) => (
    <svg className={`animate-spin ${small ? "h-3.5 w-3.5" : "h-5 w-5"} text-current`} fill="none" viewBox="0 0 24 24">
        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
    </svg>
);

// ─────────────────────────────────────────────────────────────
// ADDRESS AUTOCOMPLETE
// ─────────────────────────────────────────────────────────────
interface AddressInputProps {
    label: string;
    placeholder: string;
    value: string;
    onSelect: (suggestion: GeoSuggestion) => void;
    onChange: (val: string) => void;
    error?: string;
    required?: boolean;
}

function AddressInput({ label, placeholder, value, onSelect, onChange, error, required }: AddressInputProps) {
    const [suggestions, setSuggestions] = useState<GeoSuggestion[]>([]);
    const [loading, setLoading] = useState(false);
    const [open, setOpen] = useState(false);
    const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
    const containerRef = useRef<HTMLDivElement>(null);



    const searchForm = useForm({
        q: '',
    })

    const fetchSuggestions = useCallback(async (q: string) => {
        if (q.length < 3) { setSuggestions([]); setOpen(false); return; }
        setLoading(true);
        try {
            // searchForm.get(`/geolocation/${q}`, {
            //     onSuccess: (resp: any) => {
            //         console.log(resp);
            //         setSuggestions(resp?.data);
            //
            //         setOpen(resp?.data.length > 0);
            //     }
            // })
            // const res = await fetch(`/api/geocode?q=${encodeURIComponent(q)}`);
            // const data: GeoSuggestion[] = await res.json();
            // const data: GeoSuggestion[] = getMapSuggestions(q);
            // console.log('data', data,);
            getMapSuggestionsLocal(q).then((thenData: any) => {
                setSuggestions(thenData);
                console.log('thenData', thenData);
                setOpen(thenData.length > 0);
            })
            // setSuggestions(data);
            // setOpen(data.length > 0);
        } finally {
            setLoading(false);
        }
    }, []);

    const handleInput = (e: React.ChangeEvent<HTMLInputElement>) => {
        const val = e.target.value;
        onChange(val);
        if (debounceRef.current) clearTimeout(debounceRef.current);
        debounceRef.current = setTimeout(() => fetchSuggestions(val), 300);
    };

    const handleSelect = (s: GeoSuggestion) => {
        onChange(s.label);
        onSelect(s);
        setOpen(false);
        setSuggestions([]);
    };

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

    return (
        <div className="flex flex-col gap-1.5 relative" ref={containerRef}>
            <label className="text-sm font-semibold text-navy/80">
                {label} {required && <span className="text-red-500">*</span>}
            </label>
            <div className="relative">
                <input
                    type="text"
                    placeholder={placeholder}
                    value={value}
                    onChange={handleInput}
                    onFocus={() => suggestions.length > 0 && setOpen(true)}
                    className={`form-input w-full pr-10 ${error ? "border-red-500 ring-1 ring-red-500" : ""}`}
                    autoComplete="off"
                />
                {loading && (
                    <div className="absolute right-3 top-1/2 -translate-y-1/2 text-navy/40">
                        <SpinnerIcon small />
                    </div>
                )}
            </div>

            {open && suggestions.length > 0 && (
                <ul className="absolute top-[100%] left-0 right-0 z-50 mt-1 rounded-xl overflow-hidden border border-navy/15 bg-white shadow-2xl">
                    {suggestions.map((s, i) => (
                        <li
                            key={i}
                            onMouseDown={() => handleSelect(s)}
                            className="px-4 py-3 text-sm text-navy cursor-pointer hover:bg-gold/10 border-b border-navy/10 last:border-b-0 transition-colors"
                        >
                            <span className="line-clamp-2">{s.label}</span>
                        </li>
                    ))}
                </ul>
            )}

            {error && <span className="text-xs text-red-500">{error}</span>}
        </div>
    );
}

// ─────────────────────────────────────────────────────────────
// MAIN RESERVATION PAGE
// ─────────────────────────────────────────────────────────────
export default function Reservation({reservation}:any) {
    const [currentStep, setCurrentStep] = useState<"trip" | "passengers" | "confirmation" | "success">("trip");
    const [loading, setLoading] = useState(false);
    const [bookingRef, setBookingRef] = useState("");
    const [errors, setErrors] = useState<Record<string, string>>({});


    // Map & Route
    const [departCoords, setDepartCoords] = useState<GeoSuggestion | null>(null);
    const [arriveeCoords, setArriveeCoords] = useState<GeoSuggestion | null>(null);
    const [routeInfo, setRouteInfo] = useState<RouteInfo | null>(null);
    const [fetchingRoute, setFetchingRoute] = useState(false);
    const [showMap, setShowMap] = useState(false);

    // Selected Vehicle (default ECO as in screenshot)
    const [selectedVehicleId, setSelectedVehicleId] = useState<string>("eco");

    // Payment Method choice in Step 3
    const [paymentMethod, setPaymentMethod] = useState<"sumup" | "on_the_spot">("sumup");

    // Rating Modal
    const [showRatingModal, setShowRatingModal] = useState(false);

    const createReservationFrom = useForm({
        dateDebut: "",
        heureDebut: "",
        isMiseADisposition: false,
        nbHeure: "2",
        departAddress: "",
        departTransportNum: "",
        departTransportTime: "",
        arriveeAddress: "",
        arriveeTransportNum: "",
        arriveeTransportTime: "",
        totalPax: "1",
        totalBagage: "1",
        noteChauffeur: "",
        paxCivilite: "M.",
        paxNom: "",
        paxPrenom: "",
        paxTelephoneMobile: "",
        paxTelephoneFixe: "",
        paxLangue: "FR",
        paxInfoParticuliere: "",
        societeFacturation: "",
        refClientDossier: "",
        infoComplementaire: "",
        contactCivilite: "M.",
        contactNom: "",
        contactPrenom: "",
        contactEmail: "",
        contactTelephone: "",
        contactLangue: "FR",
        statutDemande: "14",
    });
    
    // Form Fields
    const [form, setForm] = useState({
        dateDebut: "",
        heureDebut: "",
        isMiseADisposition: false,
        nbHeure: "2",
        departAddress: "",
        departTransportNum: "",
        departTransportTime: "",
        arriveeAddress: "",
        arriveeTransportNum: "",
        arriveeTransportTime: "",
        totalPax: "1",
        totalBagage: "1",
        noteChauffeur: "",
        paxCivilite: "M.",
        paxNom: "",
        paxPrenom: "",
        paxTelephoneMobile: "",
        paxTelephoneFixe: "",
        paxLangue: "FR",
        paxInfoParticuliere: "",
        societeFacturation: "",
        refClientDossier: "",
        infoComplementaire: "",
        contactCivilite: "M.",
        contactNom: "",
        contactPrenom: "",
        contactEmail: "",
        contactTelephone: "",
        contactLangue: "FR",
        statutDemande: "14",
    });

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
        const { name, value, type } = e.target;
        const val = type === "checkbox" ? (e.target as HTMLInputElement).checked : value;
        setForm((prev) => ({ ...prev, [name]: val }));
        if (errors[name]) {
            setErrors((prev) => {
                const n = { ...prev };
                delete n[name];
                return n;
            });
        }
    };

    const isNight = (() => {
        if (!form.heureDebut) return false;
        const h = parseInt(form.heureDebut.split(":")[0], 10);
        return !isNaN(h) && (h >= 22 || h < 6);
    })();

    const isTransportLocation = (addr: string) =>
        ["aeroport", "airport", "gare", "station", "zaventem", "charleroi"].some((k) =>
            addr.toLowerCase().includes(k)
        );

    const createGeolocationRouteForm = useForm({
        startLat:0,
        startLong:0,
        endLat:0,
        endLong:0,
    })
    // Fetch Route when coordinates available
    useEffect(() => {
        if (!departCoords || !arriveeCoords) {
            setRouteInfo(null);
            return;
        }
        console.log("Distance");

        /* const fetchRoute = async () => {
*     setFetchingRoute(true);
*     try { */
        createGeolocationRouteForm.setData({
            startLat:departCoords.lon,
            startLong:departCoords.lat,
            endLat:arriveeCoords.lon,
            endLong:arriveeCoords.lat,
        });

                createGeolocationRouteForm.post("/geolocation_route", {
                onSuccess: (data:any) => {
                    setRouteInfo({
                        distance: data?.props?.data?.routes[0]?.distance,
                        duration: data?.props?.data?.routes[0]?.duration,
                        geometry:  data?.props?.data?.routes[0]?.geometry,
                        distanceKm: (data?.props?.data?.routes[0]?.distance / 1000).toFixed(1),
                        durationMin: Math.ceil(data?.props?.data?.routes[0]?.duration / 60),
                    }as any); 
                }
            });

    }, [departCoords, arriveeCoords]);

    const distanceKmNum = routeInfo ? parseFloat(routeInfo.distanceKm) : null;
    const durationMinNum = routeInfo ? routeInfo.durationMin : null;

    const vehiclePrices: Record<string, number> = {};
    VEHICLES.forEach((v) => {
        vehiclePrices[v.id] = calculateVehiclePrice(v, distanceKmNum, durationMinNum, form.heureDebut);
    });

    const selectedVehicle = VEHICLES.find((v) => v.id === selectedVehicleId) || VEHICLES[5];
    const currentTotalPrice = vehiclePrices[selectedVehicleId] || selectedVehicle.baseFlatPrice;

    // Step Validations
    const validateStep1 = () => {
        const e: Record<string, string> = {};
        if (!form.dateDebut) e.dateDebut = "La date de prise en charge est obligatoire";
        if (!form.heureDebut) e.heureDebut = "L'heure de prise en charge est obligatoire";
        if (!form.departAddress) e.departAddress = "L'adresse de départ est obligatoire";
        if (!form.arriveeAddress) e.arriveeAddress = "L'adresse d'arrivée est obligatoire";
        setErrors(e);
        return Object.keys(e).length === 0;
    };

    const validateStep2 = () => {
        const e: Record<string, string> = {};
        if (!form.totalPax || Number(form.totalPax) < 1) e.totalPax = "Le nombre de passagers est obligatoire";
        if (!form.paxNom.trim()) e.paxNom = "Le nom du passager est obligatoire";
        if (!form.paxTelephoneMobile.trim()) {
            e.paxTelephoneMobile = "Le numéro mobile est obligatoire pour le suivi";
        }
        setErrors(e);
        return Object.keys(e).length === 0;
    };

    const handleCopyPassengerInfo = (e: React.MouseEvent) => {
        e.preventDefault();
        setForm((prev) => ({
            ...prev,
            contactCivilite: prev.paxCivilite,
            contactNom: prev.paxNom,
            contactPrenom: prev.paxPrenom,
            contactTelephone: prev.paxTelephoneMobile || prev.paxTelephoneFixe,
            contactLangue: prev.paxLangue,
        }));
    };

    // Final Submission & Payment Routing
    const handleFinalSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        const tempErrors: Record<string, string> = {};
        if (!form.contactNom.trim()) tempErrors.contactNom = "Le nom du contact est obligatoire";
        if (!form.contactEmail.trim() || !/\S+@\S+\.\S+/.test(form.contactEmail)) {
            tempErrors.contactEmail = "Veuillez renseigner un email valide";
        }
        if (Object.keys(tempErrors).length > 0) {
            setErrors(tempErrors);
            return;
        }

        setLoading(true);

        createReservationFrom.setData({
            ...form,
            vehicleId: selectedVehicle.id,
            vehicleName: selectedVehicle.name,
            totalPrice: currentTotalPrice,
            distanceKm: routeInfo?.distanceKm ?? null,
            durationMin: routeInfo?.durationMin ?? null,
            paymentMethod,
            paymentStatus: paymentMethod === "sumup" ? "pending" : "pay_on_arrival",
        } as any);

        createReservationFrom.post('/reservation', {
            preserveState: true,
            onSuccess: async () => {
                // 2. Handle Payment
                if (paymentMethod === "sumup") {
                    // Create a SumUp checkout, then redirect to the hosted payment page
                    try {
                        const bookingReference = `AEROCAB-${Date.now()}`;
                        const csrfToken = document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.content ?? '';

                        const response = await fetch('/sumup/pay', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'Accept': 'application/json',
                                'X-CSRF-TOKEN': csrfToken,
                            },
                            body: JSON.stringify({
                                checkout_reference: bookingReference,
                                amount: currentTotalPrice,
                                currency: 'EUR',
                                description: `AEROCAB - ${selectedVehicle.name} (${bookingReference})`,
                            }),
                        });

                        if (!response.ok) {
                            throw new Error(`SumUp checkout failed with status ${response.status}`);
                        }

                        const checkout = await response.json();

                        if (!checkout.checkoutUrl) {
                            throw new Error('SumUp checkout URL missing from response');
                        }

                        localStorage.setItem("RESERVATION", JSON.stringify({
                            bookingRef: bookingReference,
                            checkoutId: checkout.checkout_id,
                            amount: currentTotalPrice,
                            contactEmail: form.contactEmail,
                            description: `AEROCAB - ${selectedVehicle.name} (${bookingReference})`,
                        }));

                        window.location.href = checkout.checkoutUrl;
                    } catch (error) {
                        console.error('SumUp checkout error:', error);
                        toast.error("Impossible d'initialiser le paiement SumUp. Veuillez réessayer.");
                        setLoading(false);
                    }
                } else {
                    toast.success('Réservation créée avec succès');
                    // On the spot cash payment -> validate and open rating modal
                    setCurrentStep("success");
                    setLoading(false);
                    setTimeout(() => {
                        setShowRatingModal(true);
                    }, 1200);
                }
            },
            onError: (serverErrors) => {
                console.error('Reservation validation errors:', serverErrors);
                setErrors(serverErrors as Record<string, string>);
                toast.error("Veuillez vérifier les champs du formulaire.");
                setLoading(false);
            },
            onFinish: () => {
                // Safety net: never leave the submit button stuck in loading state
                // (unless we are navigating away to SumUp, in which case the page unloads)
                if (paymentMethod !== "sumup") {
                    setLoading(false);
                }
            },
        });
    };

    const resetForm = () => {
        setForm({
            dateDebut: "", heureDebut: "", isMiseADisposition: false, nbHeure: "2",
            departAddress: "", departTransportNum: "", departTransportTime: "",
            arriveeAddress: "", arriveeTransportNum: "", arriveeTransportTime: "",
            totalPax: "1", totalBagage: "1", noteChauffeur: "",
            paxCivilite: "M.", paxNom: "", paxPrenom: "", paxTelephoneMobile: "",
            paxTelephoneFixe: "", paxLangue: "FR", paxInfoParticuliere: "",
            societeFacturation: "", refClientDossier: "", infoComplementaire: "",
            contactCivilite: "M.", contactNom: "", contactPrenom: "", contactEmail: "",
            contactTelephone: "", contactLangue: "FR", statutDemande: "14",
        });
        setDepartCoords(null);
        setArriveeCoords(null);
        setRouteInfo(null);
        setSelectedVehicleId("eco");
        setPaymentMethod("sumup");
        setShowRatingModal(false);
        setCurrentStep("trip");
    };

    return (
        <div className="relative min-h-screen flex flex-col justify-between overflow-x-hidden bg-cream font-body text-navy">
            {/* Background Subtle Lines */}
            <div className="fixed inset-0 -z-20 flex items-center justify-around pointer-events-none">
                <span className="flex h-full w-[1px] animate-line1 bg-gold/20"></span>
                <span className="flex h-full w-[1px] animate-line2 bg-gold/20"></span>
                <span className="flex h-full w-[1px] animate-line3 bg-gold/20"></span>
            </div>

            {/* Header */}
            <header className="fixed top-0 left-0 z-50 w-full border-b border-gold/20 bg-cream/95 py-4 backdrop-blur-md">
                <div className="mx-auto flex max-w-7xl items-center justify-between px-6 md:px-12">
                    <Link href="/" className="group flex items-center gap-3">
                        <LogoMark color="#0f1f3d" size={34} />
                        <span className="font-display text-xl font-bold tracking-widest text-navy transition-colors group-hover:text-gold">AEROCAB</span>
                    </Link>
                    <Link href="/" className="text-sm font-semibold tracking-wide text-navy/70 transition-colors hover:text-gold">
                        ← Retour au site
                    </Link>
                </div>
            </header>

            {/* Main Container */}
            <main className="flex-1 flex flex-col items-center justify-start pt-28 pb-16 px-4 md:px-8">
                <div className="w-full max-w-4xl">

                    {/* Header Title */}
                    <div className="animate-fade-up mb-10 text-center">
                        <span className="gold-line mx-auto"></span>
                        <h2 className="font-display text-3xl tracking-tight text-navy md:text-5xl">
                            Réservation <em className="italic text-gold">en ligne</em>
                        </h2>
                        <p className="mx-auto mt-3 max-w-xl text-sm text-navy/60 md:text-base">
                            Navettes aéroport et transport haut de gamme avec tarif forfaitaire garanti.
                        </p>
                    </div>

                    {/* Steps Indicator */}
                    {currentStep !== "success" && (
                        <div className="grid grid-cols-3 gap-2.5 mb-6">
                            {(["trip", "passengers", "confirmation"] as const).map((step, i) => {
                                const labels = ["1. Trajet & Véhicule", "2. Passagers", "3. Confirmation & Paiement"];
                                const active = currentStep === step;
                                const past = ["trip", "passengers", "confirmation"].indexOf(currentStep) > i;
                                return (
                                    <div
                                        key={step}
                                        className={`py-3 rounded-xl font-bold text-xs md:text-sm text-center transition-all ${active
                                            ? "bg-navy text-white shadow-md ring-1 ring-gold/40"
                                            : past
                                                ? "border border-gold/40 bg-gold/10 text-gold"
                                                : "border border-navy/10 bg-white/70 text-navy/40"
                                            }`}
                                    >
                                        {past ? "✓ " : ""}{labels[i]}
                                    </div>
                                );
                            })}
                        </div>
                    )}

                    <form onSubmit={handleFinalSubmit}>

                        {/* ══════════════════════════════════════════════════════════════ */}
                        {/* STEP 1: TRIP & CAR MODEL SELECTION */}
                        {/* ══════════════════════════════════════════════════════════════ */}
                        {currentStep === "trip" && (
                            <div className="space-y-6">

                                {/* Date, Time & Itinerary inputs */}
                                <div className="bg-white rounded-2xl p-6 md:p-8 space-y-6 border border-navy/15 shadow-sm">
                                    {/* Date & Time */}
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        <div className="flex flex-col gap-1.5">
                                            <label className="text-sm font-semibold text-navy/80">
                                                Date de prise en charge <span className="text-red-500">*</span>
                                            </label>
                                            <input
                                                type="date"
                                                name="dateDebut"
                                                value={form.dateDebut}
                                                onChange={handleChange}
                                                min={new Date().toISOString().split("T")[0]}
                                                className={`form-input w-full ${errors.dateDebut ? "border-red-500 ring-1 ring-red-500" : ""}`}
                                            />
                                            {errors.dateDebut && <span className="text-xs text-red-500">{errors.dateDebut}</span>}
                                        </div>

                                        <div className="flex flex-col gap-1.5">
                                            <label className="text-sm font-semibold text-navy/80">
                                                Heure de prise en charge <span className="text-red-500">*</span>
                                            </label>
                                            <input
                                                type="time"
                                                name="heureDebut"
                                                value={form.heureDebut}
                                                onChange={handleChange}
                                                className={`form-input w-full ${errors.heureDebut ? "border-red-500 ring-1 ring-red-500" : ""}`}
                                            />
                                            {isNight && (
                                                <span className="text-xs text-amber-600 font-medium">🌙 Tarif de nuit (+20%) appliqué (22h - 6h)</span>
                                            )}
                                            {errors.heureDebut && <span className="text-xs text-red-500">{errors.heureDebut}</span>}
                                        </div>
                                    </div>

                                    {/* Hourly Disposition Toggle */}
                                    <div className="bg-cream/70 rounded-xl p-4 border border-navy/15 flex items-center justify-between gap-4">
                                        <div>
                                            <p className="text-sm font-bold text-navy">Pour une mise à disposition ?</p>
                                            <p className="text-xs text-navy/60 mt-0.5">Chauffeur privé à disposition par tranche horaire</p>
                                        </div>
                                        <label className="relative inline-flex items-center cursor-pointer flex-shrink-0">
                                            <input
                                                type="checkbox"
                                                name="isMiseADisposition"
                                                checked={form.isMiseADisposition}
                                                onChange={handleChange}
                                                className="sr-only peer"
                                            />
                                            <div className="w-11 h-6 bg-gold/20 rounded-full peer peer-checked:bg-gold after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:after:translate-x-full"></div>
                                        </label>
                                    </div>

                                    {form.isMiseADisposition && (
                                        <div className="flex flex-col gap-1.5">
                                            <label className="text-sm font-semibold text-navy/80">Nombre d'heures</label>
                                            <select
                                                name="nbHeure"
                                                value={form.nbHeure}
                                                onChange={handleChange}
                                                className="form-input bg-white border-navy/20 text-navy"
                                            >
                                                {[...Array(24)].map((_, i) => (
                                                    <option key={i + 1} value={i + 1}>
                                                        {i + 1} heure{i > 0 ? "s" : ""}
                                                    </option>
                                                ))}
                                            </select>
                                        </div>
                                    )}

                                    {/* Addresses */}
                                    <div className="space-y-4">
                                        <h4 className="text-base font-bold text-navy border-b border-navy/10 pb-2">
                                            Itinéraire
                                        </h4>

                                        <AddressInput
                                            label="Adresse de départ"
                                            placeholder="Ex: Aéroport de Bruxelles (BRU), Gare du Midi, Avenue Louise..."
                                            value={form.departAddress}
                                            onChange={(val) => setForm((prev) => ({ ...prev, departAddress: val }))}
                                            onSelect={(s) => {
                                                setDepartCoords(s);
                                                setForm((prev) => ({ ...prev, departAddress: s.label }));
                                            }}
                                            error={errors.departAddress}
                                            required
                                        />

                                        {isTransportLocation(form.departAddress) && (
                                            <div className="grid grid-cols-2 gap-4 bg-cream/70 p-4 rounded-xl border border-navy/15">
                                                <div className="flex flex-col gap-1">
                                                    <label className="text-xs font-semibold text-navy/80">Numéro de vol / train</label>
                                                    <input
                                                        type="text"
                                                        name="departTransportNum"
                                                        placeholder="SN3711"
                                                        value={form.departTransportNum}
                                                        onChange={handleChange}
                                                        className="form-input text-sm py-2 bg-white"
                                                    />
                                                </div>
                                                <div className="flex flex-col gap-1">
                                                    <label className="text-xs font-semibold text-navy/80">Heure d'arrivée prévue</label>
                                                    <input
                                                        type="text"
                                                        name="departTransportTime"
                                                        placeholder="14:30"
                                                        value={form.departTransportTime}
                                                        onChange={handleChange}
                                                        className="form-input text-sm py-2 bg-white"
                                                    />
                                                </div>
                                            </div>
                                        )}

                                        <AddressInput
                                            label="Adresse d'arrivée"
                                            placeholder="Ex: Grand-Place, Rue de la Loi 200, Charleroi Airport..."
                                            value={form.arriveeAddress}
                                            onChange={(val) => setForm((prev) => ({ ...prev, arriveeAddress: val }))}
                                            onSelect={(s) => {
                                                setArriveeCoords(s);
                                                setForm((prev) => ({ ...prev, arriveeAddress: s.label }));
                                            }}
                                            error={errors.arriveeAddress}
                                            required
                                        />

                                        {isTransportLocation(form.arriveeAddress) && (
                                            <div className="grid grid-cols-2 gap-4 bg-cream/70 p-4 rounded-xl border border-navy/15">
                                                <div className="flex flex-col gap-1">
                                                    <label className="text-xs font-semibold text-navy/80">Numéro de vol / train</label>
                                                    <input
                                                        type="text"
                                                        name="arriveeTransportNum"
                                                        placeholder="LH102"
                                                        value={form.arriveeTransportNum}
                                                        onChange={handleChange}
                                                        className="form-input text-sm py-2 bg-white"
                                                    />
                                                </div>
                                                <div className="flex flex-col gap-1">
                                                    <label className="text-xs font-semibold text-navy/80">Heure prévue</label>
                                                    <input
                                                        type="text"
                                                        name="arriveeTransportTime"
                                                        placeholder="18:45"
                                                        value={form.arriveeTransportTime}
                                                        onChange={handleChange}
                                                        className="form-input text-sm py-2 bg-white"
                                                    />
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                </div>

                                {/* Route Calculation Banner */}
                                {fetchingRoute && (
                                    <div className="bg-gold/10 border border-gold/30 rounded-xl p-3 flex items-center justify-center gap-2 text-sm text-navy">
                                        <SpinnerIcon small />
                                        <span>Calcul de l'itinéraire et mise à jour des tarifs en cours...</span>
                                    </div>
                                )}

                                {/* ══════════════════════════════════════════════════════════════ */}
                                {/* VEHICLE SELECTION CARDS (Identical to user's screenshot) */}
                                {/* ══════════════════════════════════════════════════════════════ */}
                                <div className="space-y-4">
                                    <div className="flex items-center justify-between">
                                        <h3 className="text-base sm:text-lg font-bold text-navy flex items-center gap-2">
                                            <span>Choisissez votre catégorie de véhicule</span>
                                            {routeInfo && (
                                                <span className="text-xs font-semibold text-navy/60 bg-navy/5 px-2.5 py-1 rounded-full border border-navy/15">
                                                    {routeInfo.distanceKm} km • {routeInfo.durationMin} min
                                                </span>
                                            )}
                                        </h3>
                                    </div>

                                    {/* 2-Column Grid of 6 Vehicle Cards matching screenshot */}
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3.5">
                                        {VEHICLES.map((vehicle) => {
                                            const isSelected = selectedVehicleId === vehicle.id;
                                            const price = vehiclePrices[vehicle.id] || vehicle.baseFlatPrice;

                                            return (
                                                <div
                                                    key={vehicle.id}
                                                    onClick={() => setSelectedVehicleId(vehicle.id)}
                                                    className={`relative rounded-lg p-3.5 transition-all cursor-pointer flex items-center justify-between gap-3 bg-white text-[#1e2532] shadow-sm hover:shadow-md ${isSelected
                                                        ? "ring-2 ring-gold border-2 border-gold"
                                                        : "border border-navy/15 hover:border-gold/50"
                                                        }`}
                                                >
                                                    {/* Left: Car img */}
                                                    <div className="relative w-28 h-16 sm:w-32 sm:h-18 flex-shrink-0 bg-white rounded overflow-hidden">
                                                        <img
                                                            src={vehicle.image}
                                                            alt={vehicle.name}
                                                            className="object-contain"
                                                            sizes="130px"
                                                        />
                                                    </div>

                                                    {/* Middle: Name & Capacity Icons */}
                                                    <div className="flex-1 min-w-0 pr-1">
                                                        <h4 className="font-bold text-base text-navy leading-tight">
                                                            {vehicle.name}
                                                        </h4>

                                                        {/* Capacity Indicators */}
                                                        <div className="flex items-center gap-3 mt-2 text-xs text-navy/60">
                                                            <span className="flex items-center gap-1 font-medium">
                                                                <PersonIcon /> x{vehicle.passengers}
                                                            </span>
                                                            <span className="flex items-center gap-1 font-medium">
                                                                <LuggageIcon /> x{vehicle.luggage}
                                                            </span>
                                                            <span className="flex items-center gap-1 font-medium">
                                                                <BriefcaseIcon /> x{vehicle.handLuggage}
                                                            </span>
                                                        </div>
                                                    </div>

                                                    {/* Right: Price & Selection Checkbox Button */}
                                                    <div className="flex flex-col items-end justify-between h-full pl-2 self-stretch">
                                                        <div className="text-right">
                                                            <span className="text-xl font-bold text-navy block leading-tight">
                                                                €{price}
                                                            </span>
                                                            <span className="text-[10px] text-navy/40 font-medium block">
                                                                TVA incl.
                                                            </span>
                                                        </div>

                                                        {/* Square Blue Checkbox Button matching screenshot */}
                                                        <div
                                                            className={`w-6 h-6 rounded flex items-center justify-center transition-colors mt-2 ${isSelected
                                                                ? "bg-gold text-navy"
                                                                : "bg-navy/10 text-transparent hover:bg-gold/50"
                                                                }`}
                                                        >
                                                            {isSelected && (
                                                                <svg className="w-4 h-4 text-navy" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="3" d="M5 13l4 4L19 7" />
                                                                </svg>
                                                            )}
                                                        </div>
                                                    </div>
                                                </div>
                                            );
                                        })}
                                    </div>

                                    {/* "📍 Voir la carte" Toggle Link */}
                                    <div className="pt-2">
                                        <button
                                            type="button"
                                            onClick={() => setShowMap(!showMap)}
                                            className="text-xs sm:text-sm text-navy/80 hover:text-gold flex items-center gap-1.5 transition-colors cursor-pointer py-1"
                                        >
                                            <PinIcon />
                                            <span className="font-semibold underline underline-offset-4">
                                                {showMap ? "Masquer la carte" : "Voir la carte"}
                                            </span>
                                        </button>
                                    </div>

                                    {/* Collapsible Leaflet Map */}
                                    {showMap && (
                                        <div className="rounded-2xl overflow-hidden border border-navy/15 shadow-lg mt-3">
                                            <RouteMap
                                                pickup={departCoords ? { ...departCoords, label: form.departAddress } : null}
                                                dropoff={arriveeCoords ? { ...arriveeCoords, label: form.arriveeAddress } : null}
                                                routeGeometry={routeInfo?.geometry ?? null}
                                            />
                                        </div>
                                    )}

                                    {/* Total & Action Button matching screenshot */}
                                    <div className="text-center pt-6 space-y-4">
                                        <div>
                                            <p className="text-2xl font-light text-navy">
                                                Total: <span className="font-extrabold text-navy">€{currentTotalPrice}</span>{" "}
                                                <span className="text-xs text-navy/40">TVA incl.</span>
                                            </p>
                                            <p className="text-xs text-navy font-semibold mt-0.5">
                                                Véhicule sélectionné : {selectedVehicle.name} ({selectedVehicle.passengers} passagers max)
                                            </p>
                                        </div>

                                        <button
                                            type="button"
                                            onClick={() => {
                                                if (validateStep1()) setCurrentStep("passengers");
                                            }}
                                            className="px-10 py-3.5 bg-gold hover:bg-gold-light text-navy font-bold rounded-lg transition-all shadow-lg hover:shadow-gold/30 text-base cursor-pointer inline-flex items-center gap-2"
                                        >
                                            <span>Réserver maintenant</span>
                                            <ArrowRightIcon />
                                        </button>
                                    </div>

                                </div>

                            </div>
                        )}

                        {/* ══════════════════════════════════════════════════════════════ */}
                        {/* STEP 2: PASSENGERS */}
                        {/* ══════════════════════════════════════════════════════════════ */}
                        {currentStep === "passengers" && (
                            <div className="bg-white rounded-2xl p-6 md:p-8 space-y-6 border border-navy/15 shadow-sm">

                                {/* Vehicle Selected Reminder */}
                                <div className="bg-cream/70 rounded-xl p-4 border border-navy/15 flex items-center justify-between">
                                    <div className="flex items-center gap-3">
                                        <div className="relative w-16 h-10 bg-white rounded overflow-hidden flex-shrink-0 border border-navy/15">
                                            <img src={selectedVehicle.image} alt={selectedVehicle.name} className="object-contain" />
                                        </div>
                                        <div>
                                            <span className="text-xs text-navy/40 block">Catégorie choisie</span>
                                            <span className="text-sm font-bold text-navy">{selectedVehicle.name}</span>
                                        </div>
                                    </div>
                                    <div className="text-right">
                                        <span className="text-lg font-black text-navy">€{currentTotalPrice}</span>
                                        <span className="text-[10px] text-navy/40 block">TVA incl.</span>
                                    </div>
                                </div>

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <div className="flex flex-col gap-1.5">
                                        <label className="text-sm font-semibold text-navy/80">
                                            Nombre de passagers <span className="text-red-500">*</span> (max: {selectedVehicle.passengers})
                                        </label>
                                        <input
                                            type="number"
                                            name="totalPax"
                                            min="1"
                                            max={selectedVehicle.passengers}
                                            value={form.totalPax}
                                            onChange={handleChange}
                                            className={`form-input w-full ${errors.totalPax ? "border-red-500 ring-1 ring-red-500" : ""}`}
                                        />
                                        {errors.totalPax && <span className="text-xs text-red-500">{errors.totalPax}</span>}
                                    </div>

                                    <div className="flex flex-col gap-1.5">
                                        <label className="text-sm font-semibold text-navy/80">
                                            Nombre de bagages (max: {selectedVehicle.luggage})
                                        </label>
                                        <input
                                            type="number"
                                            name="totalBagage"
                                            min="0"
                                            value={form.totalBagage}
                                            onChange={handleChange}
                                            className="form-input w-full"
                                        />
                                    </div>
                                </div>

                                <div className="flex flex-col gap-1.5">
                                    <label className="text-sm font-semibold text-navy/80 flex justify-between">
                                        <span>Note au chauffeur</span>
                                        <span className={`text-xs ${form.noteChauffeur.length > 500 ? "text-red-500" : "text-navy/40"}`}>
                                            {form.noteChauffeur.length}/500
                                        </span>
                                    </label>
                                    <textarea
                                        name="noteChauffeur"
                                        maxLength={500}
                                        rows={3}
                                        onChange={handleChange}
                                        value={form.noteChauffeur}
                                        placeholder="Ex: Siège enfant 3 ans, bagages volumineux, accueil avec pancarte..."
                                        className="form-input w-full resize-none"
                                    />
                                </div>

                                <div className="space-y-4 pt-4 border-t border-navy/10">
                                    <h4 className="text-base font-bold text-navy">Passager référent</h4>

                                    <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                                        <div className="flex flex-col gap-1.5">
                                            <label className="text-sm font-semibold text-navy/80">Civilité <span className="text-red-500">*</span></label>
                                            <select
                                                name="paxCivilite"
                                                value={form.paxCivilite}
                                                onChange={handleChange}
                                                className="form-input bg-white border-navy/20 text-navy"
                                            >
                                                <option>M.</option>
                                                <option>Mme.</option>
                                                <option>Mlle.</option>
                                            </select>
                                        </div>

                                        <div className="flex flex-col gap-1.5">
                                            <label className="text-sm font-semibold text-navy/80">Nom <span className="text-red-500">*</span></label>
                                            <input
                                                type="text"
                                                name="paxNom"
                                                value={form.paxNom}
                                                onChange={handleChange}
                                                className={`form-input w-full ${errors.paxNom ? "border-red-500 ring-1 ring-red-500" : ""}`}
                                            />
                                            {errors.paxNom && <span className="text-xs text-red-500">{errors.paxNom}</span>}
                                        </div>

                                        <div className="flex flex-col gap-1.5">
                                            <label className="text-sm font-semibold text-navy/80">Prénom</label>
                                            <input
                                                type="text"
                                                name="paxPrenom"
                                                value={form.paxPrenom}
                                                onChange={handleChange}
                                                className="form-input w-full"
                                            />
                                        </div>
                                    </div>

                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        <div className="flex flex-col gap-1.5">
                                            <label className="text-sm font-semibold text-navy/80">
                                                Téléphone Mobile (pour urgences) <span className="text-red-500">*</span>
                                            </label>
                                            <input
                                                type="tel"
                                                name="paxTelephoneMobile"
                                                placeholder="+32 470 00 00 00"
                                                value={form.paxTelephoneMobile}
                                                onChange={handleChange}
                                                className={`form-input w-full ${errors.paxTelephoneMobile ? "border-red-500 ring-1 ring-red-500" : ""}`}
                                            />
                                            {errors.paxTelephoneMobile && (
                                                <span className="text-xs text-red-500">{errors.paxTelephoneMobile}</span>
                                            )}
                                        </div>

                                        <div className="flex flex-col gap-1.5">
                                            <label className="text-sm font-semibold text-navy/80">Téléphone Fixe</label>
                                            <input
                                                type="tel"
                                                name="paxTelephoneFixe"
                                                value={form.paxTelephoneFixe}
                                                onChange={handleChange}
                                                className="form-input w-full"
                                            />
                                        </div>
                                    </div>

                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        <div className="flex flex-col gap-1.5">
                                            <label className="text-sm font-semibold text-navy/80">Langue</label>
                                            <select
                                                name="paxLangue"
                                                value={form.paxLangue}
                                                onChange={handleChange}
                                                className="form-input bg-white border-navy/20 text-navy"
                                            >
                                                <option value="FR">Français (FR)</option>
                                                <option value="EN">English (EN)</option>
                                                <option value="NL">Nederlands (NL)</option>
                                            </select>
                                        </div>

                                        <div className="flex flex-col gap-1.5">
                                            <label className="text-sm font-semibold text-navy/80">Information particulière</label>
                                            <input
                                                type="text"
                                                name="paxInfoParticuliere"
                                                placeholder="Ex: Mobilité réduite..."
                                                value={form.paxInfoParticuliere}
                                                onChange={handleChange}
                                                className="form-input w-full"
                                            />
                                        </div>
                                    </div>
                                </div>

                                <div className="flex justify-between pt-4 border-t border-navy/10">
                                    <button
                                        type="button"
                                        onClick={() => setCurrentStep("trip")}
                                        className="px-5 py-3 font-semibold text-navy/60 hover:text-navy bg-navy/5 hover:bg-navy/10 rounded-xl transition flex items-center gap-2 cursor-pointer"
                                    >
                                        <ArrowLeftIcon /> Étape précédente
                                    </button>

                                    <button
                                        type="button"
                                        onClick={() => {
                                            if (validateStep2()) setCurrentStep("confirmation");
                                        }}
                                        className="px-6 py-3 font-bold text-navy bg-gold hover:bg-gold-light rounded-xl transition flex items-center gap-2 shadow-md cursor-pointer"
                                    >
                                        Étape suivante <ArrowRightIcon />
                                    </button>
                                </div>
                            </div>
                        )}

                        {/* ══════════════════════════════════════════════════════════════ */}
                        {/* STEP 3: CONFIRMATION & PAYMENT METHOD */}
                        {/* ══════════════════════════════════════════════════════════════ */}
                        {currentStep === "confirmation" && (
                            <div className="space-y-6">

                                {/* Trip & Vehicle Recap Banner */}
                                <div className="bg-white rounded-2xl p-6 border border-navy/15 shadow-sm space-y-4">
                                    <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3 border-b border-navy/10 pb-4">
                                        <div className="flex items-center gap-3">
                                            <div className="relative w-20 h-12 bg-white rounded overflow-hidden flex-shrink-0 border border-navy/15">
                                                <img src={selectedVehicle.image} alt={selectedVehicle.name} className="object-contain" />
                                            </div>
                                            <div>
                                                <span className="text-xs text-navy/40 uppercase font-semibold">Catégorie réservée</span>
                                                <h4 className="font-bold text-navy text-base">{selectedVehicle.name}</h4>
                                            </div>
                                        </div>

                                        <div className="text-right">
                                            <span className="text-2xl font-black text-navy">€{currentTotalPrice}</span>
                                            <span className="text-xs text-navy/40 block">TVA incluse</span>
                                        </div>
                                    </div>

                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs text-navy/60">
                                        <div>
                                            <span className="text-navy/40 block">Prise en charge :</span>
                                            <span className="font-bold text-navy">{form.dateDebut} à {form.heureDebut}</span>
                                        </div>
                                        <div>
                                            <span className="text-navy/40 block">Itinéraire estimé :</span>
                                            <span className="font-semibold text-navy">{routeInfo ? `${routeInfo.distanceKm} km • ~${routeInfo.durationMin} min` : "Bruxelles & Environs"}</span>
                                        </div>
                                        <div className="sm:col-span-2">
                                            <span className="text-navy/40 block">Départ → Arrivée :</span>
                                            <span className="text-navy font-medium">{form.departAddress}</span>
                                            <span className="text-navy/40 block">→ {form.arriveeAddress}</span>
                                        </div>
                                    </div>
                                </div>

                                {/* Contact Person Details */}
                                <div className="bg-white rounded-2xl p-6 md:p-8 space-y-6 border border-navy/15 shadow-sm">

                                    {/* Company & Billing */}
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        <div className="flex flex-col gap-1.5">
                                            <label className="text-sm font-semibold text-navy/80">Société ou nom de facturation</label>
                                            <input
                                                type="text"
                                                name="societeFacturation"
                                                placeholder="Ex: Aerocab SPRL (optionnel)"
                                                value={form.societeFacturation}
                                                onChange={handleChange}
                                                className="form-input w-full"
                                            />
                                        </div>
                                        <div className="flex flex-col gap-1.5">
                                            <label className="text-sm font-semibold text-navy/80">Référence interne du dossier</label>
                                            <input
                                                type="text"
                                                name="refClientDossier"
                                                placeholder="Ex: DOSSIER-2026 (optionnel)"
                                                value={form.refClientDossier}
                                                onChange={handleChange}
                                                className="form-input w-full"
                                            />
                                        </div>
                                    </div>

                                    {/* Contact Person */}
                                    <div className="space-y-4 pt-4 border-t border-navy/10">
                                        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3">
                                            <h4 className="text-base font-bold text-navy">Personne à contacter (Facturation / Suivi)</h4>
                                            <button
                                                type="button"
                                                onClick={handleCopyPassengerInfo}
                                                className="px-3 py-1.5 text-xs font-bold text-navy hover:text-gold bg-gold/10 border border-gold/30 rounded-lg transition cursor-pointer"
                                            >
                                                Reprendre les infos du passager
                                            </button>
                                        </div>

                                        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                                            <div className="flex flex-col gap-1.5">
                                                <label className="text-sm font-semibold text-navy/80">Civilité <span className="text-red-500">*</span></label>
                                                <select
                                                    name="contactCivilite"
                                                    value={form.contactCivilite}
                                                    onChange={handleChange}
                                                    className="form-input bg-white border-navy/20 text-navy"
                                                >
                                                    <option>M.</option>
                                                    <option>Mme.</option>
                                                    <option>Mlle.</option>
                                                </select>
                                            </div>
                                            <div className="flex flex-col gap-1.5">
                                                <label className="text-sm font-semibold text-navy/80">Nom <span className="text-red-500">*</span></label>
                                                <input
                                                    type="text"
                                                    name="contactNom"
                                                    value={form.contactNom}
                                                    onChange={handleChange}
                                                    className={`form-input w-full ${errors.contactNom ? "border-red-500 ring-1 ring-red-500" : ""}`}
                                                />
                                                {errors.contactNom && <span className="text-xs text-red-500">{errors.contactNom}</span>}
                                            </div>
                                            <div className="flex flex-col gap-1.5">
                                                <label className="text-sm font-semibold text-navy/80">Prénom</label>
                                                <input
                                                    type="text"
                                                    name="contactPrenom"
                                                    value={form.contactPrenom}
                                                    onChange={handleChange}
                                                    className="form-input w-full"
                                                />
                                            </div>
                                        </div>

                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                            <div className="flex flex-col gap-1.5">
                                                <label className="text-sm font-semibold text-navy/80">Email de confirmation <span className="text-red-500">*</span></label>
                                                <input
                                                    type="email"
                                                    name="contactEmail"
                                                    placeholder="contact@email.com"
                                                    value={form.contactEmail}
                                                    onChange={handleChange}
                                                    className={`form-input w-full ${errors.contactEmail ? "border-red-500 ring-1 ring-red-500" : ""}`}
                                                />
                                                {errors.contactEmail && <span className="text-xs text-red-500">{errors.contactEmail}</span>}
                                            </div>
                                            <div className="flex flex-col gap-1.5">
                                                <label className="text-sm font-semibold text-navy/80">Téléphone</label>
                                                <input
                                                    type="tel"
                                                    name="contactTelephone"
                                                    value={form.contactTelephone}
                                                    onChange={handleChange}
                                                    className="form-input w-full"
                                                />
                                            </div>
                                        </div>
                                    </div>

                                    {/* ══════════════════════════════════════════════════════════ */}
                                    {/* PAYMENT METHOD CHOICES */}
                                    {/* ══════════════════════════════════════════════════════════ */}
                                    <div className="space-y-4 pt-6 border-t border-navy/10">
                                        <div className="flex items-center justify-between">
                                            <h4 className="text-base font-bold text-navy">
                                                Mode de règlement (Validation du trajet)
                                            </h4>
                                            <span className="text-xs text-navy font-semibold">Sélectionnez une option</span>
                                        </div>

                                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">

                                            {/* 1. SumUp Online Payment */}
                                            <div
                                                onClick={() => setPaymentMethod("sumup")}
                                                className={`p-4 rounded-xl border transition-all cursor-pointer flex flex-col justify-between gap-3 ${paymentMethod === "sumup"
                                                    ? "bg-gold/10 border-gold ring-2 ring-gold/40 shadow-sm"
                                                    : "bg-white border-navy/15 hover:border-gold/50"
                                                    }`}
                                            >
                                                <div className="flex items-start justify-between">
                                                    <div className="flex items-center gap-2">
                                                        <span className="w-4 h-4 rounded-full border border-navy/30 flex items-center justify-center">
                                                            {paymentMethod === "sumup" && (
                                                                <span className="w-2.5 h-2.5 rounded-full bg-gold"></span>
                                                            )}
                                                        </span>
                                                        <span className="font-bold text-sm text-navy">
                                                            Paiement en ligne sécurisé
                                                        </span>
                                                    </div>
                                                    <span className="text-[10px] uppercase font-bold text-navy bg-gold/15 px-2 py-0.5 rounded border border-gold/30">
                                                        SumUp
                                                    </span>
                                                </div>

                                                <p className="text-xs text-navy/60 leading-relaxed">
                                                    Carte bancaire (Visa, Mastercard), Apple Pay, Google Pay via le portail officiel SumUp.
                                                </p>

                                                <div className="flex items-center gap-2 text-[11px] text-navy/40 font-medium">
                                                    <span>🔒 256-bit SSL</span>
                                                    <span>•</span>
                                                    <span>Validation immédiate</span>
                                                </div>
                                            </div>

                                            {/* 2. On the Spot Cash Payment */}
                                            <div
                                                onClick={() => setPaymentMethod("on_the_spot")}
                                                className={`p-4 rounded-xl border transition-all cursor-pointer flex flex-col justify-between gap-3 ${paymentMethod === "on_the_spot"
                                                    ? "bg-gold/10 border-gold ring-2 ring-gold/40 shadow-sm"
                                                    : "bg-white border-navy/15 hover:border-gold/50"
                                                    }`}
                                            >
                                                <div className="flex items-start justify-between">
                                                    <div className="flex items-center gap-2">
                                                        <span className="w-4 h-4 rounded-full border border-navy/30 flex items-center justify-center">
                                                            {paymentMethod === "on_the_spot" && (
                                                                <span className="w-2.5 h-2.5 rounded-full bg-gold"></span>
                                                            )}
                                                        </span>
                                                        <span className="font-bold text-sm text-navy">
                                                            Paiement à bord (Au chauffeur)
                                                        </span>
                                                    </div>
                                                    <span className="text-[10px] uppercase font-bold text-navy bg-gold/15 px-2 py-0.5 rounded border border-gold/30">
                                                        Sur place
                                                    </span>
                                                </div>

                                                <p className="text-xs text-navy/60 leading-relaxed">
                                                    Réglez directement en espèces ou par carte bancaire auprès du chauffeur le jour de la course.
                                                </p>

                                                <div className="flex items-center gap-2 text-[11px] text-navy/40 font-medium">
                                                    <span>💶 Espèces acceptées</span>
                                                    <span>•</span>
                                                    <span>💳 Terminal à bord</span>
                                                </div>
                                            </div>

                                        </div>
                                    </div>

                                    {errors.submit && (
                                        <div className="p-3.5 bg-red-50 border border-red-200 rounded-xl text-red-600 text-sm text-center font-medium">
                                            {errors.submit}
                                        </div>
                                    )}

                                    {/* Submission Action */}
                                    <div className="flex flex-col sm:flex-row justify-between items-center gap-4 pt-4 border-t border-navy/10">
                                        <button
                                            type="button"
                                            onClick={() => setCurrentStep("passengers")}
                                            className="px-5 py-3 font-semibold text-navy/60 hover:text-navy bg-navy/5 hover:bg-navy/10 rounded-xl transition flex items-center gap-2 cursor-pointer w-full sm:w-auto justify-center"
                                        >
                                            <ArrowLeftIcon /> Étape précédente
                                        </button>

                                        <button
                                            type="submit"
                                            disabled={loading}
                                            className="w-full sm:w-auto px-8 py-3.5 font-bold text-navy bg-gold hover:bg-gold-light rounded-xl transition flex items-center justify-center gap-2 shadow-lg cursor-pointer disabled:opacity-50 text-base"
                                        >
                                            {loading ? (
                                                <>
                                                    <SpinnerIcon />
                                                    <span>Traitement en cours...</span>
                                                </>
                                            ) : paymentMethod === "sumup" ? (
                                                <>
                                                    <span>Procéder au paiement SumUp (€{currentTotalPrice})</span>
                                                    <ArrowRightIcon />
                                                </>
                                            ) : (
                                                <>
                                                    <span>Confirmer la réservation (€{currentTotalPrice} sur place)</span>
                                                    <ArrowRightIcon />
                                                </>
                                            )}
                                        </button>
                                    </div>

                                </div>

                            </div>
                        )}

                        {/* ══════════════════════════════════════════════════════════════ */}
                        {/* STEP 4: SUCCESS / CONFIRMED (For Cash on arrival) */}
                        {/* ══════════════════════════════════════════════════════════════ */}
                        {currentStep === "success" && (
                            <div className="bg-white rounded-2xl p-8 md:p-12 text-center space-y-7 border border-navy/15 shadow-md">
                                <div className="inline-flex h-20 w-20 items-center justify-center rounded-full bg-gold/10 border border-gold/40 text-gold mx-auto">
                                    <svg className="w-10 h-10" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" d="M5 13l4 4L19 7" />
                                    </svg>
                                </div>

                                <div>
                                    <h3 className="font-display text-3xl tracking-tight text-navy md:text-4xl mb-2">
                                        Réservation Confirmée !
                                    </h3>
                                    <p className="text-navy/60 text-sm max-w-md mx-auto">
                                        Votre chauffeur vous attendra à l'heure convenue. Le règlement s'effectuera directement à bord.
                                    </p>
                                </div>

                                <div className="bg-cream/70 rounded-2xl p-6 border border-navy/15 text-left max-w-xl mx-auto space-y-4">
                                    <div className="flex justify-between items-center border-b border-navy/15 pb-3">
                                        <span className="text-xs text-navy/40 uppercase tracking-wider font-semibold">Référence Dossier</span>
                                        <span className="text-xl font-mono font-black text-navy">{bookingRef}</span>
                                    </div>

                                    <div className="grid grid-cols-2 gap-4 text-sm">
                                        <div>
                                            <p className="text-xs text-navy/40 uppercase mb-0.5">Date & Heure</p>
                                            <p className="text-navy font-bold">{form.dateDebut} à {form.heureDebut}</p>
                                        </div>

                                        <div>
                                            <p className="text-xs text-navy/40 uppercase mb-0.5">Véhicule choisi</p>
                                            <p className="text-navy font-bold">{selectedVehicle.name}</p>
                                        </div>

                                        <div className="col-span-2">
                                            <p className="text-xs text-navy/40 uppercase mb-0.5">Trajet</p>
                                            <p className="text-navy font-semibold text-xs line-clamp-1">{form.departAddress}</p>
                                            <p className="text-navy/60 text-xs line-clamp-1">→ {form.arriveeAddress}</p>
                                        </div>

                                        <div className="col-span-2 bg-gold/10 border border-gold/30 rounded-xl p-3 text-center">
                                            <p className="text-xs text-navy/70 uppercase tracking-wide font-semibold mb-0.5">Montant à régler au chauffeur</p>
                                            <p className="text-2xl font-black text-navy">€{currentTotalPrice}</p>
                                            <p className="text-[11px] text-gold mt-0.5 font-semibold">Paiement sur place (Espèces ou Carte)</p>
                                        </div>

                                        <div>
                                            <p className="text-xs text-navy/40 uppercase mb-0.5">Passager</p>
                                            <p className="text-navy font-semibold">{form.paxCivilite} {form.paxNom} {form.paxPrenom}</p>
                                            <p className="text-xs text-navy/60">{form.paxTelephoneMobile}</p>
                                        </div>

                                        <div>
                                            <p className="text-xs text-navy/40 uppercase mb-0.5">Contact</p>
                                            <p className="text-navy font-semibold">{form.contactNom} {form.contactPrenom}</p>
                                            <p className="text-xs text-navy/60">{form.contactEmail}</p>
                                        </div>
                                    </div>
                                </div>

                                <div className="flex flex-col sm:flex-row justify-center gap-3 pt-2">
                                    <button
                                        type="button"
                                        onClick={() => setShowRatingModal(true)}
                                        className="px-5 py-3 font-bold text-navy bg-gold/15 hover:bg-gold/25 border border-gold/40 rounded-xl transition flex items-center justify-center gap-2 cursor-pointer shadow-sm"
                                    >
                                        <span>⭐ Évaluer mon trajet</span>
                                    </button>

                                    <button
                                        type="button"
                                        onClick={resetForm}
                                        className="px-6 py-3 font-semibold text-navy/80 bg-navy/5 border border-navy/15 hover:bg-navy/10 rounded-xl transition cursor-pointer"
                                    >
                                        Nouvelle réservation
                                    </button>

                                    <Link
                                        href="/"
                                        className="px-6 py-3 font-bold text-navy bg-gold hover:bg-gold-light rounded-xl transition shadow-md text-center"
                                    >
                                        Retour à l'accueil
                                    </Link>
                                </div>
                            </div>
                        )}

                    </form>

                </div>
            </main>

            {/* Rating Modal */}
            <RatingModal
                isOpen={showRatingModal}
                bookingRef={bookingRef}
                vehicleName={selectedVehicle.name}
                onClose={() => setShowRatingModal(false)}
            />

            {/* Footer */}
            <footer className="border-t border-gold/15 bg-navy py-8 text-xs text-cream/50">
                <div className="mx-auto flex max-w-7xl flex-col items-center justify-between gap-4 px-6 sm:flex-row">
                    <p>&copy; {new Date().getFullYear()} AEROCAB. Tous droits réservés.</p>
                    <div className="flex gap-6">
                        <Link href="/" className="font-medium transition-colors hover:text-gold">Accueil</Link>
                        <a href="https://www.waynium.com" target="_blank" rel="noopener noreferrer" className="transition-colors hover:text-gold">
                            Powered by WAYNIUM
                        </a>
                    </div>
                </div>
            </footer>
        </div>
    );
}
