﻿import React, { useState } from 'react';
import { Head, Link, router, usePage } from '@inertiajs/react';
import { PublicLayout } from '@/Layouts/PublicLayout';
import { CurrencyPrice } from '@/Components/CurrencyPrice';
import { 
    Calendar, Users, Check, Sparkles, Shield, 
    ArrowRight, ArrowLeft, CreditCard, Clock, 
    Lock, Plane, Coffee, Heart, CheckCircle 
} from 'lucide-react';

interface Props {
    searchParams: {
        check_in: string;
        check_out: string;
        adults: number;
        children: number;
        promo?: string;
    };
    availableRooms: any[];
    addOnExtras: any[];
}

export default function BookingEngine({
    searchParams,
    availableRooms = [],
    addOnExtras = [],
}: Props) {
    const { hotel } = usePage().props as any;
    const exchangeRate = hotel?.exchange_rate_ugx || 3800;

    // Booking Steps: 1: Room Selection, 2: Rate Plan & Add-ons, 3: Guest Details, 4: Payment & Review
    const [step, setStep] = useState(1);
    const [selectedRoom, setSelectedRoom] = useState<any>(null);
    const [selectedPlan, setSelectedPlan] = useState<any>(null);
    const [selectedAddOns, setSelectedAddOns] = useState<{ [id: number]: number }>({});
    const [currency, setCurrency] = useState<'USD' | 'UGX'>('USD');
    const [promoInput, setPromoInput] = useState(searchParams.promo || '');
    const [corporateCode, setCorporateCode] = useState('');
    const [paymentMethod, setPaymentMethod] = useState<'pesapal' | 'guarantee_hotel'>('pesapal');
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [errorMessage, setErrorMessage] = useState('');

    const [guestForm, setGuestForm] = useState({
        title: 'Mr.',
        first_name: '',
        last_name: '',
        email: '',
        phone: '',
        whatsapp_number: '',
        nationality: 'Uganda',
        company_name: '',
        estimated_arrival_time: '15:00',
        special_requests: '',
    });

    const handleSelectRoom = (roomData: any, plan: any) => {
        setSelectedRoom(roomData.room_type);
        setSelectedPlan(plan);
        setStep(2);
    };

    const toggleAddOn = (extraId: number, qty: number = 1) => {
        setSelectedAddOns(prev => {
            const next = { ...prev };
            if (next[extraId]) {
                delete next[extraId];
            } else {
                next[extraId] = qty;
            }
            return next;
        });
    };

    const checkInStr = searchParams?.check_in || new Date().toISOString().split('T')[0];
    const checkOutStr = searchParams?.check_out || new Date(Date.now() + 86400000).toISOString().split('T')[0];
    const nights = Math.max(1, Math.round((new Date(checkOutStr).getTime() - new Date(checkInStr).getTime()) / (1000 * 3600 * 24)) || 1);

    const roomSubtotal = selectedPlan ? (selectedPlan.nightly_usd * nights) : 0;
    const promoDiscount = selectedPlan ? (selectedPlan.discount_usd || 0) : 0;

    let addOnsTotal = 0;
    const addOnList: any[] = [];
    Object.entries(selectedAddOns).forEach(([id, qty]) => {
        const extra = addOnExtras.find(e => e.id === parseInt(id));
        if (extra) {
            const line = parseFloat(extra.price_usd) * qty;
            addOnsTotal += line;
            addOnList.push({ id: extra.id, name: extra.name, quantity: qty, price: line });
        }
    });

    const taxableAmount = Math.max(0, (roomSubtotal + addOnsTotal) - promoDiscount);
    const taxTotal = Math.round(taxableAmount * 0.18 * 100) / 100;
    const serviceCharge = Math.round(taxableAmount * 0.05 * 100) / 100;
    const grandTotalUsd = Math.round((taxableAmount + taxTotal + serviceCharge) * 100) / 100;
    const grandTotalUgx = Math.round(grandTotalUsd * exchangeRate);

    const handleFinalCheckout = async (e: React.FormEvent) => {
        e.preventDefault();
        setErrorMessage('');
        setIsSubmitting(true);

        const payload = {
            room_type_id: selectedRoom.id,
            rate_plan_id: selectedPlan.id,
            check_in: searchParams.check_in,
            check_out: searchParams.check_out,
            adults: searchParams.adults,
            children: searchParams.children,
            rooms_count: 1,
            // Guest Details
            title: guestForm.title,
            first_name: guestForm.first_name,
            last_name: guestForm.last_name,
            email: guestForm.email,
            phone: guestForm.phone,
            whatsapp_number: guestForm.whatsapp_number || guestForm.phone,
            nationality: guestForm.nationality,
            company_name: guestForm.company_name,
            estimated_arrival_time: guestForm.estimated_arrival_time,
            special_requests: guestForm.special_requests,
            // Payment & Codes
            payment_method: paymentMethod,
            promo_code: promoInput,
            corporate_code: corporateCode,
            currency: currency,
            selected_add_ons: Object.entries(selectedAddOns).map(([id, qty]) => ({ id: parseInt(id), quantity: qty })),
        };

        try {
            const res = await fetch('/booking/checkout', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content || '',
                    'Accept': 'application/json',
                },
                body: JSON.stringify(payload),
            });

            const data = await res.json();
            if (data.success && data.redirect) {
                window.location.href = data.redirect;
            } else {
                setErrorMessage(data.message || 'An error occurred during booking. Please try again.');
                setIsSubmitting(false);
            }
        } catch (err: any) {
            setErrorMessage('Network error processing reservation. Please check your connection.');
            setIsSubmitting(false);
        }
    };

    return (
        <PublicLayout>
            <Head title="Direct Booking Engine — Primon Hotel Naalya" />

            {/* Header Steps Tracker */}
            <section className="pt-28 pb-8 bg-[#1A1A1A] text-[#FBF9F5] border-b border-[#C5A880]/20">
                <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="flex flex-col sm:flex-row items-center justify-between gap-4 pb-6">
                        <div>
                            <span className="text-[10px] uppercase tracking-widest text-[#C5A880] font-semibold">
                                Primon Direct Reservation
                            </span>
                            <h1 className="font-serif text-2xl sm:text-3xl text-white font-light">
                                Select Your Suite & Extras
                            </h1>
                        </div>

                        {/* Currency Selector */}
                        <div className="flex items-center gap-2 border border-[#C5A880]/40 rounded-full p-1 text-xs">
                            <button
                                type="button"
                                onClick={() => setCurrency('USD')}
                                className={`px-3 py-1 rounded-full transition-all ${currency === 'USD' ? 'bg-[#C5A880] text-[#1A1A1A] font-bold' : 'text-gray-400'}`}
                            >
                                USD ($)
                            </button>
                            <button
                                type="button"
                                onClick={() => setCurrency('UGX')}
                                className={`px-3 py-1 rounded-full transition-all ${currency === 'UGX' ? 'bg-[#C5A880] text-[#1A1A1A] font-bold' : 'text-gray-400'}`}
                            >
                                UGX (USh)
                            </button>
                        </div>
                    </div>

                    {/* Step Indicators */}
                    <div className="grid grid-cols-4 gap-2 text-center text-xs pt-4 border-t border-white/10">
                        <div className={`py-2 rounded-lg font-medium transition-colors ${step >= 1 ? 'bg-[#C5A880] text-[#1A1A1A] font-bold' : 'text-gray-400 bg-white/5'}`}>
                            1. Select Room
                        </div>
                        <div className={`py-2 rounded-lg font-medium transition-colors ${step >= 2 ? 'bg-[#C5A880] text-[#1A1A1A] font-bold' : 'text-gray-400 bg-white/5'}`}>
                            2. Add-On Extras
                        </div>
                        <div className={`py-2 rounded-lg font-medium transition-colors ${step >= 3 ? 'bg-[#C5A880] text-[#1A1A1A] font-bold' : 'text-gray-400 bg-white/5'}`}>
                            3. Guest Details
                        </div>
                        <div className={`py-2 rounded-lg font-medium transition-colors ${step >= 4 ? 'bg-[#C5A880] text-[#1A1A1A] font-bold' : 'text-gray-400 bg-white/5'}`}>
                            4. Payment
                        </div>
                    </div>
                </div>
            </section>

            {/* Error Banner */}
            {errorMessage && (
                <div className="max-w-6xl mx-auto px-4 mt-6">
                    <div className="bg-[#9C382C] text-white p-4 rounded-xl text-xs font-medium">
                        {errorMessage}
                    </div>
                </div>
            )}

            {/* Step 1: Available Rooms & Rates */}
            {step === 1 && (
                <section className="py-12 bg-[#FBF9F5]">
                    <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 space-y-8">
                        <div className="flex items-center justify-between bg-[#F3EFEA] p-4 rounded-2xl border border-[#C5A880]/20 text-xs">
                            <div className="flex flex-wrap items-center gap-4 text-gray-700">
                                <span><strong>Dates:</strong> {searchParams.check_in} to {searchParams.check_out} ({nights} {nights === 1 ? 'Night' : 'Nights'})</span>
                                <span>•</span>
                                <span><strong>Guests:</strong> {searchParams.adults} Adult(s)</span>
                                {searchParams.promo && (
                                    <>
                                        <span>•</span>
                                        <span className="text-[#C5A880] font-semibold uppercase">Promo: {searchParams.promo}</span>
                                    </>
                                )}
                            </div>
                            <Link href="/" className="text-[#C5A880] font-semibold hover:underline">
                                Modify Dates
                            </Link>
                        </div>

                        {availableRooms.length === 0 ? (
                            <div className="text-center py-16 bg-[#F3EFEA] rounded-3xl p-8 border border-gray-300 space-y-4">
                                <h3 className="font-serif text-2xl font-normal text-[#1A1A1A]">No Suites Available for Selected Dates</h3>
                                <p className="text-xs text-gray-600">Please choose alternative dates or contact our concierge.</p>
                                <Link href="/" className="inline-block bg-[#1A1A1A] text-white px-6 py-2.5 rounded-full text-xs font-semibold uppercase">
                                    Change Dates
                                </Link>
                            </div>
                        ) : (
                            <div className="space-y-8">
                                {availableRooms.map((item) => {
                                    const room = item.room_type;
                                    return (
                                        <div
                                            key={room.id}
                                            className="bg-[#F3EFEA] rounded-3xl overflow-hidden border border-[#C5A880]/20 shadow-md grid grid-cols-1 lg:grid-cols-12"
                                        >
                                            <div className="lg:col-span-4 relative h-64 lg:h-auto">
                                                <img
                                                    src={room.featured_image || 'https://images.unsplash.com/photo-1590490360182-c33d57733427?auto=format&fit=crop&w=800&q=80'}
                                                    alt={room.name}
                                                    className="w-full h-full object-cover"
                                                />
                                                <div className="absolute top-3 left-3 bg-[#1A1A1A]/85 px-3 py-1 rounded-full text-[10px] text-[#C5A880] font-bold uppercase tracking-wider">
                                                    {item.available_count} Available
                                                </div>
                                            </div>

                                            <div className="lg:col-span-8 p-6 lg:p-8 flex flex-col justify-between space-y-6">
                                                <div className="space-y-2">
                                                    <div className="flex items-center justify-between">
                                                        <h3 className="font-serif text-2xl font-normal text-[#1A1A1A]">{room.name}</h3>
                                                        <span className="text-xs text-gray-500">{room.size_sqm} m² • {room.bed_type}</span>
                                                    </div>
                                                    <p className="text-xs text-gray-600 font-light leading-relaxed">{room.short_description}</p>
                                                </div>

                                                {/* Rate Plans for this Room */}
                                                <div className="space-y-3 pt-4 border-t border-gray-300">
                                                    <span className="text-[10px] uppercase tracking-wider text-gray-500 font-semibold block">
                                                        Select Rate Plan:
                                                    </span>
                                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                                        {item.rate_plans.map((plan: any) => (
                                                            <div
                                                                key={plan.id}
                                                                className="p-4 rounded-2xl bg-[#FBF9F5] border border-[#C5A880]/30 flex flex-col justify-between space-y-3 hover:border-[#C5A880] transition-colors"
                                                            >
                                                                <div>
                                                                    <div className="flex items-start justify-between">
                                                                        <h4 className="text-xs font-bold text-[#1A1A1A]">{plan.name}</h4>
                                                                        <span className="font-serif text-base font-bold text-[#C5A880]">
                                                                            <CurrencyPrice amountUsd={plan.nightly_usd} />
                                                                        </span>
                                                                    </div>
                                                                    <p className="text-[10px] text-gray-500 mt-1 font-light">{plan.cancellation_policy}</p>
                                                                </div>

                                                                <button
                                                                    type="button"
                                                                    onClick={() => handleSelectRoom(item, plan)}
                                                                    className="w-full bg-[#1A1A1A] hover:bg-[#C5A880] hover:text-[#1A1A1A] text-[#FBF9F5] py-2 rounded-xl text-xs font-semibold uppercase tracking-wider transition-all"
                                                                >
                                                                    Select Suite
                                                                </button>
                                                            </div>
                                                        ))}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        )}
                    </div>
                </section>
            )}

            {/* Step 2: Add-On Extras */}
            {step === 2 && selectedRoom && (
                <section className="py-12 bg-[#FBF9F5]">
                    <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 space-y-8">
                        <div className="bg-[#F3EFEA] p-6 rounded-3xl border border-[#C5A880]/20 flex items-center justify-between">
                            <div>
                                <span className="text-[10px] uppercase tracking-wider text-[#C5A880] font-semibold block">Selected Suite</span>
                                <h3 className="font-serif text-xl text-[#1A1A1A]">{selectedRoom.name}</h3>
                                <span className="text-xs text-gray-500">{selectedPlan.name} • {nights} Nights</span>
                            </div>
                            <button
                                onClick={() => setStep(1)}
                                className="text-xs font-semibold uppercase text-gray-600 hover:text-[#C5A880]"
                            >
                                Change Room
                            </button>
                        </div>

                        <div className="space-y-4">
                            <h3 className="font-serif text-2xl font-normal text-[#1A1A1A]">
                                Enhance Your Stay With Curated Extras
                            </h3>
                            <p className="text-xs text-gray-600 font-light">Select personalized amenities to prepare your arrival in Kampala.</p>

                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                {addOnExtras.map((extra) => {
                                    const isSelected = !!selectedAddOns[extra.id];
                                    return (
                                        <div
                                            key={extra.id}
                                            onClick={() => toggleAddOn(extra.id)}
                                            className={`p-6 rounded-2xl border cursor-pointer transition-all flex flex-col justify-between space-y-4 ${
                                                isSelected 
                                                    ? 'bg-[#1A1A1A] text-[#FBF9F5] border-[#C5A880] shadow-lg' 
                                                    : 'bg-[#F3EFEA] text-[#1A1A1A] border-[#C5A880]/20 hover:border-[#C5A880]'
                                            }`}
                                        >
                                            <div className="space-y-2">
                                                <div className="flex items-center justify-between">
                                                    <span className="text-xs font-bold uppercase tracking-wider">{extra.name}</span>
                                                    <span className="font-serif text-base font-bold text-[#C5A880]">
                                                        +<CurrencyPrice amountUsd={extra.price_usd} />
                                                    </span>
                                                </div>
                                                <p className="text-xs font-light text-gray-400">{extra.description}</p>
                                            </div>

                                            <div className="flex items-center justify-between pt-2 text-xs">
                                                <span className={isSelected ? 'text-[#C5A880] font-semibold' : 'text-gray-500'}>
                                                    {isSelected ? '✓ Added to Reservation' : '+ Click to Add'}
                                                </span>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        </div>

                        <div className="flex items-center justify-between pt-6 border-t border-gray-300">
                            <button
                                onClick={() => setStep(1)}
                                className="px-6 py-3 rounded-full text-xs font-semibold uppercase text-gray-700 hover:text-black flex items-center gap-1"
                            >
                                <ArrowLeft className="h-4 w-4" /> Back
                            </button>
                            <button
                                onClick={() => setStep(3)}
                                className="bg-[#1A1A1A] hover:bg-[#C5A880] hover:text-[#1A1A1A] text-[#FBF9F5] px-8 py-3.5 rounded-full text-xs font-bold uppercase tracking-widest transition-all shadow-md flex items-center gap-2"
                            >
                                <span>Continue to Guest Details</span>
                                <ArrowRight className="h-4 w-4" />
                            </button>
                        </div>
                    </div>
                </section>
            )}

            {/* Step 3: Guest Details Form */}
            {step === 3 && selectedRoom && (
                <section className="py-12 bg-[#FBF9F5]">
                    <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 space-y-8">
                        <div className="space-y-2">
                            <span className="text-[10px] uppercase tracking-widest text-[#C5A880] font-semibold">
                                Guest Information
                            </span>
                            <h2 className="font-serif text-3xl font-light text-[#1A1A1A]">
                                Primary Guest & Arrival Details
                            </h2>
                        </div>

                        <div className="bg-[#F3EFEA] p-8 rounded-3xl border border-[#C5A880]/20 space-y-6">
                            <div className="grid grid-cols-1 sm:grid-cols-4 gap-4">
                                <div>
                                    <label className="text-xs font-semibold uppercase text-gray-600 block mb-1">Title</label>
                                    <select
                                        value={guestForm.title}
                                        onChange={(e) => setGuestForm({ ...guestForm, title: e.target.value })}
                                        className="w-full bg-white border border-gray-300 rounded-xl px-3 py-2 text-xs focus:outline-none focus:border-[#C5A880]"
                                    >
                                        <option value="Mr.">Mr.</option>
                                        <option value="Mrs.">Mrs.</option>
                                        <option value="Ms.">Ms.</option>
                                        <option value="Dr.">Dr.</option>
                                        <option value="Amb.">Ambassador</option>
                                        <option value="Hon.">Honorable</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="text-xs font-semibold uppercase text-gray-600 block mb-1">First Name</label>
                                    <input
                                        type="text"
                                        required
                                        value={guestForm.first_name}
                                        onChange={(e) => setGuestForm({ ...guestForm, first_name: e.target.value })}
                                        className="w-full bg-white border border-gray-300 rounded-xl px-3 py-2 text-xs focus:outline-none focus:border-[#C5A880]"
                                    />
                                </div>
                                <div className="sm:col-span-2">
                                    <label className="text-xs font-semibold uppercase text-gray-600 block mb-1">Last Name</label>
                                    <input
                                        type="text"
                                        required
                                        value={guestForm.last_name}
                                        onChange={(e) => setGuestForm({ ...guestForm, last_name: e.target.value })}
                                        className="w-full bg-white border border-gray-300 rounded-xl px-3 py-2 text-xs focus:outline-none focus:border-[#C5A880]"
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div>
                                    <label className="text-xs font-semibold uppercase text-gray-600 block mb-1">Email Address</label>
                                    <input
                                        type="email"
                                        required
                                        value={guestForm.email}
                                        onChange={(e) => setGuestForm({ ...guestForm, email: e.target.value })}
                                        className="w-full bg-white border border-gray-300 rounded-xl px-3 py-2 text-xs focus:outline-none focus:border-[#C5A880]"
                                    />
                                </div>
                                <div>
                                    <label className="text-xs font-semibold uppercase text-gray-600 block mb-1">Phone / WhatsApp</label>
                                    <input
                                        type="text"
                                        required
                                        value={guestForm.phone}
                                        onChange={(e) => setGuestForm({ ...guestForm, phone: e.target.value })}
                                        className="w-full bg-white border border-gray-300 rounded-xl px-3 py-2 text-xs focus:outline-none focus:border-[#C5A880]"
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div>
                                    <label className="text-xs font-semibold uppercase text-gray-600 block mb-1">Company / Organization (Optional)</label>
                                    <input
                                        type="text"
                                        value={guestForm.company_name}
                                        onChange={(e) => setGuestForm({ ...guestForm, company_name: e.target.value })}
                                        className="w-full bg-white border border-gray-300 rounded-xl px-3 py-2 text-xs focus:outline-none focus:border-[#C5A880]"
                                    />
                                </div>
                                <div>
                                    <label className="text-xs font-semibold uppercase text-gray-600 block mb-1">Estimated Arrival Time</label>
                                    <select
                                        value={guestForm.estimated_arrival_time}
                                        onChange={(e) => setGuestForm({ ...guestForm, estimated_arrival_time: e.target.value })}
                                        className="w-full bg-white border border-gray-300 rounded-xl px-3 py-2 text-xs focus:outline-none focus:border-[#C5A880]"
                                    >
                                        <option value="14:00">14:00 (Standard Check-in)</option>
                                        <option value="15:00">15:00</option>
                                        <option value="17:00">17:00</option>
                                        <option value="20:00">20:00 (Evening)</option>
                                        <option value="23:00">23:00 (Late Flight Arrival)</option>
                                    </select>
                                </div>
                            </div>

                            <div>
                                <label className="text-xs font-semibold uppercase text-gray-600 block mb-1">Special Requests or Preferences</label>
                                <textarea
                                    rows={2}
                                    placeholder="e.g. Quiet high floor, feather pillow, early breakfast box"
                                    value={guestForm.special_requests}
                                    onChange={(e) => setGuestForm({ ...guestForm, special_requests: e.target.value })}
                                    className="w-full bg-white border border-gray-300 rounded-xl px-3.5 py-2 text-xs focus:outline-none focus:border-[#C5A880]"
                                />
                            </div>
                        </div>

                        <div className="flex items-center justify-between pt-6 border-t border-gray-300">
                            <button
                                onClick={() => setStep(2)}
                                className="px-6 py-3 rounded-full text-xs font-semibold uppercase text-gray-700 hover:text-black flex items-center gap-1"
                            >
                                <ArrowLeft className="h-4 w-4" /> Back
                            </button>
                            <button
                                onClick={() => {
                                    if (!guestForm.first_name || !guestForm.last_name || !guestForm.email || !guestForm.phone) {
                                        setErrorMessage('Please fill in your name, email, and phone number.');
                                        return;
                                    }
                                    setErrorMessage('');
                                    setStep(4);
                                }}
                                className="bg-[#1A1A1A] hover:bg-[#C5A880] hover:text-[#1A1A1A] text-[#FBF9F5] px-8 py-3.5 rounded-full text-xs font-bold uppercase tracking-widest transition-all shadow-md flex items-center gap-2"
                            >
                                <span>Review & Payment</span>
                                <ArrowRight className="h-4 w-4" />
                            </button>
                        </div>
                    </div>
                </section>
            )}

            {/* Step 4: Final Summary & Payment Choice */}
            {step === 4 && selectedRoom && (
                <section className="py-12 bg-[#FBF9F5]">
                    <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
                        <form onSubmit={handleFinalCheckout} className="grid grid-cols-1 lg:grid-cols-12 gap-8">
                            {/* Left: Payment Method & Policies */}
                            <div className="lg:col-span-7 space-y-6">
                                <div className="space-y-2">
                                    <span className="text-[10px] uppercase tracking-widest text-[#C5A880] font-semibold">
                                        Step 4 of 4
                                    </span>
                                    <h2 className="font-serif text-3xl font-light text-[#1A1A1A]">
                                        Payment Method
                                    </h2>
                                </div>

                                <div className="space-y-3">
                                    {/* Option 1: Pesapal Online */}
                                    <label
                                        className={`p-6 rounded-2xl border flex items-start gap-4 cursor-pointer transition-all ${
                                            paymentMethod === 'pesapal'
                                                ? 'bg-[#1A1A1A] text-[#FBF9F5] border-[#C5A880] shadow-lg'
                                                : 'bg-[#F3EFEA] text-[#1A1A1A] border-gray-300'
                                        }`}
                                    >
                                        <input
                                            type="radio"
                                            name="paymentMethod"
                                            checked={paymentMethod === 'pesapal'}
                                            onChange={() => setPaymentMethod('pesapal')}
                                            className="mt-1 text-[#C5A880]"
                                        />
                                        <div className="space-y-1">
                                            <div className="flex items-center gap-2">
                                                <CreditCard className="h-4 w-4 text-[#C5A880]" />
                                                <span className="text-xs font-bold uppercase tracking-wider">
                                                    Pesapal Online Gateway (Mobile Money & Cards)
                                                </span>
                                            </div>
                                            <p className="text-xs font-light text-gray-400">
                                                Instant confirmation via MTN Mobile Money, Airtel Money, Visa, or Mastercard.
                                            </p>
                                        </div>
                                    </label>

                                    {/* Option 2: Pay at Hotel Guarantee */}
                                    <label
                                        className={`p-6 rounded-2xl border flex items-start gap-4 cursor-pointer transition-all ${
                                            paymentMethod === 'guarantee_hotel'
                                                ? 'bg-[#1A1A1A] text-[#FBF9F5] border-[#C5A880] shadow-lg'
                                                : 'bg-[#F3EFEA] text-[#1A1A1A] border-gray-300'
                                        }`}
                                    >
                                        <input
                                            type="radio"
                                            name="paymentMethod"
                                            checked={paymentMethod === 'guarantee_hotel'}
                                            onChange={() => setPaymentMethod('guarantee_hotel')}
                                            className="mt-1 text-[#C5A880]"
                                        />
                                        <div className="space-y-1">
                                            <div className="flex items-center gap-2">
                                                <Lock className="h-4 w-4 text-[#C5A880]" />
                                                <span className="text-xs font-bold uppercase tracking-wider">
                                                    Guarantee Reservation & Pay at Hotel
                                                </span>
                                            </div>
                                            <p className="text-xs font-light text-gray-400">
                                                Settle upon check-in via Cash, Card, or Mobile Money (Subject to 24h cancellation rule).
                                            </p>
                                        </div>
                                    </label>
                                </div>

                                <div className="p-4 bg-[#F3EFEA] rounded-2xl border border-[#C5A880]/20 space-y-2 text-xs text-gray-700">
                                    <span className="font-semibold block text-[#1A1A1A]">Guest Booking Guarantee</span>
                                    <p className="font-light leading-relaxed">
                                        By confirming, you agree to Primon Hotel's terms & conditions. Free cancellation up to 24 hours prior to 14:00 on the day of arrival.
                                    </p>
                                </div>

                                <div className="flex items-center justify-between pt-4">
                                    <button
                                        type="button"
                                        onClick={() => setStep(3)}
                                        className="text-xs font-semibold uppercase text-gray-700 hover:text-black flex items-center gap-1"
                                    >
                                        <ArrowLeft className="h-4 w-4" /> Back to Details
                                    </button>
                                </div>
                            </div>

                            {/* Right: Transparent Price Breakdown Summary */}
                            <div className="lg:col-span-5 bg-[#1A1A1A] text-[#FBF9F5] p-8 rounded-3xl border border-[#C5A880]/30 shadow-2xl space-y-6 flex flex-col justify-between">
                                <div className="space-y-4">
                                    <span className="text-[10px] uppercase tracking-widest text-[#C5A880] font-semibold block">
                                        Reservation Summary
                                    </span>

                                    <div className="space-y-1 pb-4 border-b border-white/10">
                                        <h4 className="font-serif text-xl text-white">{selectedRoom.name}</h4>
                                        <p className="text-xs text-gray-400">{searchParams.check_in} — {searchParams.check_out} ({nights} Nights)</p>
                                        <p className="text-xs text-[#C5A880]">{guestForm.first_name} {guestForm.last_name}</p>
                                    </div>

                                    {/* Line Items */}
                                    <div className="space-y-2 text-xs text-gray-300">
                                        <div className="flex justify-between">
                                            <span>Room Accommodation ({nights} nights)</span>
                                            <span><CurrencyPrice amountUsd={roomSubtotal} /></span>
                                        </div>

                                        {addOnList.map((a, i) => (
                                            <div key={i} className="flex justify-between text-[#C5A880]">
                                                <span>+ {a.name} (x{a.quantity})</span>
                                                <span><CurrencyPrice amountUsd={a.price} /></span>
                                            </div>
                                        ))}

                                        {promoDiscount > 0 && (
                                            <div className="flex justify-between text-green-400">
                                                <span>Promo Code Discount</span>
                                                <span>-<CurrencyPrice amountUsd={promoDiscount} /></span>
                                            </div>
                                        )}

                                        <div className="flex justify-between text-gray-400">
                                            <span>VAT (18%) & Tourism Levy</span>
                                            <span><CurrencyPrice amountUsd={taxTotal} /></span>
                                        </div>

                                        <div className="flex justify-between text-gray-400">
                                            <span>Service Charge (5%)</span>
                                            <span><CurrencyPrice amountUsd={serviceCharge} /></span>
                                        </div>
                                    </div>

                                    {/* Grand Total */}
                                    <div className="pt-4 border-t border-white/10 space-y-1">
                                        <div className="flex items-baseline justify-between">
                                            <span className="text-xs uppercase tracking-wider text-gray-300 font-semibold">Total Price</span>
                                            <span className="font-serif text-3xl font-bold text-[#C5A880]">
                                                {currency === 'UGX' 
                                                    ? new Intl.NumberFormat('en-UG', { style: 'currency', currency: 'UGX' }).format(grandTotalUgx)
                                                    : new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(grandTotalUsd)
                                                }
                                            </span>
                                        </div>
                                        <span className="text-[10px] text-gray-400 block text-right">Includes all taxes and fees</span>
                                    </div>
                                </div>

                                <button
                                    type="submit"
                                    disabled={isSubmitting}
                                    className="w-full bg-[#C5A880] hover:bg-[#DFC7A5] text-[#1A1A1A] py-4 rounded-xl text-xs font-bold uppercase tracking-widest transition-all shadow-xl flex items-center justify-center gap-2 mt-6"
                                >
                                    {isSubmitting ? (
                                        <span>Processing Reservation...</span>
                                    ) : (
                                        <>
                                            <CheckCircle className="h-4 w-4" />
                                            <span>Confirm & Reserve Room</span>
                                        </>
                                    )}
                                </button>
                            </div>
                        </form>
                    </div>
                </section>
            )}
        </PublicLayout>
    );
}
