import { useState, useEffect, useRef, useCallback } from 'react'
import LogoMark from './LogoMark'

// ── Types ─────────────────────────────────────────────────────────────────────
interface FormData {
  isMiseADisposition: boolean
  dateDebut: string
  heureDebut: string
  nbHeure: string
  departAddress: string
  departTransportNum: string
  departTransportTime: string
  arriveeAddress: string
  arriveeTransportNum: string
  arriveeTransportTime: string
  totalPax: string
  totalBagage: string
  noteChauffeur: string
  paxCivilite: string
  paxNom: string
  paxPrenom: string
  paxTelephoneMobile: string
  paxTelephoneFixe: string
  paxLangue: string
  paxInfoParticuliere: string
  societeFacturation: string
  refClientDossier: string
  infoComplementaire: string
  contactCivilite: string
  contactNom: string
  contactPrenom: string
  contactEmail: string
  contactTelephone: string
  contactLangue: string
  sameAsPax: boolean
}

const INITIAL_FORM: FormData = {
  isMiseADisposition: false,
  dateDebut: '',
  heureDebut: '',
  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',
  sameAsPax: true,
}

const API_BASE = 'https://unique-myers-rich-dirt.trycloudflare.com';

// ── Address autocomplete ──────────────────────────────────────────────────────
function AddressInput({
  label, value, onChange, placeholder, required = false
}: {
  label: string; value: string; onChange: (v: string) => void; placeholder?: string; required?: boolean
}) {
  const [query, setQuery] = useState(value)
  const [suggestions, setSuggestions] = useState<string[]>([])
  const [open, setOpen] = useState(false)
  const [loading, setLoading] = useState(false)
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null)
  const wrapRef = useRef<HTMLDivElement>(null)

  useEffect(() => { setQuery(value) }, [value])

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target as Node)) setOpen(false)
    }
    document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [])

  const search = useCallback((q: string) => {
    if (timer.current) clearTimeout(timer.current)
    if (q.length < 3) { setSuggestions([]); return }
    timer.current = setTimeout(async () => {
      setLoading(true)
      try {
        const res = await fetch(`${API_BASE}/geolocation/${encodeURIComponent(q)}`, { headers: { Accept: 'application/json' } })
        const json = await res.json()
        if (json.success && Array.isArray(json.data)) {
          setSuggestions(json.data.map((d: { display_name: string }) => d.display_name))
          setOpen(true)
        }
      } catch { /* ignore */ }
      setLoading(false)
    }, 350)
  }, [])

  const handleChange = (v: string) => {
    setQuery(v)
    onChange(v)
    search(v)
  }

  const pick = (s: string) => {
    setQuery(s)
    onChange(s)
    setSuggestions([])
    setOpen(false)
  }

  return (
    <div className="relative" ref={wrapRef}>
      <label className="block text-xs font-semibold tracking-wide uppercase mb-1.5" style={{ color: '#6b7280' }}>
        {label}{required && <span className="text-[#c9a84c] ml-0.5">*</span>}
      </label>
      <div className="relative">
        <input
          type="text"
          value={query}
          onChange={e => handleChange(e.target.value)}
          onFocus={() => { if (suggestions.length > 0) setOpen(true) }}
          placeholder={placeholder}
          required={required}
          className="w-full px-4 py-3 rounded-xl text-sm outline-none transition-all duration-200 pr-10"
          style={{
            background: '#f8f5f0',
            border: '1.5px solid #e5e0d8',
            color: '#0f1f3d',
          }}
        />
        {loading && (
          <span className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 border-2 border-[#c9a84c] border-t-transparent rounded-full animate-spin" />
        )}
      </div>
      {open && suggestions.length > 0 && (
        <ul
          className="absolute z-50 mt-1 w-full rounded-xl overflow-hidden shadow-xl"
          style={{ background: '#fff', border: '1px solid #e5e0d8', maxHeight: '200px', overflowY: 'auto' }}
        >
          {suggestions.map((s, i) => (
            <li
              key={i}
              onMouseDown={() => pick(s)}
              className="px-4 py-2.5 text-xs cursor-pointer hover:bg-[#f8f5f0] transition-colors"
              style={{ color: '#0f1f3d', borderBottom: i < suggestions.length - 1 ? '1px solid #f0ece4' : 'none' }}
            >
              {s}
            </li>
          ))}
        </ul>
      )}
    </div>
  )
}

// ── Small reusable inputs ─────────────────────────────────────────────────────
function Field({ label, required, children }: { label: string; required?: boolean; children: React.ReactNode }) {
  return (
    <div>
      <label className="block text-xs font-semibold tracking-wide uppercase mb-1.5" style={{ color: '#6b7280' }}>
        {label}{required && <span className="text-[#c9a84c] ml-0.5">*</span>}
      </label>
      {children}
    </div>
  )
}

const inputCls = "w-full px-4 py-3 rounded-xl text-sm outline-none transition-all duration-200"
const inputStyle = { background: '#f8f5f0', border: '1.5px solid #e5e0d8', color: '#0f1f3d' }

function TextInput({ value, onChange, placeholder, type = 'text', required }: {
  value: string; onChange: (v: string) => void; placeholder?: string; type?: string; required?: boolean
}) {
  return (
    <input
      type={type}
      value={value}
      onChange={e => onChange(e.target.value)}
      placeholder={placeholder}
      required={required}
      className={inputCls}
      style={inputStyle}
    />
  )
}

function Select({ value, onChange, options }: {
  value: string; onChange: (v: string) => void; options: { value: string; label: string }[]
}) {
  return (
    <select
      value={value}
      onChange={e => onChange(e.target.value)}
      className={inputCls + ' cursor-pointer appearance-none'}
      style={{ ...inputStyle, backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%236b7280' stroke-width='2'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E")`, backgroundRepeat: 'no-repeat', backgroundPosition: 'right 12px center', backgroundSize: '16px', paddingRight: '36px' }}
    >
      {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
    </select>
  )
}

// ── Section heading ───────────────────────────────────────────────────────────
function SectionTitle({ step, title, subtitle }: { step: number; title: string; subtitle?: string }) {
  return (
    <div className="flex items-start gap-4 mb-6">
      <div className="w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold flex-shrink-0 mt-0.5" style={{ background: '#0f1f3d', color: '#c9a84c' }}>
        {step}
      </div>
      <div>
        <h3 className="text-base font-semibold" style={{ color: '#0f1f3d', fontFamily: 'DM Serif Display, serif' }}>{title}</h3>
        {subtitle && <p className="text-xs mt-0.5" style={{ color: '#9ca3af' }}>{subtitle}</p>}
      </div>
    </div>
  )
}

// ── Main modal ────────────────────────────────────────────────────────────────
interface Props {
  open: boolean
  onClose: () => void
}

export default function ReservationModal({ open, onClose }: Props) {
  const [form, setForm] = useState<FormData>(INITIAL_FORM)
  const [step, setStep] = useState(1)
  const [submitting, setSubmitting] = useState(false)
  const [submitted, setSubmitted] = useState(false)
  const [error, setError] = useState('')

  const set = (key: keyof FormData, value: string | boolean) =>
    setForm(f => ({ ...f, [key]: value }))

  // Sync contact from pax when sameAsPax
  useEffect(() => {
    if (form.sameAsPax) {
      setForm(f => ({
        ...f,
        contactCivilite: f.paxCivilite,
        contactNom: f.paxNom,
        contactPrenom: f.paxPrenom,
        contactLangue: f.paxLangue,
      }))
    }
  }, [form.sameAsPax, form.paxCivilite, form.paxNom, form.paxPrenom, form.paxLangue])

  // Close on escape
  useEffect(() => {
    if (!open) return
    const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() }
    window.addEventListener('keydown', handler)
    return () => window.removeEventListener('keydown', handler)
  }, [open, onClose])

  // Lock scroll
  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : ''
    return () => { document.body.style.overflow = '' }
  }, [open])

  const totalSteps = 3

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setSubmitting(true)
    setError('')
    try {
      const payload: Record<string, string | number> = {
        dateDebut: form.dateDebut,
        heureDebut: form.heureDebut,
        departAddress: form.departAddress,
        arriveeAddress: form.arriveeAddress,
        totalPax: form.totalPax,
        totalBagage: form.totalBagage,
        paxCivilite: form.paxCivilite,
        paxNom: form.paxNom,
        paxPrenom: form.paxPrenom,
        paxTelephoneMobile: form.paxTelephoneMobile,
        paxLangue: form.paxLangue,
        contactCivilite: form.contactCivilite,
        contactNom: form.contactNom,
        contactPrenom: form.contactPrenom,
        contactEmail: form.contactEmail,
        contactLangue: form.contactLangue,
        isMiseADisposition: form.isMiseADisposition ? 1 : 0,
      }
      if (form.isMiseADisposition) payload.nbHeure = form.nbHeure
      if (form.noteChauffeur) payload.noteChauffeur = form.noteChauffeur
      if (form.paxTelephoneFixe) payload.paxTelephoneFixe = form.paxTelephoneFixe
      if (form.paxInfoParticuliere) payload.paxInfoParticuliere = form.paxInfoParticuliere
      if (form.departTransportNum) payload.departTransportNum = form.departTransportNum
      if (form.departTransportTime) payload.departTransportTime = form.departTransportTime
      if (form.arriveeTransportNum) payload.arriveeTransportNum = form.arriveeTransportNum
      if (form.arriveeTransportTime) payload.arriveeTransportTime = form.arriveeTransportTime
      if (form.societeFacturation) payload.societeFacturation = form.societeFacturation
      if (form.refClientDossier) payload.refClientDossier = form.refClientDossier
      if (form.infoComplementaire) payload.infoComplementaire = form.infoComplementaire
      if (form.contactTelephone) payload.contactTelephone = form.contactTelephone

      const res = await fetch(`${API_BASE}/reservation`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
        body: JSON.stringify(payload),
      })
      if (res.ok || res.status === 201 || res.status === 302) {
        setSubmitted(true)
      } else {
        const json = await res.json().catch(() => ({}))
        setError(json?.message || `Erreur ${res.status}. Veuillez réessayer.`)
      }
    } catch {
      setError('Erreur de connexion. Veuillez réessayer.')
    }
    setSubmitting(false)
  }

  const civiliteOptions = [{ value: 'M.', label: 'M.' }, { value: 'Mme.', label: 'Mme.' }]
  const langOptions = [{ value: 'FR', label: 'Français' }, { value: 'EN', label: 'English' }, { value: 'NL', label: 'Nederlands' }, { value: 'DE', label: 'Deutsch' }]

  if (!open) return null

  return (
    <div
      className="fixed inset-0 z-[100] flex"
      style={{ background: 'rgba(15,31,61,0.7)', backdropFilter: 'blur(6px)' }}
      onClick={e => { if (e.target === e.currentTarget) onClose() }}
    >
      {/* Panel */}
      <div
        className="ml-auto h-full flex flex-col overflow-hidden w-full max-w-2xl"
        style={{
          background: '#ffffff',
          animation: 'slidePanel 0.4s cubic-bezier(0.22,1,0.36,1) both',
        }}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-8 py-5 flex-shrink-0" style={{ background: '#0f1f3d', borderBottom: '1px solid rgba(201,168,76,0.2)' }}>
          <div className="flex items-center gap-3">
            <LogoMark color="#c9a84c" size={30} />
            <div>
              <div className="text-white font-bold tracking-widest text-sm" style={{ fontFamily: 'DM Serif Display, serif' }}>AEROCAB</div>
              <div className="text-xs" style={{ color: 'rgba(248,245,240,0.5)' }}>Réservation en ligne</div>
            </div>
          </div>
          <button onClick={onClose} className="w-9 h-9 rounded-full flex items-center justify-center transition-colors hover:bg-white/10" style={{ color: 'rgba(248,245,240,0.6)' }} aria-label="Fermer">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="w-5 h-5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>

        {/* Step progress */}
        {!submitted && (
          <div className="flex px-8 py-4 gap-2 flex-shrink-0" style={{ background: '#f8f5f0', borderBottom: '1px solid #ede9e0' }}>
            {Array.from({ length: totalSteps }).map((_, i) => (
              <div key={i} className="flex items-center gap-2 flex-1">
                <div
                  className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0 transition-all duration-300"
                  style={{
                    background: i + 1 <= step ? '#0f1f3d' : '#e5e0d8',
                    color: i + 1 <= step ? '#c9a84c' : '#9ca3af',
                  }}
                >
                  {i + 1 < step ? '✓' : i + 1}
                </div>
                <div className="text-xs font-medium" style={{ color: i + 1 === step ? '#0f1f3d' : '#9ca3af' }}>
                  {['Trajet', 'Passager', 'Contact'][i]}
                </div>
                {i < totalSteps - 1 && <div className="flex-1 h-px ml-1" style={{ background: '#e5e0d8' }} />}
              </div>
            ))}
          </div>
        )}

        {/* Body */}
        <div className="flex-1 overflow-y-auto" style={{ scrollbarWidth: 'thin', scrollbarColor: '#c9a84c transparent' }}>
          {submitted ? (
            <div className="flex flex-col items-center justify-center h-full px-8 py-16 text-center">
              <div className="w-20 h-20 rounded-full flex items-center justify-center mb-6" style={{ background: 'rgba(201,168,76,0.12)' }}>
                <svg viewBox="0 0 24 24" fill="none" stroke="#c9a84c" strokeWidth="2" className="w-10 h-10">
                  <polyline points="20 6 9 17 4 12"/>
                </svg>
              </div>
              <h2 className="text-2xl mb-3" style={{ fontFamily: 'DM Serif Display, serif', color: '#0f1f3d' }}>Demande envoyée!</h2>
              <p className="text-sm leading-relaxed mb-8 max-w-sm" style={{ color: '#6b7280' }}>
                Votre demande de réservation a bien été reçue. Nous vous contacterons rapidement pour confirmer votre trajet.
              </p>
              <div className="flex flex-col gap-3 w-full max-w-xs">
                <button
                  onClick={() => { setSubmitted(false); setForm(INITIAL_FORM); setStep(1) }}
                  className="px-6 py-3 rounded-full text-sm font-semibold transition-all duration-200 hover:scale-105"
                  style={{ background: '#0f1f3d', color: '#c9a84c' }}
                >
                  Nouvelle réservation
                </button>
                <button onClick={onClose} className="px-6 py-3 rounded-full text-sm font-semibold border transition-all duration-200" style={{ borderColor: '#e5e0d8', color: '#6b7280' }}>
                  Fermer
                </button>
              </div>
            </div>
          ) : (
            <form onSubmit={handleSubmit} className="px-8 py-8">

              {/* ── STEP 1 : Trajet ─────────────────────────────────────── */}
              {step === 1 && (
                <div style={{ animation: 'fadeStepIn 0.35s ease both' }}>
                  <SectionTitle step={1} title="Détails du trajet" subtitle="Adresses, date, heure et type de service" />

                  {/* Mise à disposition toggle */}
                  <div className="mb-6 p-4 rounded-xl flex items-center gap-4 cursor-pointer select-none" style={{ background: '#f8f5f0', border: '1.5px solid #e5e0d8' }} onClick={() => set('isMiseADisposition', !form.isMiseADisposition)}>
                    <div className="w-11 h-6 rounded-full relative flex-shrink-0 transition-colors duration-200" style={{ background: form.isMiseADisposition ? '#0f1f3d' : '#d1d5db' }}>
                      <div className="absolute top-1 w-4 h-4 rounded-full bg-white shadow transition-transform duration-200" style={{ transform: form.isMiseADisposition ? 'translateX(21px)' : 'translateX(4px)' }} />
                    </div>
                    <div>
                      <div className="text-sm font-semibold" style={{ color: '#0f1f3d' }}>Mise à disposition</div>
                      <div className="text-xs" style={{ color: '#9ca3af' }}>Tarification à l'heure plutôt qu'au trajet</div>
                    </div>
                    {form.isMiseADisposition && (
                      <div className="ml-auto">
                        <Select value={form.nbHeure} onChange={v => set('nbHeure', v)} options={[2,3,4,5,6,7,8].map(n => ({ value: String(n), label: `${n}h` }))} />
                      </div>
                    )}
                  </div>

                  <div className="grid grid-cols-2 gap-4 mb-4">
                    <Field label="Date" required>
                      <TextInput type="date" value={form.dateDebut} onChange={v => set('dateDebut', v)} required />
                    </Field>
                    <Field label="Heure" required>
                      <TextInput type="time" value={form.heureDebut} onChange={v => set('heureDebut', v)} required />
                    </Field>
                  </div>

                  <div className="flex flex-col gap-4 mb-4">
                    <AddressInput label="Adresse de départ" value={form.departAddress} onChange={v => set('departAddress', v)} placeholder="Ex: Aéroport de Bruxelles, Zaventem" required />
                    <div className="grid grid-cols-2 gap-4">
                      <Field label="N° transport départ">
                        <TextInput value={form.departTransportNum} onChange={v => set('departTransportNum', v)} placeholder="Ex: SN3702" />
                      </Field>
                      <Field label="Heure transport départ">
                        <TextInput type="time" value={form.departTransportTime} onChange={v => set('departTransportTime', v)} />
                      </Field>
                    </div>
                  </div>

                  {/* Arrow divider */}
                  <div className="flex items-center justify-center my-2 mb-4">
                    <div className="flex-1 h-px" style={{ background: '#e5e0d8' }} />
                    <div className="mx-3 w-8 h-8 rounded-full flex items-center justify-center" style={{ background: '#0f1f3d' }}>
                      <svg viewBox="0 0 24 24" fill="none" stroke="#c9a84c" strokeWidth="2.5" className="w-4 h-4"><line x1="12" y1="5" x2="12" y2="19"/><polyline points="19 12 12 19 5 12"/></svg>
                    </div>
                    <div className="flex-1 h-px" style={{ background: '#e5e0d8' }} />
                  </div>

                  <div className="flex flex-col gap-4 mb-6">
                    <AddressInput label="Adresse d'arrivée" value={form.arriveeAddress} onChange={v => set('arriveeAddress', v)} placeholder="Ex: Rue de la Loi, Bruxelles" required />
                    <div className="grid grid-cols-2 gap-4">
                      <Field label="N° transport arrivée">
                        <TextInput value={form.arriveeTransportNum} onChange={v => set('arriveeTransportNum', v)} placeholder="Ex: SN3702" />
                      </Field>
                      <Field label="Heure transport arrivée">
                        <TextInput type="time" value={form.arriveeTransportTime} onChange={v => set('arriveeTransportTime', v)} />
                      </Field>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4 mb-6">
                    <Field label="Passagers" required>
                      <Select value={form.totalPax} onChange={v => set('totalPax', v)} options={[1,2,3,4,5,6,7,8].map(n => ({ value: String(n), label: `${n} passager${n > 1 ? 's' : ''}` }))} />
                    </Field>
                    <Field label="Bagages" required>
                      <Select value={form.totalBagage} onChange={v => set('totalBagage', v)} options={[0,1,2,3,4,5,6,7,8].map(n => ({ value: String(n), label: `${n} bagage${n > 1 ? 's' : ''}` }))} />
                    </Field>
                  </div>

                  <Field label="Note pour le chauffeur">
                    <textarea
                      value={form.noteChauffeur}
                      onChange={e => set('noteChauffeur', e.target.value)}
                      placeholder="Informations utiles pour le chauffeur..."
                      rows={3}
                      className="w-full px-4 py-3 rounded-xl text-sm outline-none resize-none transition-all duration-200"
                      style={inputStyle}
                    />
                  </Field>
                </div>
              )}

              {/* ── STEP 2 : Passager ───────────────────────────────────── */}
              {step === 2 && (
                <div style={{ animation: 'fadeStepIn 0.35s ease both' }}>
                  <SectionTitle step={2} title="Informations passager" subtitle="Coordonnées du voyageur principal" />

                  <div className="grid grid-cols-3 gap-4 mb-4">
                    <Field label="Civilité" required>
                      <Select value={form.paxCivilite} onChange={v => set('paxCivilite', v)} options={civiliteOptions} />
                    </Field>
                    <div className="col-span-2">
                      <Field label="Prénom" required>
                        <TextInput value={form.paxPrenom} onChange={v => set('paxPrenom', v)} placeholder="Prénom" required />
                      </Field>
                    </div>
                  </div>

                  <div className="mb-4">
                    <Field label="Nom" required>
                      <TextInput value={form.paxNom} onChange={v => set('paxNom', v)} placeholder="Nom de famille" required />
                    </Field>
                  </div>

                  <div className="grid grid-cols-2 gap-4 mb-4">
                    <Field label="Téléphone mobile" required>
                      <TextInput type="tel" value={form.paxTelephoneMobile} onChange={v => set('paxTelephoneMobile', v)} placeholder="+32 4xx xx xx xx" required />
                    </Field>
                    <Field label="Téléphone fixe">
                      <TextInput type="tel" value={form.paxTelephoneFixe} onChange={v => set('paxTelephoneFixe', v)} placeholder="+32 2xx xx xx xx" />
                    </Field>
                  </div>

                  <div className="mb-4">
                    <Field label="Langue préférée">
                      <Select value={form.paxLangue} onChange={v => set('paxLangue', v)} options={langOptions} />
                    </Field>
                  </div>

                  <div className="mb-6">
                    <Field label="Informations particulières">
                      <textarea
                        value={form.paxInfoParticuliere}
                        onChange={e => set('paxInfoParticuliere', e.target.value)}
                        placeholder="PMR, allergie, besoin particulier..."
                        rows={3}
                        className="w-full px-4 py-3 rounded-xl text-sm outline-none resize-none"
                        style={inputStyle}
                      />
                    </Field>
                  </div>

                  {/* Billing */}
                  <div className="pt-6 border-t" style={{ borderColor: '#ede9e0' }}>
                    <p className="text-xs font-semibold tracking-wide uppercase mb-4" style={{ color: '#9ca3af' }}>Facturation (optionnel)</p>
                    <div className="grid grid-cols-2 gap-4">
                      <Field label="Société">
                        <TextInput value={form.societeFacturation} onChange={v => set('societeFacturation', v)} placeholder="Nom de la société" />
                      </Field>
                      <Field label="Référence dossier">
                        <TextInput value={form.refClientDossier} onChange={v => set('refClientDossier', v)} placeholder="Réf. interne" />
                      </Field>
                    </div>
                  </div>
                </div>
              )}

              {/* ── STEP 3 : Contact ────────────────────────────────────── */}
              {step === 3 && (
                <div style={{ animation: 'fadeStepIn 0.35s ease both' }}>
                  <SectionTitle step={3} title="Contact & confirmation" subtitle="Qui recevra la confirmation de réservation" />

                  {/* Same as pax toggle */}
                  <div className="mb-6 p-4 rounded-xl flex items-center gap-4 cursor-pointer select-none" style={{ background: '#f8f5f0', border: '1.5px solid #e5e0d8' }} onClick={() => set('sameAsPax', !form.sameAsPax)}>
                    <div className="w-5 h-5 rounded flex items-center justify-center flex-shrink-0 transition-all duration-200" style={{ background: form.sameAsPax ? '#0f1f3d' : 'white', border: '2px solid ' + (form.sameAsPax ? '#0f1f3d' : '#d1d5db') }}>
                      {form.sameAsPax && <svg viewBox="0 0 24 24" fill="none" stroke="#c9a84c" strokeWidth="3" className="w-3 h-3"><polyline points="20 6 9 17 4 12"/></svg>}
                    </div>
                    <span className="text-sm font-medium" style={{ color: '#0f1f3d' }}>Même personne que le passager</span>
                  </div>

                  {!form.sameAsPax && (
                    <>
                      <div className="grid grid-cols-3 gap-4 mb-4">
                        <Field label="Civilité">
                          <Select value={form.contactCivilite} onChange={v => set('contactCivilite', v)} options={civiliteOptions} />
                        </Field>
                        <div className="col-span-2">
                          <Field label="Prénom">
                            <TextInput value={form.contactPrenom} onChange={v => set('contactPrenom', v)} placeholder="Prénom" />
                          </Field>
                        </div>
                      </div>
                      <div className="mb-4">
                        <Field label="Nom">
                          <TextInput value={form.contactNom} onChange={v => set('contactNom', v)} placeholder="Nom de famille" />
                        </Field>
                      </div>
                      <div className="mb-4">
                        <Field label="Langue préférée">
                          <Select value={form.contactLangue} onChange={v => set('contactLangue', v)} options={langOptions} />
                        </Field>
                      </div>
                    </>
                  )}

                  <div className="mb-4">
                    <Field label="Email" required>
                      <TextInput type="email" value={form.contactEmail} onChange={v => set('contactEmail', v)} placeholder="votre@email.com" required />
                    </Field>
                  </div>
                  <div className="mb-6">
                    <Field label="Téléphone contact">
                      <TextInput type="tel" value={form.contactTelephone} onChange={v => set('contactTelephone', v)} placeholder="+32 4xx xx xx xx" />
                    </Field>
                  </div>

                  <div className="mb-6">
                    <Field label="Informations complémentaires">
                      <textarea
                        value={form.infoComplementaire}
                        onChange={e => set('infoComplementaire', e.target.value)}
                        placeholder="Tout autre renseignement utile..."
                        rows={3}
                        className="w-full px-4 py-3 rounded-xl text-sm outline-none resize-none"
                        style={inputStyle}
                      />
                    </Field>
                  </div>

                  {/* Summary */}
                  <div className="rounded-xl p-5 mb-2" style={{ background: '#f8f5f0', border: '1px solid #ede9e0' }}>
                    <p className="text-xs font-semibold tracking-wide uppercase mb-3" style={{ color: '#9ca3af' }}>Récapitulatif</p>
                    <div className="flex flex-col gap-2 text-sm">
                      <div className="flex justify-between"><span style={{ color: '#9ca3af' }}>Date</span><span style={{ color: '#0f1f3d' }}>{form.dateDebut} {form.heureDebut}</span></div>
                      <div className="flex justify-between"><span style={{ color: '#9ca3af' }}>Départ</span><span className="max-w-[60%] text-right text-xs" style={{ color: '#0f1f3d' }}>{form.departAddress || '—'}</span></div>
                      <div className="flex justify-between"><span style={{ color: '#9ca3af' }}>Arrivée</span><span className="max-w-[60%] text-right text-xs" style={{ color: '#0f1f3d' }}>{form.arriveeAddress || '—'}</span></div>
                      <div className="flex justify-between"><span style={{ color: '#9ca3af' }}>Passagers</span><span style={{ color: '#0f1f3d' }}>{form.totalPax} pax · {form.totalBagage} bagage(s)</span></div>
                    </div>
                  </div>

                  {error && (
                    <div className="mt-4 px-4 py-3 rounded-xl text-sm" style={{ background: 'rgba(239,68,68,0.08)', color: '#dc2626', border: '1px solid rgba(239,68,68,0.2)' }}>
                      {error}
                    </div>
                  )}
                </div>
              )}

              {/* ── Navigation buttons ────────────────────────────────────── */}
              <div className="flex gap-3 mt-8 pt-6 border-t" style={{ borderColor: '#ede9e0' }}>
                {step > 1 && (
                  <button
                    type="button"
                    onClick={() => setStep(s => s - 1)}
                    className="flex-1 py-3.5 rounded-full text-sm font-semibold border transition-all duration-200 hover:bg-[#f8f5f0]"
                    style={{ borderColor: '#e5e0d8', color: '#6b7280' }}
                  >
                    ← Retour
                  </button>
                )}
                {step < totalSteps ? (
                  <button
                    type="button"
                    onClick={() => setStep(s => s + 1)}
                    className="flex-1 py-3.5 rounded-full text-sm font-semibold transition-all duration-300 hover:scale-[1.02] hover:shadow-lg"
                    style={{ background: '#0f1f3d', color: '#c9a84c' }}
                  >
                    Continuer →
                  </button>
                ) : (
                  <button
                    type="submit"
                    disabled={submitting}
                    className="flex-1 py-3.5 rounded-full text-sm font-semibold transition-all duration-300 hover:scale-[1.02] hover:shadow-lg disabled:opacity-60 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                    style={{ background: '#c9a84c', color: '#0f1f3d' }}
                  >
                    {submitting ? (
                      <><span className="w-4 h-4 border-2 border-[#0f1f3d]/30 border-t-[#0f1f3d] rounded-full animate-spin" /> Envoi en cours...</>
                    ) : (
                      'Confirmer la réservation'
                    )}
                  </button>
                )}
              </div>
            </form>
          )}
        </div>
      </div>

      <style>{`
        @keyframes slidePanel {
          from { transform: translateX(100%); opacity: 0; }
          to   { transform: translateX(0);    opacity: 1; }
        }
        @keyframes fadeStepIn {
          from { opacity: 0; transform: translateY(12px); }
          to   { opacity: 1; transform: translateY(0); }
        }
      `}</style>
    </div>
  )
}
