/* ============================================================
   Rent-a-Car — Mobility & Fleet service page
   ============================================================ */
/* date helper — YYYY-MM-DD with day offset */
function nigerToday(offsetDays = 0) {
  const d = new Date(Date.now() + offsetDays * 86400000);
  return d.toISOString().slice(0, 10);
}
const FLEET_CATS = [
  { k: "all", label: { en: "All", fr: "Tous" } },
  { k: "sedan", label: { en: "Sedans", fr: "Berlines" } },
  { k: "suv", label: { en: "SUVs & 4x4", fr: "SUV & 4x4" } },
  { k: "van", label: { en: "Vans", fr: "Vans" } },
  { k: "pickup", label: { en: "Pickups", fr: "Pickups" } },
];

/* Fleet now loads live from Supabase (see gg-supabase.js).
   window.GG_DATA.fleet is filled before React mounts. */
const FLEET = (window.GG_DATA && window.GG_DATA.fleet) || [];

/* Local fleet images — exact match per model */
/* Fleet images: local fallback merged live with Supabase paths via Proxy */
const RAC_VEHICLE_PHOTOS_LOCAL = {
  "Toyota Corolla":      "assets/fleet/toyota-corolla.jpg",
  "Hyundai Elantra":     "assets/fleet/elantra.jpg",
  "Toyota RAV4":         "assets/fleet/toyota-rav4.webp",
  "Toyota Land Cruiser": "assets/fleet/land-cruiser.jpg",
  "Mercedes Sprinter":   "assets/fleet/mercedes-sprinter.png",
  "Toyota HiAce":        "assets/fleet/toyota-hiace.webp",
  "Toyota Hilux D/Cab":  "assets/fleet/toyota-hilux.jpg",
  "Ford Ranger":         "assets/fleet/ford-ranger.jpg",
  "Kia Sportage":        "assets/fleet/kia-sportage.jpg",
  "Toyota Prado":        "assets/fleet/toyota-prado.jpg",
  "Mitsubishi L200":     "assets/fleet/mitsubishi-triton.jpg",
  "Toyota Coaster":      "assets/fleet/toyota-coaster.jpg",
};
const RAC_VEHICLE_PHOTOS = new Proxy(RAC_VEHICLE_PHOTOS_LOCAL, {
  get(local, key) {
    const live = (window.GG_DATA && window.GG_DATA.fleetImgs) || {};
    return live[key] || local[key];
  },
});
function RACImg({ name, cover }) {
  const [err, setErr] = useState(false);
  const src = RAC_VEHICLE_PHOTOS[name] || "assets/fleet/land-cruiser.jpg";
  if (err) return <div style={{ width: "100%", height: "100%", background: "var(--paper-0)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="car" size={32} style={{ color: "var(--muted)" }} /></div>;
  return (
    <div style={{ width: "100%", height: "100%", background: "var(--paper-0)", display: "flex", alignItems: "center", justifyContent: "center", padding: cover ? "2%" : "4% 8%" }}>
      <img src={src} alt={name} style={{ width: "100%", height: "100%", objectFit: "contain", mixBlendMode: "multiply" }} onError={() => setErr(true)} loading="lazy" />
    </div>
  );
}
/* ---------- Google-Maps-style pick-up autocomplete ---------- */
const NIGER_PLACES = [
  { main: "A\u00e9roport International Diori Hamani", sec: "Niamey · Airport pick-up", branch: true },
  { main: "Guero\u2019s Group \u2014 Niamey Centre", sec: "Bd de l\u2019Ind\u00e9pendance, Niamey", branch: true },
  { main: "Guero\u2019s Group \u2014 Rive Droite", sec: "Route de Torodi, Niamey", branch: true },
  { main: "Plateau", sec: "Niamey, Niger" },
  { main: "Yantala", sec: "Niamey, Niger" },
  { main: "Lazaret", sec: "Niamey, Niger" },
  { main: "Kouara Kano", sec: "Niamey, Niger" },
  { main: "Gamkall\u00e9", sec: "Niamey, Niger" },
  { main: "Maradi", sec: "R\u00e9gion de Maradi, Niger" },
  { main: "Zinder", sec: "R\u00e9gion de Zinder, Niger" },
  { main: "Agadez", sec: "R\u00e9gion d\u2019Agadez, Niger" },
  { main: "Tahoua", sec: "R\u00e9gion de Tahoua, Niger" },
  { main: "Dosso", sec: "R\u00e9gion de Dosso, Niger" },
  { main: "Arlit", sec: "R\u00e9gion d\u2019Agadez, Niger" },
  { main: "Tillab\u00e9ri", sec: "R\u00e9gion de Tillab\u00e9ri, Niger" },
  { main: "Diffa", sec: "R\u00e9gion de Diffa, Niger" },
];

function GoogleAttribution() {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "flex-end", gap: 6, padding: "7px 16px", fontSize: 11, color: "var(--muted)" }}>
      <span>{L("powered by", "fourni par")}</span>
      <span style={{ fontFamily: "var(--fsemi)", fontWeight: 700, letterSpacing: "-0.02em", fontSize: 13 }}>
        <span style={{ color: "#4285F4" }}>G</span><span style={{ color: "#EA4335" }}>o</span><span style={{ color: "#FBBC05" }}>o</span><span style={{ color: "#4285F4" }}>g</span><span style={{ color: "#34A853" }}>l</span><span style={{ color: "#EA4335" }}>e</span>
      </span>
    </div>
  );
}

function PlacesAutocomplete({ defaultValue }) {
  const [value, setValue] = useState(defaultValue || "");
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState(0);
  const boxRef = useRef(null);
  useEffect(() => {
    const h = (e) => { if (boxRef.current && !boxRef.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);
  const q = value.trim().toLowerCase();
  const matches = (q === "" ? NIGER_PLACES : NIGER_PLACES.filter((p) => (p.main + " " + p.sec).toLowerCase().includes(q))).slice(0, 6);
  const choose = (p) => { setValue(p.main); setOpen(false); };
  const onKey = (e) => {
    if (!open || !matches.length) return;
    if (e.key === "ArrowDown") { e.preventDefault(); setActive((a) => Math.min(a + 1, matches.length - 1)); }
    else if (e.key === "ArrowUp") { e.preventDefault(); setActive((a) => Math.max(a - 1, 0)); }
    else if (e.key === "Enter") { e.preventDefault(); if (matches[active]) choose(matches[active]); }
    else if (e.key === "Escape") setOpen(false);
  };
  return (
    <div ref={boxRef} style={{ position: "relative" }}>
      <input value={value} onChange={(e) => { setValue(e.target.value); setOpen(true); setActive(0); }} onFocus={() => setOpen(true)} onKeyDown={onKey} placeholder={L("Search a city, branch or airport", "Ville, agence ou a\u00e9roport")} style={inpStyle} autoComplete="off" />
      {open && (
        <div style={{ position: "absolute", top: "calc(100% + 12px)", left: -14, right: -14, background: "var(--paper)", border: "1px solid var(--line)", borderRadius: 6, boxShadow: "0 24px 48px -20px rgba(0,0,0,.4)", zIndex: 60, overflow: "hidden" }}>
          {matches.length === 0 ? (
            <div style={{ padding: "16px 18px", color: "var(--muted)", fontSize: 14 }}>{L("No matching place", "Aucun lieu trouv\u00e9")}</div>
          ) : matches.map((p, i) => (
            <button key={p.main} type="button" onMouseEnter={() => setActive(i)} onClick={() => choose(p)} style={{ display: "flex", alignItems: "center", gap: 12, width: "100%", textAlign: "left", padding: "11px 16px", background: i === active ? "var(--paper-2)" : "transparent", borderBottom: "1px solid var(--line)" }}>
              <span style={{ color: p.branch ? "var(--rent-d)" : "var(--muted)", flexShrink: 0 }}><Icon name={p.branch ? "key" : "pin"} size={18} /></span>
              <span style={{ minWidth: 0 }}>
                <span style={{ display: "block", fontFamily: "var(--fsemi)", fontWeight: 600, fontSize: 14.5, color: "var(--ink)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.main}</span>
                <span style={{ display: "block", fontSize: 12.5, color: "var(--muted)" }}>{p.sec}</span>
              </span>
            </button>
          ))}
          <GoogleAttribution />
        </div>
      )}
    </div>
  );
}

/* ---------- Corporate / fleet-sales contact modal ---------- */
function FleetSalesModal({ onClose }) {
  const [done, setDone] = useState(false);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState("");
  const [f, setF] = useState({ company: "", contact: "", phone: "", email: "", fleetSize: "", duration: "", message: "", _hp: "" });
  const set = (k, v) => setF((s) => ({ ...s, [k]: v }));
  useEffect(() => {
    document.body.classList.add("no-scroll");
    return () => document.body.classList.remove("no-scroll");
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (f._hp) { setDone(true); return; }
    if (!window.sb) { setError(L("Connection unavailable — please call us instead.", "Connexion indisponible \u2014 merci de nous appeler directement.")); return; }
    setSending(true); setError("");
    const { data: lead, error: err } = await window.sb.from("fleet_leads").insert({
      company: f.company, contact_name: f.contact, phone: f.phone, email: f.email,
      fleet_size: f.fleetSize, duration: f.duration, message: f.message || null,
    }).select().single();
    setSending(false);
    if (err) { setError(L("Something went wrong — please try again or call us.", "Une erreur est survenue \u2014 merci de r\u00e9essayer ou de nous appeler.")); return; }
    if (window.ggNotify) window.ggNotify("fleet_lead", lead);
    setDone(true);
  };

  return ReactDOM.createPortal(
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 100, background: "rgba(22,19,15,.6)", backdropFilter: "blur(4px)", display: "flex", alignItems: "center", justifyContent: "center", overflowY: "auto", padding: "20px", animation: "viewIn .25s both" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: "var(--paper)", borderRadius: 6, width: "min(560px,100%)", maxHeight: "90vh", overflow: "auto", boxShadow: "0 40px 80px -30px rgba(0,0,0,.6)" }}>
        <div style={{ padding: "30px 30px 32px" }}>
          {done ? (
            <div style={{ textAlign: "center", padding: "24px 6px" }}>
              <div style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--rent)", display: "grid", placeItems: "center", margin: "0 auto", color: "var(--paper)" }}><Icon name="check" size={34} /></div>
              <h3 style={{ fontSize: 30, marginTop: 20 }}>{L("Request received!", "Demande envoy\u00e9e !")}</h3>
              <p style={{ color: "var(--muted)", marginTop: 12, fontSize: 16, lineHeight: 1.55 }}>{L("Our fleet-sales team will get back to you within one business day to build a tailored proposal.", "Notre \u00e9quipe flotte vous recontacte sous un jour ouvr\u00e9 pour b\u00e2tir une proposition sur mesure.")}</p>
              <button className="btn btn-ink" style={{ marginTop: 24 }} onClick={onClose}>{L("Done", "Termin\u00e9")}</button>
            </div>
          ) : (
            <form onSubmit={handleSubmit}>
              <input type="text" name="website" value={f._hp} onChange={(e) => set("_hp", e.target.value)} autoComplete="off" tabIndex={-1}
                style={{ position: "absolute", width: 1, height: 1, opacity: 0, pointerEvents: "none" }} aria-hidden="true" />
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 14 }}>
                <div>
                  <span className="eyebrow" style={{ color: "var(--rent-d)" }}>{L("For business", "Pour les entreprises")}</span>
                  <h3 style={{ fontSize: 30, marginTop: 8 }}>{L("Talk to fleet sales", "Parler aux ventes flotte")}</h3>
                </div>
                <button type="button" onClick={onClose} style={{ width: 38, height: 38, borderRadius: "50%", background: "var(--paper-2)", display: "grid", placeItems: "center", color: "var(--ink)", flexShrink: 0 }}><Icon name="close" size={20} /></button>
              </div>
              <p style={{ color: "var(--muted)", fontSize: 15, lineHeight: 1.55, marginTop: 10 }}>{L("Tell us about your team and we\u2019ll put together monthly or annual leasing options.", "Parlez-nous de vos besoins et nous pr\u00e9parons des options de location mensuelle ou annuelle.")}</p>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginTop: 22 }}>
                <FormField label={L("Company", "Entreprise")}><input required value={f.company} onChange={(e) => set("company", e.target.value)} style={fInp} placeholder={L("Company name", "Nom de l\u2019entreprise")} /></FormField>
                <FormField label={L("Contact name", "Nom du contact")}><input required value={f.contact} onChange={(e) => set("contact", e.target.value)} style={fInp} placeholder="Ibrahim M." /></FormField>
                <FormField label={L("Phone / WhatsApp", "T\u00e9l\u00e9phone / WhatsApp")}><input required value={f.phone} onChange={(e) => set("phone", e.target.value)} style={fInp} placeholder="+227 …" /></FormField>
                <FormField label={L("Email", "E-mail")}><input type="email" required value={f.email} onChange={(e) => set("email", e.target.value)} style={fInp} placeholder="nom@entreprise.ne" /></FormField>
                <FormField label={L("Fleet size", "Taille de flotte")}>
                  <select required value={f.fleetSize} onChange={(e) => set("fleetSize", e.target.value)} style={{ ...fInp, cursor: "pointer" }}>
                    <option value="" disabled>{L("Select\u2026", "Choisir\u2026")}</option>
                    {["1 \u2013 3", "4 \u2013 10", "11 \u2013 25", "25+"].map((o) => <option key={o} value={o}>{o} {L("vehicles", "v\u00e9hicules")}</option>)}
                  </select>
                </FormField>
                <FormField label={L("Duration", "Dur\u00e9e")}>
                  <select required value={f.duration} onChange={(e) => set("duration", e.target.value)} style={{ ...fInp, cursor: "pointer" }}>
                    <option value="" disabled>{L("Select\u2026", "Choisir\u2026")}</option>
                    {[L("Monthly", "Mensuelle"), L("6 months", "6 mois"), L("Annual", "Annuelle"), L("Multi-year", "Pluriannuelle")].map((o) => <option key={o} value={o}>{o}</option>)}
                  </select>
                </FormField>
              </div>
              <div style={{ marginTop: 14 }}>
                <FormField label={L("Message (optional)", "Message (facultatif)")}><textarea rows={2} value={f.message} onChange={(e) => set("message", e.target.value)} style={{ ...fInp, resize: "vertical" }} placeholder={L("Vehicle types, with or without drivers, start date\u2026", "Types de v\u00e9hicules, avec ou sans chauffeur, date de d\u00e9but\u2026")} /></FormField>
              </div>
              {error && <p style={{ color: "#B42318", fontSize: 13.5, marginTop: 10 }}>{error}</p>}
              <button type="submit" disabled={sending} className="btn btn-accent" style={{ width: "100%", justifyContent: "center", marginTop: 20, background: "var(--rent)", color: "var(--paper)", opacity: sending ? 0.6 : 1, cursor: sending ? "wait" : "pointer" }}>
                {sending ? L("Sending…", "Envoi…") : <>{L("Request a fleet proposal", "Demander une proposition flotte")} <Icon name="arrow" size={17} className="arrow" /></>}
              </button>
              <p style={{ textAlign: "center", color: "var(--muted)", fontSize: 13, marginTop: 12 }}>{L("Or call us directly at", "Ou appelez-nous au")} {CONTACT.mobile}</p>
            </form>
          )}
        </div>
      </div>
    </div>
  , document.body);
}

function RentACar() {
  const [cat, setCat] = useState("all");
  const [withDriver, setWithDriver] = useState(false);
  const [booked, setBooked] = useState(null);
  const [salesOpen, setSalesOpen] = useState(false);

  const filtered = FLEET.filter((v) => cat === "all" || v.cat === cat);

  return (
    <div className="view" style={{ "--accent": "var(--rent)", "--accent-d": "var(--rent-d)" }}>
      <Nav variant="rent" />

      {/* HERO + BOOKING */}
      <section style={{ background: "var(--paper)", color: "var(--ink)", paddingTop: 76, position: "relative", overflow: "visible" }}>
        <Ph scene={<RACImg name="Toyota Land Cruiser" cover />} style={{ position: "absolute", inset: 0 }} />
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg,rgba(246,242,234,.5),rgba(246,242,234,.92))" }} />
        <div className="wrap" style={{ position: "relative", paddingTop: 70, paddingBottom: 56 }}>
          <Reveal><div style={{ fontFamily: "var(--fdisp)", fontWeight: 700, fontSize: 13, textTransform: "uppercase", letterSpacing: ".14em", color: "var(--muted)", marginBottom: 16 }}>Guero’s Group Rent-a-Car</div></Reveal>
          <Reveal><SectionTag color="var(--rent-d)">{L("Rent-a-Car · A Guero\u2019s Group service", "Rent-a-Car · Un service du Guero\u2019s Group")}</SectionTag></Reveal>
          <Reveal delay={70}><h1 style={{ fontSize: "clamp(48px,7.5vw,108px)", marginTop: 20, maxWidth: 960 }}>{L(<>Wheels for<br />the journey</>, <>Des roues pour<br />la route</>)}<span style={{ color: "var(--rent)" }}>.</span></h1></Reveal>
          <Reveal delay={130}><p style={{ fontSize: "clamp(16px,1.9vw,20px)", color: "var(--ink-2)", marginTop: 24, maxWidth: 560, lineHeight: 1.55 }}>{L("From a city sedan to a 14-seater van or a box truck — self-drive or chauffeured, by the day or the year. A clean, well-maintained fleet you can count on across Niger.", "De la berline urbaine au van 14 places ou au camion — en libre conduite ou avec chauffeur, \u00e0 la journ\u00e9e ou \u00e0 l\u2019ann\u00e9e. Une flotte propre et bien entretenue, partout au Niger.")}</p></Reveal>

          {/* booking widget */}
          <Reveal delay={190}>
            <div style={{ background: "var(--paper-0)", borderRadius: 5, padding: 12, marginTop: 40, maxWidth: 980, boxShadow: "0 30px 60px -34px rgba(0,0,0,.3)", border: "1px solid var(--line)" }}>
              <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr auto", gap: 10 }} className="bookbar">
                <RField icon="pin" label={L("Pick-up location", "Lieu de prise en charge")}><PlacesAutocomplete defaultValue={L("A\u00e9roport International Diori Hamani", "A\u00e9roport International Diori Hamani")} /></RField>
                <RField icon="calendar" label={L("Pick-up", "D\u00e9part")}><input type="date" defaultValue={nigerToday(1)} style={inpStyle} /></RField>
                <RField icon="calendar" label={L("Return", "Retour")}><input type="date" defaultValue={nigerToday(4)} style={inpStyle} /></RField>
                <RField icon="car" label={L("Vehicle type", "Type de v\u00e9hicule")}>
                  <select value={cat} onChange={(e) => setCat(e.target.value)} style={selStyle}>
                    {FLEET_CATS.map((c) => <option key={c.k} value={c.k}>{L(c.label.en, c.label.fr)}</option>)}
                  </select>
                </RField>
                <button className="btn btn-accent" style={{ borderRadius: 3, justifyContent: "center", background: "var(--rent)", color: "var(--paper)" }} onClick={() => { const el = document.getElementById("sec-fleet"); if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 70, behavior: "smooth" }); }}>
                  <Icon name="search" size={18} /> {L("Search", "Rechercher")}
                </button>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 16, padding: "12px 8px 4px", flexWrap: "wrap" }}>
                <button onClick={() => setWithDriver(!withDriver)} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <span style={{ width: 42, height: 24, borderRadius: 20, background: withDriver ? "var(--rent)" : "var(--paper-3)", position: "relative", transition: "background .2s" }}>
                    <span style={{ position: "absolute", top: 3, left: withDriver ? 21 : 3, width: 18, height: 18, borderRadius: "50%", background: "#fff", transition: "left .2s" }} />
                  </span>
                  <span style={{ fontFamily: "var(--fsemi)", fontWeight: 700, fontSize: 14, color: "var(--ink)" }}>{L("With a driver", "Avec chauffeur")}</span>
                </button>
                <span style={{ fontSize: 13.5, color: "var(--muted)" }}>{L("Free cancellation up to 24h before pick-up", "Annulation gratuite jusqu\u2019\u00e0 24h avant le d\u00e9part")}</span>
              </div>
            </div>
          </Reveal>
        </div>
      </section>

      <Marquee bg="var(--rent)" color="var(--paper)" accent="var(--paper)" items={L(["Self-drive", "Chauffeured", "Airport Pickup", "Daily & Monthly", "Corporate Fleet", "Long-term Lease", "24/7 Roadside"], ["Libre conduite", "Avec chauffeur", "Accueil a\u00e9roport", "Journ\u00e9e & mois", "Flotte entreprise", "Longue dur\u00e9e", "Assistance 24/7"])} />

      {/* FLEET */}
      <section id="sec-fleet" style={{ padding: "100px 0 110px", background: "var(--paper)" }}>
        <div className="wrap">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: 20, marginBottom: 34 }}>
            <div>
              <Reveal><SectionTag n="01" color="var(--rent-d)">{L("The fleet", "La flotte")}</SectionTag></Reveal>
              <Reveal delay={60}><h2 style={{ fontSize: "clamp(34px,4.4vw,56px)", marginTop: 18 }}>{L("Pick your ride.", "Choisissez votre v\u00e9hicule.")}</h2></Reveal>
            </div>
            <Reveal delay={100}>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                {FLEET_CATS.map((c) => (
                  <button key={c.k} onClick={() => setCat(c.k)} style={{
                    fontFamily: "var(--fsemi)", fontWeight: 700, fontSize: 13.5, letterSpacing: "0.04em", textTransform: "uppercase",
                    padding: "9px 16px", borderRadius: 2, transition: "all .2s",
                    background: cat === c.k ? "var(--rent)" : "transparent", color: cat === c.k ? "var(--paper)" : "var(--ink)",
                    border: "1px solid " + (cat === c.k ? "var(--rent)" : "var(--line)"),
                  }}>{L(c.label.en, c.label.fr)}</button>
                ))}
              </div>
            </Reveal>
          </div>

          {filtered.length === 0 && window.GG_DATA && window.GG_DATA.loadError ? (
            <div style={{ textAlign: "center", padding: "60px 20px", background: "var(--paper-2)", borderRadius: 6 }}>
              <p style={{ fontSize: 16, color: "var(--muted)", marginBottom: 14 }}>{L("We're having trouble loading the fleet right now.", "Nous avons un probl\u00e8me pour charger la flotte en ce moment.")}</p>
              <button className="btn" onClick={() => window.location.reload()}>{L("Try again", "R\u00e9essayer")}</button>
              <p style={{ marginTop: 14, fontSize: 13.5, color: "var(--muted)" }}>{L("Or call us at", "Ou appelez-nous au")} {CONTACT.mobile}</p>
            </div>
          ) : (
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 18 }} className="g3">
              {filtered.map((v, i) => <FleetCard key={v.name} v={v} withDriver={withDriver} delay={(i % 3) * 50} onBook={() => setBooked(v)} />)}
            </div>
          )}
        </div>
      </section>

      {/* HOW IT WORKS */}
      <section style={{ padding: "100px 0", background: "var(--paper-2)", color: "var(--ink)" }}>
        <div className="wrap">
          <Reveal><SectionTag n="02" color="var(--rent-d)">How it works</SectionTag></Reveal>
          <Reveal delay={60}><h2 style={{ fontSize: "clamp(34px,4.4vw,56px)", marginTop: 18, marginBottom: 54, maxWidth: 700 }}>On the road in four steps.</h2></Reveal>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 22 }} className="g4">
            {[
              ["Choose", "Pick a vehicle and your dates — self-drive or with a driver.", "search"],
              ["Confirm", "Send your details and a valid licence. We confirm in minutes.", "check"],
              ["Collect", "Pick up at a branch or have it delivered to your door or the airport.", "key"],
              ["Drive", "Hit the road with 24/7 roadside support behind you.", "car"],
            ].map(([h, d, ic], i) => (
              <Reveal key={h} delay={i * 70}>
                <div style={{ borderTop: "2px solid var(--rent)", paddingTop: 22 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <span style={{ fontFamily: "var(--fdisp)", fontWeight: 800, fontSize: 44, color: "var(--paper-3)" }}>0{i + 1}</span>
                    <span style={{ color: "var(--rent-d)" }}><Icon name={ic} size={26} /></span>
                  </div>
                  <h3 style={{ fontSize: 26, marginTop: 14 }}>{h}</h3>
                  <p style={{ color: "var(--muted)", fontSize: 15, lineHeight: 1.55, marginTop: 10 }}>{d}</p>
                </div>
              </Reveal>
            ))}
          </div>
          <Reveal delay={120}>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 22, marginTop: 64, paddingTop: 40, borderTop: "1px solid var(--line)" }} className="g4">
              {[["clock", "24/7", "roadside support"], ["shield", "Fully", "insured fleet"], ["gauge", "Unlimited", "mileage included"], ["users", "35%", "of Niger's market"]].map(([ic, n, l]) => (
                <div key={l} style={{ display: "flex", gap: 14, alignItems: "center" }}>
                  <span style={{ color: "var(--rent-d)" }}><Icon name={ic} size={24} /></span>
                  <div><div style={{ fontFamily: "var(--fdisp)", fontWeight: 800, fontSize: 26, lineHeight: 1 }}>{n}</div><div className="eyebrow" style={{ color: "var(--muted)", marginTop: 5 }}>{l}</div></div>
                </div>
              ))}
            </div>
          </Reveal>
        </div>
      </section>

      {/* CORPORATE CTA */}
      <section id="sec-book" style={{ padding: "110px 0", background: "var(--paper-2)" }}>
        <div className="wrap">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 64, alignItems: "center" }} className="g2">
            <Reveal>
              <Ph scene={<RACImg name="Toyota Hilux D/Cab" />} style={{ aspectRatio: "5/4", borderRadius: 5 }} />
            </Reveal>
            <div>
              <Reveal><SectionTag n="03" color="var(--rent-d)">For business</SectionTag></Reveal>
              <Reveal delay={60}><h2 style={{ fontSize: "clamp(34px,4.4vw,56px)", marginTop: 18 }}>Corporate & long-term leasing.</h2></Reveal>
              <Reveal delay={120}><p style={{ marginTop: 22, color: "var(--ink-2)", fontSize: 17, lineHeight: 1.6, maxWidth: 440 }}>Put your team and goods on the road without the capital outlay. Monthly and annual plans, dedicated account management, and replacement vehicles included.</p></Reveal>
              <div style={{ marginTop: 28, display: "flex", flexDirection: "column", gap: 12 }}>
                {["Fixed monthly billing — no surprise costs", "Servicing & maintenance handled by us", "Replacement vehicle within 24h", "Optional dedicated drivers"].map((t) => (
                  <Reveal key={t} delay={140}><div style={{ display: "flex", gap: 12, alignItems: "center", fontSize: 16, color: "var(--ink-2)" }}><Icon name="check" size={18} style={{ color: "var(--rent)" }} />{t}</div></Reveal>
                ))}
              </div>
              <Reveal delay={180}>
                <button className="btn" style={{ marginTop: 32, background: "var(--rent)", color: "var(--paper)" }} onClick={() => setSalesOpen(true)}>Talk to fleet sales <Icon name="arrow" size={17} className="arrow" /></button>
              </Reveal>
            </div>
          </div>
        </div>
      </section>

      <Footer variant="rent" />

      {/* BOOKING MODAL */}
      {booked && <BookingModal v={booked} withDriver={withDriver} onClose={() => setBooked(null)} />}
      {salesOpen && <FleetSalesModal onClose={() => setSalesOpen(false)} />}
    </div>
  );
}

/* ---------- Fleet card ---------- */
function FleetCard({ v, withDriver, delay, onBook }) {
  const [hover, setHover] = useState(false);
  const price = v.price + (withDriver ? 25000 : 0);
  return (
    <Reveal delay={delay}>
      <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
        style={{ background: "var(--paper-0)", border: "1px solid var(--line)", borderRadius: 5, overflow: "hidden", transition: "transform .2s, box-shadow .2s", transform: hover ? "translateY(-5px)" : "none", boxShadow: hover ? "0 26px 50px -28px rgba(0,0,0,.32)" : "none", display: "flex", flexDirection: "column", height: "100%" }}>
        <Ph scene={<RACImg name={v.name} />} style={{ aspectRatio: "16/10" }}>
          {v.tag && <span style={{ position: "absolute", top: 14, left: 14, background: "var(--rent)", color: "var(--paper)", fontFamily: "var(--fsemi)", fontWeight: 700, fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", padding: "5px 10px", borderRadius: 2 }}>{v.tag === "Popular" ? L("Popular", "Populaire") : v.tag}</span>}
        </Ph>
        <div style={{ padding: "20px 22px 24px", display: "flex", flexDirection: "column", flex: 1 }}>
          <h3 style={{ fontSize: 25 }}>{v.name}</h3>
          <div style={{ display: "flex", gap: 16, marginTop: 12, flexWrap: "wrap" }}>
            {[["users", v.seats + L(" seats", " places")], ["gear", v.trans === "Auto" ? L("Auto", "Auto") : L("Manual", "Manuelle")], ["bolt", v.fuel === "Petrol" ? L("Petrol", "Essence") : v.fuel === "Diesel" ? "Diesel" : L("Hybrid", "Hybride")]].map(([ic, tx]) => (
              <span key={tx} style={{ display: "inline-flex", gap: 6, alignItems: "center", fontSize: 13.5, color: "var(--muted)" }}><Icon name={ic} size={16} />{tx}</span>
            ))}
          </div>
          <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginTop: "auto", paddingTop: 20 }}>
            <div>
              <div style={{ fontFamily: "var(--fdisp)", fontWeight: 800, fontSize: 28, lineHeight: 1 }}>{price.toLocaleString()}<span style={{ fontSize: 13, color: "var(--muted)", fontFamily: "var(--fbody)", fontWeight: 500 }}> {L("FCFA/day", "FCFA/jour")}</span></div>
              {withDriver && <div style={{ fontSize: 12, color: "var(--rent-d)", marginTop: 3 }}>{L("incl. driver", "chauffeur inclus")}</div>}
            </div>
            <button className="btn" style={{ background: hover ? "var(--rent)" : "var(--ink)", color: "var(--paper)", padding: "11px 18px", fontSize: 13 }} onClick={onBook}>{L("Reserve", "R\u00e9server")} <Icon name="arrow" size={15} className="arrow" /></button>
          </div>
        </div>
      </div>
    </Reveal>
  );
}

/* ---------- Booking modal ---------- */
function BookingModal({ v, withDriver, onClose }) {
  const [done, setDone] = useState(false);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState("");
  const [f, setF] = useState({ name: "", phone: "", email: "", pickup: nigerToday(1), ret: nigerToday(4), notes: "", _hp: "" });
  const set = (k, val) => setF((s) => ({ ...s, [k]: val }));
  useEffect(() => {
    document.body.classList.add("no-scroll");
    return () => document.body.classList.remove("no-scroll");
  }, []);
  const price = v.price + (withDriver ? 25000 : 0);
  const days = Math.max(1, Math.round((new Date(f.ret) - new Date(f.pickup)) / 86400000));

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (f._hp) { setDone(true); return; }
    if (!window.sb) { setError(L("Connection unavailable — please call us instead.", "Connexion indisponible \u2014 merci de nous appeler directement.")); return; }
    if (new Date(f.ret) < new Date(f.pickup)) { setError(L("Return date must be after pick-up date.", "La date de retour doit \u00eatre apr\u00e8s la date de d\u00e9part.")); return; }
    setSending(true); setError("");
    const { error: err } = await window.sb.from("bookings").insert({
      vehicle_id: v.id, pickup_at: f.pickup, return_at: f.ret,
      with_driver: !!withDriver, total_xof: price * days,
      contact: { name: f.name, phone: f.phone, email: f.email || null },
      notes: f.notes || null, payment_method: "card",
    });
    setSending(false);
    if (err) {
      if (err.code === "23P01") {
        setError(L("These dates are no longer available for this vehicle — please pick different dates.", "Ces dates ne sont plus disponibles pour ce v\u00e9hicule \u2014 merci de choisir d'autres dates."));
      } else {
        setError(L("Something went wrong — please try again or call us.", "Une erreur est survenue \u2014 merci de r\u00e9essayer ou de nous appeler."));
      }
      return;
    }
    // Fire-and-forget notification — booking is already saved even if this fails.
    // We don't read the row back: anon only has INSERT permission on bookings,
    // not SELECT, so we build the notification from what we already have here.
    if (window.ggNotify) window.ggNotify("booking", {
      vehicle_name: v.name, pickup_at: f.pickup, return_at: f.ret,
      total_xof: price * days, notes: f.notes || null,
      contact: { name: f.name, phone: f.phone, email: f.email || null },
    });
    setDone(true);
  };

  return ReactDOM.createPortal(
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 100, background: "rgba(22,19,15,.6)", backdropFilter: "blur(4px)", display: "flex", alignItems: "center", justifyContent: "center", overflowY: "auto", padding: "20px", animation: "viewIn .25s both" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: "var(--paper)", borderRadius: 6, width: "min(560px,100%)", maxHeight: "90vh", overflow: "auto", boxShadow: "0 40px 80px -30px rgba(0,0,0,.6)" }}>
        <div style={{ position: "relative" }}>
          <Ph scene={<RACImg name={v.name} />} style={{ aspectRatio: "16/8" }} />
          <button onClick={onClose} style={{ position: "absolute", top: 14, right: 14, width: 38, height: 38, borderRadius: "50%", background: "var(--paper)", display: "grid", placeItems: "center", color: "var(--ink)" }}><Icon name="close" size={20} /></button>
        </div>
        <div style={{ padding: "28px 30px 32px" }}>
          {done ? (
            <div style={{ textAlign: "center", padding: "24px 6px" }}>
              <div style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--rent)", display: "grid", placeItems: "center", margin: "0 auto", color: "var(--paper)" }}><Icon name="check" size={34} /></div>
              <h3 style={{ fontSize: 30, marginTop: 20 }}>{L("Reservation requested!", "R\u00e9servation envoy\u00e9e !")}</h3>
              <p style={{ color: "var(--muted)", marginTop: 12, fontSize: 16, lineHeight: 1.55 }}>{L(<>We've got your request for the <strong>{v.name}</strong>. Our team will confirm availability and payment by WhatsApp shortly.</>, <>Nous avons bien reçu votre demande pour le <strong>{v.name}</strong>. Notre équipe confirmera la disponibilité et le paiement par WhatsApp très vite.</>)}</p>
              <a href={"https://wa.me/" + CONTACT.mobile.replace(/[^\d]/g, "") + "?text=" + encodeURIComponent(L(`Hello, I just requested a booking for the ${v.name}.`, `Bonjour, je viens de faire une demande de r\u00e9servation pour ${v.name}.`))} target="_blank" rel="noopener"
                style={{ display: "inline-flex", alignItems: "center", gap: 7, marginTop: 14, color: "#25D366", fontFamily: "var(--fsemi)", fontWeight: 700, fontSize: 13.5 }}>
                {L("Confirm via WhatsApp too →", "Confirmer aussi par WhatsApp →")}
              </a><br />
              <button className="btn btn-ink" style={{ marginTop: 18 }} onClick={onClose}>{L("Done", "Termin\u00e9")}</button>
            </div>
          ) : (
            <form onSubmit={handleSubmit}>
              <input type="text" name="website" value={f._hp} onChange={(e) => set("_hp", e.target.value)} autoComplete="off" tabIndex={-1}
                style={{ position: "absolute", width: 1, height: 1, opacity: 0, pointerEvents: "none" }} aria-hidden="true" />
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 14 }}>
                <div>
                  <span className="eyebrow" style={{ color: "var(--rent-d)" }}>{L("Reserve", "R\u00e9server")}</span>
                  <h3 style={{ fontSize: 32, marginTop: 8 }}>{v.name}</h3>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontFamily: "var(--fdisp)", fontWeight: 800, fontSize: 28, lineHeight: 1 }}>{price.toLocaleString()} FCFA</div>
                  <div style={{ fontSize: 12, color: "var(--muted)" }}>{L("per day", "par jour")}{withDriver ? L(" · incl. driver", " · chauffeur inclus") : ""}</div>
                </div>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginTop: 22 }}>
                <FormField label={L("Full name", "Nom complet")}><input required value={f.name} onChange={(e) => set("name", e.target.value)} style={fInp} placeholder="Ibrahim M." /></FormField>
                <FormField label={L("Phone / WhatsApp", "T\u00e9l\u00e9phone / WhatsApp")}><input required value={f.phone} onChange={(e) => set("phone", e.target.value)} style={fInp} placeholder="+227 …" /></FormField>
                <div style={{ gridColumn: "1/-1" }}><FormField label={L("Email (for confirmation)", "Email (pour confirmation)")}><input type="email" value={f.email} onChange={(e) => set("email", e.target.value)} style={fInp} placeholder="vous@exemple.com" /></FormField></div>
                <FormField label={L("Pick-up date", "Date de d\u00e9part")}><input type="date" required value={f.pickup} onChange={(e) => set("pickup", e.target.value)} style={fInp} /></FormField>
                <FormField label={L("Return date", "Date de retour")}><input type="date" required value={f.ret} onChange={(e) => set("ret", e.target.value)} style={fInp} /></FormField>
              </div>
              <div style={{ marginTop: 14 }}>
                <FormField label={L("Notes (optional)", "Notes (facultatif)")}><textarea rows={2} value={f.notes} onChange={(e) => set("notes", e.target.value)} style={{ ...fInp, resize: "vertical" }} placeholder={L("Delivery to airport, child seat, etc.", "Livraison a\u00e9roport, si\u00e8ge enfant, etc.")} /></FormField>
              </div>
              <div style={{ marginTop: 12, padding: "10px 14px", background: "var(--paper-2)", borderRadius: 3, fontSize: 13, color: "var(--muted)" }}>
                {L(`${days} day(s) · Total ${(price*days).toLocaleString()} FCFA · Payment by card, confirmed via WhatsApp`, `${days} jour(s) · Total ${(price*days).toLocaleString()} FCFA · Paiement par carte, confirm\u00e9 par WhatsApp`)}
              </div>
              {error && <p style={{ color: "#B42318", fontSize: 13.5, marginTop: 10 }}>{error}</p>}
              <button type="submit" disabled={sending} className="btn btn-accent" style={{ width: "100%", justifyContent: "center", marginTop: 16, background: "var(--rent)", color: "var(--paper)", opacity: sending ? 0.6 : 1, cursor: sending ? "wait" : "pointer" }}>
                {sending ? L("Sending…", "Envoi…") : <>{L("Request reservation", "Envoyer la r\u00e9servation")} <Icon name="arrow" size={17} className="arrow" /></>}
              </button>
              <p style={{ textAlign: "center", color: "var(--muted)", fontSize: 13, marginTop: 12 }}>{L("Free cancellation up to 24h before pick-up", "Annulation gratuite jusqu\u2019\u00e0 24h avant le d\u00e9part")}</p>
            </form>
          )}
        </div>
      </div>
    </div>
  , document.body);
}

function RField({ icon, label, children }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "8px 14px", borderRadius: 3, background: "var(--paper-2)" }}>
      <span style={{ color: "var(--rent-d)" }}><Icon name={icon} size={19} /></span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: "var(--fsemi)", fontSize: 10.5, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--muted)" }}>{label}</div>
        {children}
      </div>
    </div>
  );
}

Object.assign(window, { RentACar });
