/* ============================================== */
/* Page Réservation — avec Supabase               */
/* ============================================== */

/* ── Supabase config ── */
const SUPABASE_URL = 'https://hqvqkgtsarunveewnkjg.supabase.co'
const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImhxdnFrZ3RzYXJ1bnZlZXdua2pnIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzY1MDc0MzIsImV4cCI6MjA5MjA4MzQzMn0.3_G9zNrMKBWKnMedT7dwLSfr6Nv9iYX7Qsc4sELBkB0'
const EDGE_FN = 'https://hqvqkgtsarunveewnkjg.supabase.co/functions/v1/send-confirmation'

async function sbFetch(path, opts = {}) {
  const res = await fetch(SUPABASE_URL + path, {
    ...opts,
    headers: {
      'apikey': SUPABASE_ANON_KEY,
      'Authorization': 'Bearer ' + SUPABASE_ANON_KEY,
      'Content-Type': 'application/json',
      'Prefer': 'return=minimal',
      ...(opts.headers || {}),
    },
  })
  const text = await res.text()
  try { return { data: JSON.parse(text), error: null } }
  catch { return { data: null, error: text } }
}

async function sbSelect(table, query = '') {
  return sbFetch(`/rest/v1/${table}?${query}`)
}

async function sbInsert(table, payload) {
  return sbFetch(`/rest/v1/${table}`, { method: 'POST', body: JSON.stringify(payload) })
}

/* ── Constantes ── */
const RATES = { particulier: 1000, pro: 900 }
const CAMION_ZONES = { Mbour: 5000, Saly: 7500, 'Nguékhokh': 10000, Somone: 10000, Autre: 0 }
const MIN_QTY  = 1
const MIN_DAYS_PART = 7
const MIN_DAYS_PRO  = 21

const MONTHS_FR = ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre']
const DAYS_FR   = ['Lu','Ma','Me','Je','Ve','Sa','Di']

function genRef() {
  const c = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  let r = 'IBD-'
  for (let i = 0; i < 6; i++) r += c[Math.floor(Math.random() * c.length)]
  return r
}

function fmt(d) {
  return d.toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', year: 'numeric' })
}

function fmtIso(d) {
  return d.toISOString().slice(0, 10)
}

function diffDays(a, b) {
  return Math.round((b.getTime() - a.getTime()) / 86400000) + 1
}

/* ══════════════════════════════════════════════
   PAGE PRINCIPALE
══════════════════════════════════════════════ */
function Reservation() {
  return (
    <Page>
      <ResHero />
      <PricingCards />
      <BookingForm />
    </Page>
  )
}

/* ---------- Hero ---------- */
function ResHero() {
  return (
    <section data-screen-label="Reservation Hero" style={{
      background: "var(--marin)", color: "#fff",
      position: "relative", overflow: "hidden",
    }}>
      <div style={{
        position: "absolute", inset: 0,
        background: "radial-gradient(ellipse 60% 70% at 90% 50%, rgba(232,98,18,0.18), transparent 60%)",
        pointerEvents: "none",
      }}/>
      <div className="wrap" style={{ position: "relative", padding: "84px 32px 48px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 22 }}>
          <span className="tag">Grilles tarifaires</span>
          <span className="hr-orange"/>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 56, alignItems: "end" }} className="ibd-section-head">
          <h1 className="h1" style={{ fontSize: "clamp(40px, 5.5vw, 80px)", color: "#fff" }}>
            Tarifs selon durée<br/>
            <span style={{ color: "var(--orange)" }}>et volume de location.</span>
          </h1>
          <div>
            <p style={{ fontSize: 17, color: "var(--acier)", lineHeight: 1.55, maxWidth: 420 }}>
              Tarif clair à la pièce. Minimum 7 jours. Acompte 30% à la réservation —
              solde avant ou à la livraison du matériel.
            </p>
            <div style={{ marginTop: 22, display: "flex", gap: 14, flexWrap: "wrap" }}>
              <a href="https://wa.me/221789230600" className="btn btn--ghost-white btn--sm">
                <span style={{ width:16,height:16,borderRadius:999,background:"#25D366",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:9,fontWeight:800,color:"#fff" }}>W</span>
                Devis WhatsApp
              </a>
            </div>
          </div>
        </div>
      </div>
    </section>
  )
}

/* ---------- Pricing cards ---------- */
function PricingCards() {
  const cards = [
    {
      tag: "PARTICULIER", name: "Particulier",
      desc: "Pour un projet personnel ou un petit chantier.",
      price: "1 000", unit: "XOF", per: "par étai / jour",
      available: true, featured: false,
      perks: ["Étais de coffrage standards","Livraison en J+1 sur Mbour & Saly","Fiche de remise signée","Support WhatsApp inclus"],
      action: "particulier",
    },
    {
      tag: "PRO / ENTREPRISE", name: "Pro / Entreprise",
      desc: "Pour les entreprises BTP, artisans et chantiers à rotation.",
      price: "900", unit: "XOF", per: "par étai / jour",
      available: true, featured: true,
      perks: ["Étais de coffrage standards","Facture pro, NINEA pris en compte","Compte chantier dédié","Prolongation possible"],
      action: "pro",
    },
    {
      tag: "OPTION", name: "Camion plateau",
      desc: "Livraison & reprise par notre camion plateau.",
      price: "Sur", unit: "devis", per: "selon zone & volume",
      available: true, featured: false,
      perks: ["Livraison Mbour, Saly, Nguékhokh, Somone","Chargement & déchargement inclus","Reprise programmée à date fixe","Devis par WhatsApp en 5 min"],
      action: "camion",
    },
  ]

  return (
    <section id="pricing" data-screen-label="Tarifs" style={{ background: "var(--marin)", color: "#fff", padding: "48px 0 96px" }}>
      <div className="wrap">
        <div className="ibd-pricing-grid" style={{ display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:20, overflow:"hidden" }}>
          {cards.map(c => (
            <article key={c.name} style={{
              background: c.action === "camion" ? "var(--marin-deep)" : c.featured ? "var(--marin-deep)" : "rgba(255,255,255,0.04)",
              backgroundImage: c.action === "camion" ? "url('assets/camion-plateau.jpg')" : "none",
              backgroundSize: c.action === "camion" ? "cover" : "unset",
              backgroundPosition: c.action === "camion" ? "center center" : "unset",
              backgroundRepeat: "no-repeat",
              border: "none",
              boxShadow: c.featured ? "inset 0 0 0 1px var(--orange)" : "inset 0 0 0 1px rgba(255,255,255,0.08)",
              padding: 32, position:"relative", overflow:"hidden",
              display:"flex", flexDirection:"column",
              boxSizing: "border-box",
              contain: "paint",
            }}
            onMouseEnter={e => { e.currentTarget.style.transform="translateY(-4px)"; e.currentTarget.style.overflow="hidden" }}
            onMouseLeave={e => { e.currentTarget.style.transform="translateY(0)"; e.currentTarget.style.overflow="hidden" }}
            >
              {c.action === "camion" && (
                <div style={{ position:"absolute",inset:0,background:"linear-gradient(135deg, rgba(10,22,40,0.95) 40%, rgba(10,22,40,0.55) 100%)",zIndex:0 }}/>
              )}
              {c.featured && (
                <span style={{ position:"absolute",top:0,right:0,background:"var(--orange)",color:"#fff",padding:"6px 12px",fontFamily:"var(--ff-mono)",fontSize:10,letterSpacing:2,textTransform:"uppercase",fontWeight:600,zIndex:2 }}>Plus choisi</span>
              )}
              {/* Badge disponibilité */}
              <div style={{ display:"flex",alignItems:"center",gap:6,marginBottom:20,position:"relative",zIndex:1 }}>
                <span style={{ width:7,height:7,borderRadius:"50%",background:"#22C55E",boxShadow:"0 0 6px #22C55E" }}/>
                <span style={{ fontSize:10,fontWeight:700,color:"#22C55E",textTransform:"uppercase",letterSpacing:1 }}>Disponible</span>
              </div>

              <span className="mono" style={{ fontSize:10,color:"var(--orange)",letterSpacing:2,position:"relative",zIndex:1 }}>{c.tag}</span>
              <h3 className="h2" style={{ fontSize:28,color:"#fff",marginTop:8,lineHeight:1,position:"relative",zIndex:1 }}>{c.name}</h3>
              <p style={{ fontSize:14,color:"var(--acier)",marginTop:10,lineHeight:1.5,flexGrow:1,position:"relative",zIndex:1 }}>{c.desc}</p>

              <div style={{ marginTop:24,paddingTop:20,borderTop:"1px solid #14294A",position:"relative",zIndex:1 }}>
                <span style={{ fontFamily:"var(--ff-title)",fontWeight:900,fontSize:42,color:"#fff" }}>{c.price}</span>
                <span style={{ fontSize:13,color:"var(--orange)",marginLeft:6,fontWeight:700 }}>{c.unit}</span>
                <div className="mono" style={{ fontSize:11,color:"var(--acier)",marginTop:4,letterSpacing:1 }}>{c.per}</div>
              </div>

              <ul style={{ marginTop:20,display:"flex",flexDirection:"column",gap:8,listStyle:"none",padding:0,position:"relative",zIndex:1 }}>
                {c.perks.map(p => (
                  <li key={p} style={{ display:"flex",gap:10,fontSize:13,color:"var(--acier)" }}>
                    <span style={{ color:"var(--orange)",flexShrink:0,marginTop:1 }}>→</span>
                    {p}
                  </li>
                ))}
              </ul>

              <a href={c.action==="camion" ? "https://wa.me/221789230600" : "#booking-form"}
                onClick={c.action!=="camion" ? () => { window.__ibdBookingProfile=c.action; setTimeout(()=>{ const el=document.getElementById("booking-form"); if(el){ const y=el.getBoundingClientRect().top+window.scrollY-100; window.scrollTo({top:y,behavior:"smooth"}); }},50) } : undefined}
                className={`btn ${c.featured?"btn--orange":"btn--ghost-white"} btn--sm`}
                style={{ marginTop:24,justifyContent:"center",position:"relative",zIndex:1 }}>
                {c.action==="camion" ? "Demander un devis" : `Réserver ${c.name}`}
              </a>
            </article>
          ))}
        </div>

        {/* Conditions */}
        <div style={{ marginTop:32,padding:"24px 28px",background:"var(--marin-deep)",border:"1px solid #14294A",display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(200px,1fr))",gap:24 }} className="ibd-conditions-grid">
          <div>
            <span className="mono" style={{ fontSize:10,color:"var(--orange)",letterSpacing:2 }}>PAIEMENT</span>
            <p style={{ marginTop:8,fontSize:13,color:"var(--acier)",lineHeight:1.55 }}>
              Acompte 30% à la réservation. Solde avant ou à la livraison. Wave, Orange Money ou virement.
            </p>
          </div>
          <div>
            <span className="mono" style={{ fontSize:10,color:"var(--orange)",letterSpacing:2 }}>DURÉE</span>
            <p style={{ marginTop:8,fontSize:13,color:"var(--acier)",lineHeight:1.55 }}>
              Particulier : minimum 7 jours. Pro / Entreprise : minimum 21 jours.
            </p>
          </div>
        </div>
      </div>
    </section>
  )
}

/* ══════════════════════════════════════════════
   FORMULAIRE DE RÉSERVATION avec Supabase
══════════════════════════════════════════════ */
function BookingForm() {
  const [step, setStep] = React.useState(1)
  const [stock, setStock] = React.useState(1500)
  const [stockLoading, setStockLoading] = React.useState(true)

  // Step 1 — dates & matériel
  const [profil, setProfil] = React.useState(window.__ibdBookingProfile || 'particulier')
  const [calMonth, setCalMonth] = React.useState(new Date())
  const [startDate, setStartDate] = React.useState(null)
  const [endDate, setEndDate] = React.useState(null)
  const [qty, setQty] = React.useState(10)
  const [avecCamion, setAvecCamion] = React.useState(false)
  const [zone, setZone] = React.useState('Mbour')

  // Step 2 — contact
  const [prenom, setPrenom] = React.useState('')
  const [nom, setNom] = React.useState('')
  const [email, setEmail] = React.useState('')
  const [telephone, setTelephone] = React.useState('')
  const [adresse, setAdresse] = React.useState('')
  const [notes, setNotes] = React.useState('')
  const [entreprise, setEntreprise] = React.useState('')

  // Step 3 — paiement
  const [payMode, setPayMode] = React.useState('wave')
  const [cgv, setCgv] = React.useState(false)
  const [submitting, setSubmitting] = React.useState(false)
  const [submitError, setSubmitError] = React.useState('')
  const [successRef, setSuccessRef] = React.useState('')

  React.useEffect(() => {
    if (window.__ibdBookingProfile) setProfil(window.__ibdBookingProfile)
  }, [])

  // Ajuster durée mini selon profil
  React.useEffect(() => {
    const minDays = profil === 'pro' ? MIN_DAYS_PRO : MIN_DAYS_PART
    if (days > 0 && days < minDays && startDate && endDate) {
      const newEnd = new Date(startDate)
      newEnd.setDate(newEnd.getDate() + minDays - 1)
      setEndDate(newEnd)
    }
  }, [profil])

  // Charger stock depuis Supabase
  React.useEffect(() => {
    async function loadStock() {
      setStockLoading(true)
      try {
        const { data: sdArr } = await sbSelect('Stock', 'limit=1')
        const sd = sdArr?.[0]
        const { data: rd } = await sbFetch('/rest/v1/Reservations?select=quantite&statut=in.(en_attente,confirmee,en_cours)')
        const totalStock = sd?.total_etais ?? sd?.Total_etais ?? sd?.total ?? sd?.stock ?? 1500
        const reserved = (rd ?? []).reduce((s, r) => s + (r.quantite ?? 0), 0)
        setStock(Math.max(0, totalStock - reserved))
      } catch(e) {
        console.error('Stock load error', e)
      }
      setStockLoading(false)
    }
    loadStock()
  }, [])

  const today = new Date(); today.setHours(0,0,0,0)
  const minDays = profil === 'pro' ? MIN_DAYS_PRO : MIN_DAYS_PART
  const days = startDate && endDate ? Math.max(diffDays(startDate, endDate), minDays) : 0
  const rate = RATES[profil] || 1000
  const etaisTotal = qty * rate * days
  const camionTotal = avecCamion ? (zone === 'Autre' ? 0 : (CAMION_ZONES[zone] || 5000)) : 0
  const total = etaisTotal + camionTotal
  const acompte = Math.round(total * 0.3)
  const solde = total - acompte

  // Calendrier
  function getMonthGrid(d) {
    const year = d.getFullYear(), month = d.getMonth()
    const firstDow = (new Date(year, month, 1).getDay() + 6) % 7
    const totalDays = new Date(year, month + 1, 0).getDate()
    return { firstDow, totalDays, year, month }
  }

  function handleDayClick(year, month, day) {
    const clicked = new Date(year, month, day)
    if (clicked < today) return
    if (!startDate || (startDate && endDate)) {
      setStartDate(clicked); setEndDate(null)
    } else if (clicked > startDate) {
      setEndDate(clicked)
    } else {
      setStartDate(clicked); setEndDate(null)
    }
  }

  function dayState(year, month, day) {
    const d = new Date(year, month, day)
    if (d < today) return 'past'
    if (startDate && d.toDateString() === startDate.toDateString()) return 'start'
    if (endDate && d.toDateString() === endDate.toDateString()) return 'end'
    if (startDate && endDate && d > startDate && d < endDate) return 'range'
    if (d.toDateString() === today.toDateString()) return 'today'
    return 'normal'
  }

  const { firstDow, totalDays: daysInMonth, year: calYear, month: calMonthIdx } = getMonthGrid(calMonth)

  const PAYDUNYA_FN = `https://hqvqkgtsarunveewnkjg.supabase.co/functions/v1/paydunya-checkout`

  // Soumission vers Paydunya
  async function handleSubmit() {
    if (!cgv) { setSubmitError("Acceptez les conditions de location."); return }
    if (!startDate || !endDate) { setSubmitError("Sélectionnez vos dates."); return }
    setSubmitting(true); setSubmitError('')
    const reference = genRef()
    try {
      const res = await fetch(PAYDUNYA_FN, {
        method: 'POST',
        headers: { 'Content-Type':'application/json', 'Authorization':'Bearer '+SUPABASE_ANON_KEY },
        body: JSON.stringify({
          reference,
          prenom, nom, email, telephone, adresse, notes,
          quantite: qty,
          date_debut: fmtIso(startDate),
          date_fin: fmtIso(endDate),
          type_client: profil,
          avec_grue: avecCamion,
          mode_paiement: payMode,
          total, acompte,
        }),
      })
      const data = await res.json()
      if (!data.success || !data.invoice_url) {
        setSubmitError("Erreur lors de la création du paiement. Veuillez réessayer.")
        setSubmitting(false)
        return
      }
      // Rediriger vers la page de paiement Paydunya
      window.location.href = data.invoice_url
    } catch(e) {
      setSubmitError("Erreur réseau. Veuillez réessayer.")
      setSubmitting(false)
    }
  }

  // Succès
  if (successRef) {
    return (
      <section id="booking-form" style={{ background:"#fff", padding:"80px 0" }}>
        <div className="wrap">
          <div style={{ maxWidth:640, margin:"0 auto" }}>
            <div style={{ width:64,height:64,background:"var(--orange)",display:"inline-flex",alignItems:"center",justifyContent:"center",color:"#fff",fontSize:32,fontFamily:"var(--ff-title)",fontWeight:900 }}>✓</div>
            <h3 className="h1" style={{ fontSize:48,marginTop:18,color:"var(--marin)" }}>Réservation envoyée.</h3>
            <p style={{ marginTop:14,fontSize:16,color:"var(--noir)",lineHeight:1.55,maxWidth:540 }}>
              Merci {prenom} — confirmation sous 1h ouvrée par WhatsApp et email.
              Référence : <strong className="mono" style={{ color:"var(--orange)" }}>{successRef}</strong>
            </p>
            <div style={{ marginTop:20,padding:"16px 20px",background:"rgba(232,98,18,0.08)",border:"1px solid rgba(232,98,18,0.2)",fontSize:14,color:"var(--marin)",lineHeight:1.55 }}>
              <strong>Prochaine étape :</strong> Réglez l'acompte de <strong style={{ color:"var(--orange)" }}>{acompte.toLocaleString('fr-FR')} XOF</strong> par Wave, Orange Money ou virement pour confirmer définitivement votre réservation.
            </div>
            <div style={{ marginTop:28,display:"flex",gap:12,flexWrap:"wrap" }}>
              <a href="https://wa.me/221789230600" className="btn btn--orange">
                <span style={{ width:16,height:16,borderRadius:999,background:"#25D366",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:9,fontWeight:800,color:"#fff" }}>W</span>
                Confirmer par WhatsApp
              </a>
              <button onClick={() => { setSuccessRef(''); setStep(1); setStartDate(null); setEndDate(null); setQty(10); setCgv(false) }} className="btn btn--ghost-marin">
                Nouvelle réservation
              </button>
            </div>
          </div>
        </div>
      </section>
    )
  }

  return (
    <section id="booking-form" data-screen-label="Formulaire réservation" style={{ background:"#fff", padding:"80px 0" }}>
      <div className="wrap">
        <div style={{ display:"grid", gap:48, alignItems:"start" }} className="ibd-booking-grid">

          {/* Formulaire gauche */}
          <div>
            {/* Steps */}
            <div style={{ display:"flex",gap:0,marginBottom:40,borderBottom:"1px solid var(--acier-soft)" }}>
              {[{n:1,t:"Matériel & Dates"},{n:2,t:"Coordonnées"},{n:3,t:"Paiement"}].map(s => (
                <button key={s.n} onClick={() => s.n < step && setStep(s.n)}
                  style={{ padding:"14px 20px",border:"none",background:"none",borderBottom:step===s.n?"2px solid var(--orange)":"2px solid transparent",fontFamily:"var(--ff-title)",fontWeight:700,fontSize:13,textTransform:"uppercase",letterSpacing:1,color:step===s.n?"var(--orange)":step>s.n?"var(--marin)":"var(--acier)",cursor:s.n<step?"pointer":"default" }}>
                  <span className="mono" style={{ fontSize:10,marginRight:8,opacity:.6 }}>{s.n}</span>{s.t}
                </button>
              ))}
            </div>

            {/* ── STEP 1 ── */}
            {step === 1 && (
              <div>
                {/* Profil */}
                <FieldLabel n="01">Profil</FieldLabel>
                <div style={{ display:"grid",gridTemplateColumns:"1fr 1fr",gap:10,marginBottom:24 }}>
                  {[{v:"particulier",t:"Particulier",h:"1 000 XOF / étai / j — min. 7 jours"},{v:"pro",t:"Pro / Entreprise",h:"900 XOF / étai / j — min. 21 jours"}].map(o => {
                    const active = profil === o.v
                    return (
                      <button key={o.v} onClick={() => setProfil(o.v)}
                        style={{ padding:"14px 16px",textAlign:"left",border:active?"2px solid var(--orange)":"1px solid var(--acier)",background:active?"var(--fond-warm)":"#fff",transition:"all .15s" }}>
                        <div style={{ fontFamily:"var(--ff-title)",fontWeight:700,fontSize:17,textTransform:"uppercase",color:active?"var(--orange)":"var(--marin)" }}>{o.t}</div>
                        <div className="mono" style={{ fontSize:11,color:"#7E8B96",marginTop:4,letterSpacing:1 }}>{o.h}</div>
                      </button>
                    )
                  })}
                </div>

                {/* Étai */}
                <div style={{ padding:"16px 20px",background:"var(--fond-warm)",border:"1px solid var(--acier-soft)",display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:24 }}>
                  <div>
                    <div style={{ fontFamily:"var(--ff-title)",fontWeight:700,fontSize:16,color:"var(--marin)",textTransform:"uppercase" }}>Étai de coffrage standard</div>
                    <div className="mono" style={{ fontSize:11,color:"var(--acier)",marginTop:3,letterSpacing:1 }}>Hauteur réglable · Charge admissible certifiée</div>
                  </div>
                  <div style={{ display:"flex",alignItems:"center",gap:6 }}>
                    <span style={{ width:7,height:7,borderRadius:"50%",background:"#22C55E",boxShadow:"0 0 6px #22C55E" }}/>
                    <span style={{ fontSize:10,fontWeight:700,color:"#22C55E",textTransform:"uppercase",letterSpacing:1 }}>
                      {stockLoading ? "Chargement..." : `${stock.toLocaleString()} disponibles`}
                    </span>
                  </div>
                </div>

                {/* Calendrier */}
                <FieldLabel n="02">Dates de location</FieldLabel>
                <div style={{ background:"var(--marin)",borderRadius:4,padding:"20px",marginBottom:16,userSelect:"none" }}>
                  <div style={{ display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16 }}>
                    <button onClick={() => setCalMonth(new Date(calYear, calMonthIdx-1))}
                      style={{ width:36,height:36,background:"rgba(255,255,255,.1)",border:"none",color:"#fff",fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center" }}>‹</button>
                    <span style={{ fontFamily:"var(--ff-title)",fontWeight:700,color:"#fff",fontSize:14,textTransform:"uppercase",letterSpacing:2 }}>{MONTHS_FR[calMonthIdx]} {calYear}</span>
                    <button onClick={() => setCalMonth(new Date(calYear, calMonthIdx+1))}
                      style={{ width:36,height:36,background:"rgba(255,255,255,.1)",border:"none",color:"#fff",fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center" }}>›</button>
                  </div>
                  <div style={{ display:"grid",gridTemplateColumns:"repeat(7,1fr)",gap:2,marginBottom:8 }}>
                    {DAYS_FR.map(d => <div key={d} style={{ textAlign:"center",fontSize:10,color:"var(--acier)",fontWeight:600,padding:"4px 0" }}>{d}</div>)}
                  </div>
                  <div style={{ display:"grid",gridTemplateColumns:"repeat(7,1fr)",gap:2 }}>
                    {Array.from({length:firstDow}).map((_,i) => <div key={"e"+i}/>)}
                    {Array.from({length:daysInMonth}).map((_,i) => {
                      const day = i+1
                      const state = dayState(calYear, calMonthIdx, day)
                      const styles = {
                        past: { color:"rgba(176,190,202,.3)", cursor:"not-allowed" },
                        start: { background:"var(--orange)",color:"#fff",fontWeight:700 },
                        end: { background:"var(--orange)",color:"#fff",fontWeight:700 },
                        range: { background:"rgba(232,98,18,.25)",color:"rgba(255,255,255,.8)" },
                        today: { color:"var(--orange)",fontWeight:700 },
                        normal: { color:"#fff" },
                      }
                      return (
                        <button key={day} disabled={state==="past"}
                          onClick={() => handleDayClick(calYear, calMonthIdx, day)}
                          style={{ height:36,border:"none",background:"none",cursor:state==="past"?"not-allowed":"pointer",fontSize:12,display:"flex",alignItems:"center",justifyContent:"center",transition:"background .15s",...styles[state] }}>
                          {day}
                        </button>
                      )
                    })}
                  </div>
                </div>
                {startDate && endDate && (
                  <div style={{ fontSize:13,color:"var(--marin)",marginBottom:16,display:"flex",gap:16,flexWrap:"wrap" }}>
                    <span>Du <strong>{fmt(startDate)}</strong></span>
                    <span>au <strong>{fmt(endDate)}</strong></span>
                    <span style={{ color:"var(--orange)",fontWeight:700 }}>{days} jours</span>
                    {days < minDays && <span style={{ color:"#e53e3e",fontSize:12 }}>(minimum {minDays} jours — ajusté automatiquement)</span>}
                  </div>
                )}

                {/* Quantité */}
                <FieldLabel n="03">Quantité</FieldLabel>
                <div style={{ display:"flex",alignItems:"center",gap:12,marginBottom:8 }}>
                  <button onClick={() => setQty(q => Math.max(MIN_QTY, q-1))}
                    style={{ width:40,height:40,border:"1px solid var(--acier)",background:"#fff",fontSize:20,cursor:"pointer",fontWeight:700,color:"var(--marin)" }}>−</button>
                  <input type="number" min={MIN_QTY} max={stock} value={qty}
                    onChange={e => {
                      const v = parseInt(e.target.value)
                      if (!isNaN(v)) setQty(Math.max(MIN_QTY, Math.min(stock, v)))
                      else if (e.target.value === '') setQty('')
                    }}
                    onBlur={e => {
                      const v = parseInt(e.target.value)
                      setQty(isNaN(v) || v < MIN_QTY ? MIN_QTY : Math.min(stock, v))
                    }}
                    style={{ width:80,textAlign:"center",border:"1px solid var(--acier-soft)",padding:"10px 0",fontSize:18,fontFamily:"var(--ff-title)",fontWeight:700,color:"var(--marin)" }}/>
                  <button onClick={() => setQty(q => Math.min(stock, q+1))}
                    style={{ width:40,height:40,border:"1px solid var(--acier)",background:"#fff",fontSize:20,cursor:"pointer",fontWeight:700,color:"var(--marin)" }}>+</button>
                  <span style={{ fontSize:14,color:"var(--acier)" }}>étais</span>
                </div>
                <div style={{ fontSize:12,color:"var(--acier)",marginBottom:24 }}>Stock disponible : <strong style={{ color:"var(--orange)" }}>{stock.toLocaleString()}</strong> étais</div>

                {/* Camion */}
                <FieldLabel n="04">Livraison</FieldLabel>
                <label style={{ display:"flex",alignItems:"flex-start",gap:14,padding:"16px 18px",border:"1px solid var(--acier-soft)",cursor:"pointer",background:avecCamion?"var(--fond-warm)":"#fff",marginBottom:avecCamion?12:0 }}>
                  <input type="checkbox" checked={avecCamion} onChange={e => setAvecCamion(e.target.checked)}
                    style={{ marginTop:4,accentColor:"var(--orange)",width:18,height:18 }}/>
                  <div>
                    <div style={{ fontFamily:"var(--ff-title)",fontWeight:700,fontSize:16,color:"var(--marin)",textTransform:"uppercase" }}>Camion plateau IBD</div>
                    <div style={{ fontSize:13,color:"var(--acier)",marginTop:3 }}>Livraison & reprise sur chantier · Tarif selon zone</div>
                  </div>
                </label>
                {avecCamion && (
                  <div style={{ display:"grid",gridTemplateColumns:"repeat(2,1fr)",gap:8,marginBottom:16 }}>
                    {Object.entries(CAMION_ZONES).map(([z, prix]) => {
                      const active = zone===z
                      return (
                        <button key={z} onClick={() => setZone(z)}
                          style={{ padding:"10px 14px",textAlign:"left",border:active?"2px solid var(--orange)":"1px solid var(--acier)",background:active?"var(--fond-warm)":"#fff",transition:"all .15s" }}>
                          <div style={{ fontFamily:"var(--ff-title)",fontWeight:700,fontSize:15,textTransform:"uppercase",color:active?"var(--orange)":"var(--marin)" }}>{z}</div>
                          <div className="mono" style={{ fontSize:10,color:"#7E8B96",marginTop:2,letterSpacing:1 }}>
                            {z === "Autre" ? "Sur devis" : `${prix.toLocaleString('fr-FR')} XOF`}
                          </div>
                        </button>
                      )
                    })}
                  </div>
                )}

                <button onClick={() => {
                  if (!startDate || !endDate) { alert('Sélectionnez vos dates.'); return }
                  if (qty < MIN_QTY) { alert(`Minimum ${MIN_QTY} étai.`); return }
                  if (qty > stock) { alert('Quantité supérieure au stock disponible.'); return }
                  setStep(2)
                  setTimeout(()=>{ const el=document.getElementById("booking-form"); if(el){ const y=el.getBoundingClientRect().top+window.scrollY-100; window.scrollTo({top:y,behavior:"smooth"}); }},50)
                }} className="btn btn--orange" style={{ marginTop:24,width:"100%",justifyContent:"center" }}>
                  Continuer <span className="arr">→</span>
                </button>
              </div>
            )}

            {/* ── STEP 2 ── */}
            {step === 2 && (
              <div>
                <FieldLabel n="01">Vos coordonnées</FieldLabel>
                <div style={{ display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(140px,1fr))",gap:12,marginBottom:12 }}>
                  <input type="text" placeholder="Prénom *" value={prenom} onChange={e=>setPrenom(e.target.value)}
                    style={{ border:"1px solid var(--acier-soft)",padding:"14px 16px",fontSize:15,fontFamily:"var(--ff-body)",color:"var(--marin)",outline:"none" }}/>
                  <input type="text" placeholder="Nom *" value={nom} onChange={e=>setNom(e.target.value)}
                    style={{ border:"1px solid var(--acier-soft)",padding:"14px 16px",fontSize:15,fontFamily:"var(--ff-body)",color:"var(--marin)",outline:"none" }}/>
                </div>
                <input type="email" placeholder="Email *" value={email} onChange={e=>setEmail(e.target.value)}
                  style={{ width:"100%",border:"1px solid var(--acier-soft)",padding:"14px 16px",fontSize:15,fontFamily:"var(--ff-body)",color:"var(--marin)",outline:"none",marginBottom:12 }}/>
                <input type="tel" placeholder="Téléphone / WhatsApp *" value={telephone} onChange={e=>setTelephone(e.target.value)}
                  style={{ width:"100%",border:"1px solid var(--acier-soft)",padding:"14px 16px",fontSize:15,fontFamily:"var(--ff-body)",color:"var(--marin)",outline:"none",marginBottom:12 }}/>
                <input type="text" placeholder="Adresse du chantier *" value={adresse} onChange={e=>setAdresse(e.target.value)}
                  style={{ width:"100%",border:"1px solid var(--acier-soft)",padding:"14px 16px",fontSize:15,fontFamily:"var(--ff-body)",color:"var(--marin)",outline:"none",marginBottom:12 }}/>
                {profil === 'pro' && (
                  <input type="text" placeholder="Entreprise" value={entreprise} onChange={e=>setEntreprise(e.target.value)}
                    style={{ width:"100%",border:"1px solid var(--acier-soft)",padding:"14px 16px",fontSize:15,fontFamily:"var(--ff-body)",color:"var(--marin)",outline:"none",marginBottom:12 }}/>
                )}
                <textarea placeholder="Notes, instructions particulières..." value={notes} onChange={e=>setNotes(e.target.value)} rows={3}
                  style={{ width:"100%",border:"1px solid var(--acier-soft)",padding:"14px 16px",fontSize:15,fontFamily:"var(--ff-body)",color:"var(--marin)",outline:"none",resize:"vertical",marginBottom:24 }}/>

                <div style={{ display:"flex",gap:12 }}>
                  <button onClick={() => { setStep(1); setTimeout(()=>{ const el=document.getElementById("booking-form"); if(el){ const y=el.getBoundingClientRect().top+window.scrollY-100; window.scrollTo({top:y,behavior:"smooth"}); }},50) }} className="btn btn--ghost-marin">← Retour</button>
                  <button onClick={() => {
                    if (!prenom||!nom||!email||!telephone||!adresse) { alert('Remplissez tous les champs obligatoires.'); return }
                    setStep(3)
                    setTimeout(()=>{ const el=document.getElementById("booking-form"); if(el){ const y=el.getBoundingClientRect().top+window.scrollY-100; window.scrollTo({top:y,behavior:"smooth"}); }},50)
                  }} className="btn btn--orange" style={{ flex:1,justifyContent:"center" }}>Continuer <span className="arr">→</span></button>
                </div>
              </div>
            )}

            {/* ── STEP 3 ── */}
            {step === 3 && (
              <div>
                <FieldLabel n="01">Mode de paiement</FieldLabel>
                <div style={{ display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(120px,1fr))",gap:10,marginBottom:24 }}>
                  {[{v:"wave",t:"📱 Wave"},{v:"om",t:"🟠 Orange Money"},{v:"vir",t:"🏦 Virement"}].map(o => {
                    const active = payMode===o.v
                    return (
                      <button key={o.v} onClick={() => setPayMode(o.v)}
                        style={{ padding:"12px 14px",textAlign:"center",border:active?"2px solid var(--orange)":"1px solid var(--acier)",background:active?"var(--fond-warm)":"#fff",fontFamily:"var(--ff-title)",fontWeight:700,fontSize:14,color:active?"var(--orange)":"var(--marin)",transition:"all .15s" }}>
                        {o.t}
                      </button>
                    )
                  })}
                </div>

                <div style={{ background:"var(--fond-warm)",padding:"16px 20px",border:"1px solid var(--acier-soft)",fontSize:14,color:"var(--marin)",lineHeight:1.6,marginBottom:24 }}>
                  {payMode==="wave" && <span>📱 <strong>Wave :</strong> Envoyez l'acompte au <strong>+221 78 923 06 00</strong><br/>Référence : votre nom + date de début</span>}
                  {payMode==="om"   && <span>🟠 <strong>Orange Money :</strong> Envoyez l'acompte au <strong>+221 78 923 06 00</strong><br/>Référence : votre nom + date de début</span>}
                  {payMode==="vir"  && <span>🏦 <strong>Virement CBAO Sénégal</strong><br/>Référence : votre nom + date de début</span>}
                </div>

                {/* Récap paiement */}
                <FieldLabel n="02">Récapitulatif</FieldLabel>
                <div style={{ background:"var(--fond-warm)",padding:"20px 22px",border:"1px solid var(--acier-soft)",display:"grid",gridTemplateColumns:"1fr 1fr",gap:16,marginBottom:16 }}>
                  <div>
                    <span className="label" style={{ color:"var(--acier)" }}>Acompte 30% — à la réservation</span>
                    <div className="h3" style={{ fontSize:22,color:"var(--orange)",marginTop:4 }}>{acompte.toLocaleString('fr-FR')} XOF</div>
                  </div>
                  <div>
                    <span className="label" style={{ color:"var(--acier)" }}>Solde — avant / à la livraison</span>
                    <div className="h3" style={{ fontSize:22,color:"var(--marin)",marginTop:4 }}>{solde.toLocaleString('fr-FR')} XOF</div>
                  </div>
                </div>

                <label style={{ display:"flex",alignItems:"flex-start",gap:14,padding:"16px 18px",border:"1px solid var(--acier-soft)",cursor:"pointer",background:cgv?"var(--fond-warm)":"#fff",marginBottom:24 }}>
                  <input type="checkbox" checked={cgv} onChange={e=>setCgv(e.target.checked)}
                    style={{ marginTop:4,accentColor:"var(--orange)",width:18,height:18 }}/>
                  <span style={{ fontSize:14,color:"var(--marin)",lineHeight:1.55 }}>
                    Je confirme avoir lu et accepté les <a href="#/faq" style={{ color:"var(--orange)",fontWeight:600 }}>conditions de location</a>.
                    Acompte 30% obligatoire. Solde avant ou à la livraison.
                  </span>
                </label>

                {submitError && <p style={{ color:"#e53e3e",fontSize:13,marginBottom:16 }}>{submitError}</p>}

                <div style={{ display:"flex",gap:12 }}>
                  <button onClick={() => { setStep(2); setTimeout(()=>{ const el=document.getElementById("booking-form"); if(el){ const y=el.getBoundingClientRect().top+window.scrollY-100; window.scrollTo({top:y,behavior:"smooth"}); }},50) }} className="btn btn--ghost-marin">← Retour</button>
                  <button onClick={handleSubmit} disabled={submitting||!cgv}
                    className="btn btn--orange"
                    style={{ flex:1,justifyContent:"center",opacity:(!cgv||submitting)?.45:1 }}>
                    {submitting ? "Création du paiement…" : "Payer l'acompte →"}
                  </button>
                </div>
              </div>
            )}
          </div>

          {/* Résumé droite */}
          <aside style={{ position:"sticky",top:100,background:"var(--marin)",color:"#fff",padding:32,border:"1px solid #14294A" }}>
            <span className="tag">Devis en direct</span>
            <div style={{ marginTop:24,display:"flex",flexDirection:"column",gap:12 }}>
              {[
                ["Profil",    profil==="pro"?"Pro":"Particulier"],
                ["Matériel",  "Étai standard"],
                ["Quantité",  `${qty} étais`],
                ["Durée",     days>0?`${days} jours`:"—"],
                ["Tarif",     `${rate.toLocaleString()} XOF / étai / j`],
                ["Livraison", avecCamion ? `Camion · ${zone}${zone==='Autre'?' (sur devis)':''}` : "Retrait dépôt"],
              ].map(([k,v]) => (
                <div key={k} style={{ display:"flex",justifyContent:"space-between",fontSize:14,gap:12 }}>
                  <span style={{ color:"var(--acier)" }}>{k}</span>
                  <span style={{ color:"#fff",fontWeight:600,textAlign:"right" }}>{v}</span>
                </div>
              ))}
            </div>
            <div style={{ marginTop:24,paddingTop:20,borderTop:"2px solid var(--orange)" }}>
              <div style={{ display:"flex",justifyContent:"space-between",alignItems:"baseline" }}>
                <span className="label" style={{ color:"var(--acier)" }}>Total HT</span>
                <span className="h1" style={{ fontSize:36,color:"#fff" }}>
                  {total.toLocaleString('fr-FR')} <span style={{ fontSize:14,color:"var(--orange)" }}>XOF</span>
                </span>
              </div>
              <div style={{ marginTop:12,display:"flex",flexDirection:"column",gap:6 }}>
                <div style={{ display:"flex",justifyContent:"space-between",fontSize:13,color:"var(--acier)" }}>
                  <span>Acompte 30%</span>
                  <span className="mono" style={{ fontWeight:700,color:"var(--orange)" }}>{acompte.toLocaleString('fr-FR')} XOF</span>
                </div>
                <div style={{ display:"flex",justifyContent:"space-between",fontSize:13,color:"var(--acier)" }}>
                  <span>Solde</span>
                  <span className="mono" style={{ fontWeight:700,color:"#fff" }}>{solde.toLocaleString('fr-FR')} XOF</span>
                </div>
              </div>
            </div>
            <p style={{ marginTop:16,fontSize:12,color:"var(--acier)",lineHeight:1.55 }}>
              Devis estimatif. Confirmé par contrat après réception de l'acompte.
            </p>
          </aside>
        </div>
      </div>
    </section>
  )
}

/* ---------- Primitives ---------- */
function FieldLabel({ n, mt, children }) {
  return (
    <div style={{ marginTop:mt?28:0,marginBottom:10,display:"flex",alignItems:"center",gap:10 }}>
      <span className="mono" style={{ fontSize:10,color:"var(--orange)",letterSpacing:2 }}>{n}</span>
      <span className="label" style={{ color:"var(--marin)" }}>{children}</span>
    </div>
  )
}

window.Reservation = Reservation
