// components.jsx — globals, React via UMD (React global)
const { useState, useEffect, useRef } = React;

// --- CRM event tracking ---
function getSessionId() {
  try {
    let sid = sessionStorage.getItem("ce_sid");
    if (!sid) {
      sid = Date.now().toString(36) + Math.random().toString(36).slice(2, 10);
      sessionStorage.setItem("ce_sid", sid);
    }
    return sid;
  } catch (_) { return null; }
}
function trackEvent(type, payload) {
  const session_id = getSessionId();
  if (!session_id) return;
  const body = JSON.stringify({ type, session_id, payload: payload || {} });
  try {
    if (navigator.sendBeacon) {
      navigator.sendBeacon("/api/events", new Blob([body], { type: "application/json" }));
      return;
    }
  } catch (_) {}
  fetch("/api/events", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body,
    keepalive: true,
  }).catch(() => {});
}
// Fire "visit" once per session on first mount
if (typeof window !== "undefined" && !window.__ce_visit_tracked) {
  window.__ce_visit_tracked = true;
  try { trackEvent("visit", { path: location.pathname, ref: document.referrer || null }); } catch (_) {}
}

function Stars({ value = 5 }) {
  const full = Math.floor(value);
  return (
    <span className="stars" aria-label={`${value} étoiles`}>
      {Array.from({ length: 5 }).map((_, i) => (
        <svg key={i} width="14" height="14" viewBox="0 0 20 20" fill={i < full ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.5">
          <path d="M10 2l2.47 5 5.53.8-4 3.9.94 5.5L10 14.6l-4.94 2.6.94-5.5-4-3.9 5.53-.8L10 2z"/>
        </svg>
      ))}
    </span>
  );
}

function Reveal({ children, delay = 0, className = "" }) {
  const ref = useRef(null);
  const [inView, setInView] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setInView(true); io.unobserve(el); }
    }, { rootMargin: "0px 0px -80px 0px", threshold: 0.1 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <div ref={ref} className={`reveal ${inView ? "in" : ""} ${className}`} style={{ transitionDelay: `${delay}ms` }}>
      {children}
    </div>
  );
}

function Eyebrow({ children }) {
  return <div className="eyebrow">{children}</div>;
}

function PhoneIcon(props) {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <path d="M22 16.92v3a2 2 0 01-2.18 2 19.8 19.8 0 01-8.63-3.07 19.5 19.5 0 01-6-6A19.8 19.8 0 012.12 4.18 2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.9.72 2.8a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.28-1.28a2 2 0 012.11-.45c.9.35 1.84.59 2.8.72A2 2 0 0122 16.92z"/>
    </svg>
  );
}

function ArrowIcon(props) {
  return (
    <svg className="arrow" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <path d="M5 12h14M13 5l7 7-7 7"/>
    </svg>
  );
}

function Header({ page, setPage, openModal }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const go = (p) => (e) => { e.preventDefault(); setPage(p); window.scrollTo({ top: 0, behavior: "smooth" }); };

  return (
    <header className={`header ${scrolled ? "scrolled" : ""}`}>
      <div className="wrap header-inner">
        <a href="#" onClick={go("home")} className="brand">
          <span className="brand-mark" />
          <span>Cours Edgar</span>
        </a>
        <nav className="nav">
          <a href="#" onClick={go("home")}   className={page === "home"   ? "active" : ""}>Accueil</a>
          <a href="#" onClick={go("tarifs")} className={page === "tarifs" ? "active" : ""}>Tarifs</a>
          <a href="#" onClick={go("profs")}  className={page === "profs"  ? "active" : ""}>Nos professeurs</a>
        </nav>
        <div className="header-actions">
          <a href={`tel:${PHONE.replace(/\s/g,"")}`} className="phone-link">
            <PhoneIcon /> {PHONE}
          </a>
          <button className="btn btn-primary btn-sm" onClick={openModal}>Être rappelé</button>
        </div>
      </div>
    </header>
  );
}

function StickyCTA({ openModal }) {
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const onScroll = () => setVisible(window.scrollY > 300);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <div className={`sticky-cta ${visible ? "visible" : ""}`}>
      <span className="label">Parlons de votre enfant</span>
      <div className="sc-actions">
        <a href={`tel:${PHONE.replace(/\s/g,"")}`} className="icon-btn" aria-label="Appeler"><PhoneIcon /></a>
        <button className="btn btn-accent btn-sm" onClick={openModal}>Être rappelé</button>
      </div>
    </div>
  );
}

function Footer({ setPage, openModal }) {
  const go = (p) => (e) => { e.preventDefault(); setPage(p); window.scrollTo({ top: 0, behavior: "smooth" }); };
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div className="footer-brand">
            <div className="brand"><span className="brand-mark" /><span>Cours Edgar</span></div>
            <p>Soutien scolaire d'excellence à domicile à Paris. Des professeurs issus des grandes écoles, un matching sur-mesure, un suivi transparent.</p>
            <button className="btn btn-primary btn-sm" onClick={openModal}>Être rappelé</button>
          </div>
          <div className="footer-col">
            <h5>Navigation</h5>
            <ul>
              <li><a href="#" onClick={go("home")}>Accueil</a></li>
              <li><a href="#" onClick={go("tarifs")}>Tarifs</a></li>
              <li><a href="#" onClick={go("profs")}>Nos professeurs</a></li>
              <li><a href="#" onClick={(e) => e.preventDefault()}>Contact</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Contact</h5>
            <ul>
              <li><a href={`tel:${PHONE.replace(/\s/g,"")}`}>{PHONE}</a></li>
              <li><a href={`mailto:${EMAIL}`}>{EMAIL}</a></li>
              <li><span className="muted">Lun–Sam, 9h–20h</span></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Légal</h5>
            <ul>
              <li><a href="#" onClick={(e) => e.preventDefault()}>Mentions légales</a></li>
              <li><a href="#" onClick={(e) => e.preventDefault()}>CGV</a></li>
              <li><a href="#" onClick={(e) => e.preventDefault()}>Confidentialité</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 Cours Edgar. Soutien scolaire d'excellence à domicile à Paris.</span>
          <span className="mono">Agréé service à la personne · Crédit d'impôt 50%</span>
        </div>
      </div>
    </footer>
  );
}

const FR_DAYS = ["Dimanche","Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi"];
const FR_MONTHS = ["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre"];

function toISODate(d) {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${y}-${m}-${day}`;
}
function formatDateFR(iso) {
  if (!iso) return "";
  const d = new Date(iso + "T00:00:00");
  return `${FR_DAYS[d.getDay()]} ${d.getDate()} ${FR_MONTHS[d.getMonth()]}`;
}
function formatHeureFR(hhmm) { return hhmm ? hhmm.replace(":", "h") : ""; }
function getAvailableSlots(iso) {
  const slots = [];
  for (let h = 9; h <= 21; h++) {
    for (let m = 0; m < 60; m += 30) {
      if (h === 21 && m > 0) break;
      slots.push(`${String(h).padStart(2,"0")}:${String(m).padStart(2,"0")}`);
    }
  }
  const now = new Date();
  if (iso === toISODate(now)) {
    const cutoff = now.getHours() * 60 + now.getMinutes() + 60;
    return slots.filter(s => {
      const [h, m] = s.split(":").map(Number);
      return h * 60 + m >= cutoff;
    });
  }
  return slots;
}
async function submitLead(data) {
  try {
    const leads = JSON.parse(localStorage.getItem("ce_leads") || "[]");
    leads.push({ ...data, at: new Date().toISOString() });
    localStorage.setItem("ce_leads", JSON.stringify(leads));
  } catch (_) {}
  try { sessionStorage.setItem("ce_lead_submitted", "1"); sessionStorage.setItem("ce_lead_popup_shown", "1"); } catch (_) {}
  try {
    const res = await fetch("/api/lead", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    });
    if (!res.ok) return false;
    const json = await res.json().catch(() => ({}));
    return json && json.ok !== false;
  } catch (_) {
    return false;
  }
}

function CalendarPicker({ value, onChange }) {
  const today = new Date(); today.setHours(0,0,0,0);
  const maxDate = new Date(today); maxDate.setDate(maxDate.getDate() + 30);
  const [cursor, setCursor] = useState(() => {
    const d = value ? new Date(value + "T00:00:00") : today;
    return new Date(d.getFullYear(), d.getMonth(), 1);
  });
  const monthStart = new Date(cursor);
  const monthEnd = new Date(cursor.getFullYear(), cursor.getMonth() + 1, 0);
  const startOffset = (monthStart.getDay() + 6) % 7; // Monday-first
  const days = [];
  for (let i = 0; i < startOffset; i++) days.push(null);
  for (let d = 1; d <= monthEnd.getDate(); d++) {
    days.push(new Date(cursor.getFullYear(), cursor.getMonth(), d));
  }
  const prevMonth = () => setCursor(new Date(cursor.getFullYear(), cursor.getMonth() - 1, 1));
  const nextMonth = () => setCursor(new Date(cursor.getFullYear(), cursor.getMonth() + 1, 1));
  const prevDisabled = cursor.getFullYear() === today.getFullYear() && cursor.getMonth() === today.getMonth();
  const nextDisabled = cursor.getFullYear() === maxDate.getFullYear() && cursor.getMonth() === maxDate.getMonth();
  return (
    <div className="wizard-calendar">
      <div className="wc-head">
        <button type="button" className="wc-nav" onClick={prevMonth} disabled={prevDisabled} aria-label="Mois précédent">‹</button>
        <div className="wc-title">
          <span className="wc-month">{FR_MONTHS[cursor.getMonth()]}</span>
          <span className="wc-year">{cursor.getFullYear()}</span>
        </div>
        <button type="button" className="wc-nav" onClick={nextMonth} disabled={nextDisabled} aria-label="Mois suivant">›</button>
      </div>
      <div className="wc-weekdays">
        {["L","M","M","J","V","S","D"].map((l, i) => <span key={i}>{l}</span>)}
      </div>
      <div className="wc-grid">
        {days.map((d, i) => {
          if (!d) return <span key={i} className="wc-cell wc-empty" />;
          const iso = toISODate(d);
          const disabled = d < today || d > maxDate;
          const selected = iso === value;
          return (
            <button
              key={i}
              type="button"
              className={`wc-cell ${selected ? "is-selected" : ""} ${disabled ? "is-disabled" : ""}`}
              disabled={disabled}
              onClick={() => onChange(iso)}
            >{d.getDate()}</button>
          );
        })}
      </div>
    </div>
  );
}

function Modal({ open, prefill, onClose }) {
  const emptyForm = {
    prenomEnfant: "", niveau: "", matieres: [], objectif: "",
    prenomParent: "", tel: "", email: "",
    date: "", heure: "", message: "",
  };
  const [step, setStep] = useState(1);
  const [values, setValues] = useState(emptyForm);
  const [errors, setErrors] = useState({});
  const [success, setSuccess] = useState(false);
  const [sending, setSending] = useState(false);
  const [submitError, setSubmitError] = useState("");
  const [showCalendar, setShowCalendar] = useState(false);

  useEffect(() => {
    if (!open) return;
    trackEvent("wizard_opened", {});
    setSuccess(false);
    setSending(false);
    setSubmitError("");
    setErrors({});
    setStep(1);
    setShowCalendar(false);
    setValues({
      ...emptyForm,
      ...(prefill && typeof prefill === "object" ? {
        prenomParent: prefill.prenomParent || prefill.prenom || "",
        tel: prefill.tel || "",
        email: prefill.email || "",
        niveau: prefill.niveau || "",
        matieres: Array.isArray(prefill.matieres) ? prefill.matieres : [],
      } : {}),
    });
  }, [open, prefill]);

  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    if (open) window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  useEffect(() => {
    if (!open || success) return;
    const onLeave = () => { trackEvent("wizard_abandoned", { step }); };
    const onVis = () => { if (document.visibilityState === "hidden") onLeave(); };
    window.addEventListener("beforeunload", onLeave);
    document.addEventListener("visibilitychange", onVis);
    return () => {
      window.removeEventListener("beforeunload", onLeave);
      document.removeEventListener("visibilitychange", onVis);
    };
  }, [open, success, step]);

  const set = (k, v) => {
    setValues(prev => ({ ...prev, [k]: v }));
    if (errors[k]) setErrors(e => { const { [k]: _, ...rest } = e; return rest; });
  };
  const toggleMatiere = (name) => setValues(v => ({
    ...v,
    matieres: v.matieres.includes(name) ? v.matieres.filter(x => x !== name) : [...v.matieres, name],
  }));

  const validateStep = (s) => {
    const err = {};
    if (s === 1) {
      if (!values.prenomEnfant.trim()) err.prenomEnfant = "Requis";
      if (!values.niveau) err.niveau = "Requis";
      if (values.matieres.length === 0) err.matieres = "Sélectionnez au moins une matière";
      if (!values.objectif) err.objectif = "Requis";
    }
    if (s === 2) {
      if (!values.prenomParent.trim()) err.prenomParent = "Requis";
      if (!values.tel.trim()) err.tel = "Requis";
      else if (!/^[\d\s+().-]{10,}$/.test(values.tel)) err.tel = "Numéro invalide";
      if (!values.email.trim()) err.email = "Requis";
      else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) err.email = "Email invalide";
    }
    if (s === 3) {
      if (!values.date) err.date = "Sélectionnez un jour";
      if (!values.heure) err.heure = "Sélectionnez un horaire";
    }
    setErrors(err);
    return Object.keys(err).length === 0;
  };

  const next = () => {
    if (validateStep(step)) {
      trackEvent(`wizard_step_${step}`, { step });
      setStep(step + 1);
    }
  };
  const back = () => setStep(Math.max(1, step - 1));

  const submit = async (e) => {
    e.preventDefault();
    if (!validateStep(3)) return;
    if (sending) return;
    setSubmitError("");
    setSending(true);
    const ok = await submitLead(values);
    setSending(false);
    if (ok) {
      setSuccess(true);
    } else {
      setSubmitError("Envoi impossible pour le moment. Vérifiez votre connexion et réessayez — vos informations sont conservées.");
    }
  };

  const now = new Date();
  const todayISO = toISODate(now);
  const tomorrow = new Date(now); tomorrow.setDate(tomorrow.getDate() + 1);
  const tomorrowISO = toISODate(tomorrow);
  const showTodayChip = now.getHours() < 19;
  const slots = values.date ? getAvailableSlots(values.date) : [];
  const selectedIsQuick = values.date === todayISO || values.date === tomorrowISO;

  const stepLabels = ["Votre enfant", "Vos coordonnées", "Votre créneau"];

  return (
    <div className={`modal-backdrop ${open ? "open" : ""}`} onClick={onClose}>
      <div className="modal wizard-modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Fermer">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6l-12 12"/></svg>
        </button>

        {success ? (
          <div className="modal-success wizard-success">
            <div className="check">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 13l4 4 10-10"/></svg>
            </div>
            <h3>C'est noté, {values.prenomParent}.</h3>
            <p>
              Notre directeur pédagogique vous rappelle <strong>{formatDateFR(values.date)} à {formatHeureFR(values.heure)}</strong> au {values.tel}.
            </p>
            <p className="wizard-success-sub">Un email récapitulatif arrive dans votre boîte dans quelques minutes.</p>
            {typeof WHATSAPP !== "undefined" && (
              <a
                href={`https://wa.me/${WHATSAPP.number}?text=${encodeURIComponent(WHATSAPP.defaultMessage)}`}
                target="_blank" rel="noopener noreferrer"
                className="btn btn-ghost wizard-success-wa"
              >
                Parlez directement au fondateur sur WhatsApp
              </a>
            )}
            <button className="btn btn-primary" onClick={onClose}>Fermer</button>
          </div>
        ) : (
          <React.Fragment>
            <div className="wizard-head">
              <div className="wizard-steps">
                {stepLabels.map((label, i) => {
                  const idx = i + 1;
                  const state = idx < step ? "done" : idx === step ? "active" : "todo";
                  return (
                    <div key={label} className={`wizard-step is-${state}`}>
                      <span className="wizard-step-dot">
                        {state === "done" ? (
                          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M5 13l4 4 10-10"/></svg>
                        ) : idx}
                      </span>
                      <span className="wizard-step-label">{label}</span>
                    </div>
                  );
                })}
              </div>
              <div className="wizard-progress"><span style={{ width: `${((step - 1) / 2) * 100}%` }} /></div>
            </div>

            <form onSubmit={submit} noValidate className="wizard-form">
              <div className={`wizard-panel wizard-panel-${step}`}>
                {step === 1 && (
                  <div className="wizard-step-body">
                    <h3>Parlez-nous de votre enfant.</h3>
                    <div className={`field ${errors.prenomEnfant ? "error" : ""}`}>
                      <label>Prénom de l'enfant</label>
                      <input type="text" value={values.prenomEnfant} onChange={e => set("prenomEnfant", e.target.value)} placeholder="Hugo" />
                      {errors.prenomEnfant && <div className="field-error-msg">{errors.prenomEnfant}</div>}
                    </div>
                    <div className={`field ${errors.niveau ? "error" : ""}`}>
                      <label>Niveau</label>
                      <select value={values.niveau} onChange={e => set("niveau", e.target.value)}>
                        <option value="">Sélectionner…</option>
                        {NIVEAUX.map(n => <option key={n} value={n}>{n}</option>)}
                      </select>
                      {errors.niveau && <div className="field-error-msg">{errors.niveau}</div>}
                    </div>
                    <div className={`field ${errors.matieres ? "error" : ""}`}>
                      <label>Matière(s) souhaitée(s)</label>
                      <div className="wizard-chips">
                        {SUBJECTS.map(s => (
                          <button type="button" key={s.name}
                            className={`matiere-chip${values.matieres.includes(s.name) ? " is-active" : ""}`}
                            onClick={() => toggleMatiere(s.name)}>
                            {s.name}
                          </button>
                        ))}
                      </div>
                      {errors.matieres && <div className="field-error-msg">{errors.matieres}</div>}
                    </div>
                    <div className={`field ${errors.objectif ? "error" : ""}`}>
                      <label>Objectif principal</label>
                      <div className="wizard-chips">
                        {OBJECTIFS.map(o => (
                          <button type="button" key={o}
                            className={`matiere-chip${values.objectif === o ? " is-active" : ""}`}
                            onClick={() => set("objectif", o)}>
                            {o}
                          </button>
                        ))}
                      </div>
                      {errors.objectif && <div className="field-error-msg">{errors.objectif}</div>}
                    </div>
                  </div>
                )}

                {step === 2 && (
                  <div className="wizard-step-body">
                    <h3>Comment vous joindre ?</h3>
                    <div className={`field ${errors.prenomParent ? "error" : ""}`}>
                      <label>Votre prénom</label>
                      <input type="text" value={values.prenomParent} onChange={e => set("prenomParent", e.target.value)} placeholder="Marie" />
                      {errors.prenomParent && <div className="field-error-msg">{errors.prenomParent}</div>}
                    </div>
                    <div className="field two-col">
                      <div className={`sub ${errors.tel ? "error" : ""}`}>
                        <label>Téléphone</label>
                        <input type="tel" value={values.tel} onChange={e => set("tel", e.target.value)} placeholder="06 00 00 00 00" />
                        {errors.tel && <div className="field-error-msg">{errors.tel}</div>}
                      </div>
                      <div className={`sub ${errors.email ? "error" : ""}`}>
                        <label>Email</label>
                        <input type="email" value={values.email} onChange={e => set("email", e.target.value)} placeholder="marie@exemple.fr" />
                        {errors.email && <div className="field-error-msg">{errors.email}</div>}
                      </div>
                    </div>
                  </div>
                )}

                {step === 3 && (
                  <div className="wizard-step-body">
                    <h3>Quand souhaitez-vous être rappelé ?</h3>
                    <div className={`field ${errors.date ? "error" : ""}`}>
                      <label>Jour</label>
                      <div className="wizard-chips">
                        {showTodayChip && (
                          <button type="button"
                            className={`matiere-chip${values.date === todayISO && !showCalendar ? " is-active" : ""}`}
                            onClick={() => { set("date", todayISO); set("heure", ""); setShowCalendar(false); }}>
                            Aujourd'hui
                          </button>
                        )}
                        <button type="button"
                          className={`matiere-chip${values.date === tomorrowISO && !showCalendar ? " is-active" : ""}`}
                          onClick={() => { set("date", tomorrowISO); set("heure", ""); setShowCalendar(false); }}>
                          Demain
                        </button>
                        <button type="button"
                          className={`matiere-chip${showCalendar || (values.date && !selectedIsQuick) ? " is-active" : ""}`}
                          onClick={() => setShowCalendar(s => !s)}>
                          {values.date && !selectedIsQuick ? formatDateFR(values.date) : "Choisir une date"}
                        </button>
                      </div>
                      {showCalendar && (
                        <CalendarPicker
                          value={values.date}
                          onChange={(iso) => { set("date", iso); set("heure", ""); setShowCalendar(false); }}
                        />
                      )}
                      {errors.date && <div className="field-error-msg">{errors.date}</div>}
                    </div>

                    <div className={`field ${errors.heure ? "error" : ""}`}>
                      <label>Heure précise</label>
                      <select value={values.heure} onChange={e => set("heure", e.target.value)} disabled={!values.date}>
                        <option value="">{values.date ? "Choisir un créneau…" : "Sélectionnez d'abord un jour"}</option>
                        {slots.map(s => <option key={s} value={s}>{formatHeureFR(s)}</option>)}
                      </select>
                      {values.date && slots.length === 0 && (
                        <div className="field-error-msg">Aucun créneau disponible aujourd'hui — choisissez demain.</div>
                      )}
                      {errors.heure && <div className="field-error-msg">{errors.heure}</div>}
                    </div>

                    <div className="field">
                      <label>Message (optionnel)</label>
                      <textarea value={values.message} onChange={e => set("message", e.target.value)} placeholder="Contraintes horaires, précisions…" />
                    </div>
                  </div>
                )}
              </div>

              <div className="wizard-nav">
                {step > 1 && (
                  <button type="button" className="btn btn-ghost" onClick={back}>← Retour</button>
                )}
                <div className="wizard-nav-spacer" />
                {step < 3 && (
                  <button type="button" className="btn btn-primary" onClick={next} data-cta="form-submit" data-step={step}>
                    Suivant <ArrowIcon />
                  </button>
                )}
                {step === 3 && (
                  <button type="submit" className="btn btn-primary" data-cta="form-submit" data-step="3" disabled={sending}>
                    {sending ? "Envoi en cours…" : <>Confirmer le rendez-vous <ArrowIcon /></>}
                  </button>
                )}
              </div>
              {submitError && (
                <div className="wizard-error" role="alert" style={{ marginTop: 12, color: "#b42318", fontSize: 14 }}>
                  {submitError}
                </div>
              )}
            </form>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

function Hero({ headline, variant, openModal }) {
  return (
    <section className="hero">
      <div className="wrap hero-grid">
        <div>
          <div className="hero-eyebrow">
            <span className="dot" />
            <span>Notre équipe est disponible · Lun–Sam 9h–20h</span>
          </div>
          <h1 dangerouslySetInnerHTML={{ __html: headline.replace(/grandes écoles/i, "<em>grandes écoles</em>") }} />
          <p className="lead">
            Cours particuliers à domicile à Paris — Collège, Lycée, Prépa, Médecine et Supérieur. Nos professeurs sont issus de HEC, Polytechnique, Sciences Po, ENS et des meilleures facultés de médecine.
          </p>
          <div className="hero-ctas">
            <button className="btn btn-primary btn-lg" onClick={openModal}>Prendre rendez-vous <ArrowIcon /></button>
            <a href={`tel:${PHONE.replace(/\s/g,"")}`} className="btn btn-ghost btn-lg"><PhoneIcon /> {PHONE}</a>
          </div>
          <div className="hero-note">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#22C55E" strokeWidth="2" strokeLinecap="round"><path d="M5 13l4 4 10-10"/></svg>
            <span>Sans engagement · 50% de crédit d'impôt · Rappel en 2h</span>
          </div>
        </div>
        <HeroVisual variant={variant} />
      </div>
    </section>
  );
}

function HeroVisual({ variant }) {
  return (
    <div className="hero-visual" data-variant={variant}>
      <div className="hero-canvas">
        {variant === "type" && (
          <div className="hero-type-content">
            <div className="hero-type-line">HEC.</div>
            <div className="hero-type-line">Polytechnique.</div>
            <div className="hero-type-line">Sciences Po.</div>
            <div className="hero-type-line">ENS.</div>
            <div className="hero-type-line muted">Au service de votre enfant.</div>
            <div className="hero-type-meta">
              <span>55 professeurs</span><span>Paris · 2026</span>
            </div>
          </div>
        )}
        {variant === "geo" && (
          <div className="hero-geo">
            <svg viewBox="0 0 400 400" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" style={{ position: "absolute", inset: 0 }}>
              <defs>
                <pattern id="grid" width="28" height="28" patternUnits="userSpaceOnUse">
                  <path d="M 28 0 L 0 0 0 28" fill="none" stroke="#D5DAE4" strokeWidth="0.5"/>
                </pattern>
              </defs>
              <rect width="400" height="400" fill="url(#grid)" opacity="0.6"/>
              <circle cx="200" cy="200" r="140" fill="none" stroke="#1B3A6B" strokeWidth="1.5" opacity="0.25"/>
              <circle cx="200" cy="200" r="90" fill="none" stroke="#1B3A6B" strokeWidth="1.5" opacity="0.4"/>
              <circle cx="200" cy="200" r="44" fill="#1B3A6B"/>
              <text x="200" y="195" textAnchor="middle" fill="#fff" fontFamily="Inter" fontSize="10" fontWeight="600" letterSpacing="1">VOTRE</text>
              <text x="200" y="210" textAnchor="middle" fill="#fff" fontFamily="Inter" fontSize="10" fontWeight="600" letterSpacing="1">ENFANT</text>
              <circle cx="90"  cy="110" r="26" fill="#fff" stroke="#E5E8EF"/>
              <text x="90"  y="114" textAnchor="middle" fill="#1B3A6B" fontFamily="Inter" fontSize="10" fontWeight="700">HEC</text>
              <circle cx="310" cy="110" r="26" fill="#fff" stroke="#E5E8EF"/>
              <text x="310" y="114" textAnchor="middle" fill="#1B3A6B" fontFamily="Inter" fontSize="9" fontWeight="700">X</text>
              <circle cx="80"  cy="290" r="26" fill="#fff" stroke="#E5E8EF"/>
              <text x="80"  y="294" textAnchor="middle" fill="#1B3A6B" fontFamily="Inter" fontSize="8" fontWeight="700">ENS</text>
              <circle cx="320" cy="290" r="26" fill="#fff" stroke="#E5E8EF"/>
              <text x="320" y="294" textAnchor="middle" fill="#1B3A6B" fontFamily="Inter" fontSize="7" fontWeight="700">SC.PO</text>
              <line x1="114" y1="120" x2="158" y2="178" stroke="#1B3A6B" strokeWidth="1" strokeDasharray="3 3" opacity="0.4"/>
              <line x1="286" y1="120" x2="242" y2="178" stroke="#1B3A6B" strokeWidth="1" strokeDasharray="3 3" opacity="0.4"/>
              <line x1="104" y1="278" x2="158" y2="222" stroke="#1B3A6B" strokeWidth="1" strokeDasharray="3 3" opacity="0.4"/>
              <line x1="296" y1="278" x2="242" y2="222" stroke="#1B3A6B" strokeWidth="1" strokeDasharray="3 3" opacity="0.4"/>
            </svg>
          </div>
        )}
        {variant === "schools" && (
          <React.Fragment>
            {SCHOOLS.map((s, i) => (
              <div key={s.name} className={`hero-school-card sc-${i+1}`}>
                <div className="sc-name">{s.name}</div>
                <div className="sc-meta"><span className="sc-dot" /> {s.count} professeurs</div>
              </div>
            ))}
            <div className="hero-center-badge">
              <div>
                <div className="hcb-num">55</div>
                <div className="hcb-label">Professeurs · Paris</div>
              </div>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

function TrustBar() {
  return (
    <section className="trust-bar">
      <div className="wrap trust-inner">
        <div className="trust-label">Nos professeurs viennent de</div>
        <div className="trust-schools">
          {SCHOOLS.map(s => (
            <div key={s.name} className="trust-chip">
              <span>{s.name}</span>
              <span className="count">{s.count} profs</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Pillars() {
  return (
    <section className="section">
      <div className="wrap">
        <div className="sec-head">
          <div className="left">
            <Eyebrow>Pourquoi Cours Edgar</Eyebrow>
            <h2>Trois piliers qui font la différence.</h2>
          </div>
          <p className="lead" style={{ maxWidth: 380 }}>
            Nous ne faisons pas du soutien scolaire générique. Nous faisons du matching sur-mesure entre des étudiants d'élite et votre enfant.
          </p>
        </div>
        <div className="pillars">
          {PILLARS.map((p, i) => (
            <Reveal key={p.title} delay={i * 80}>
              <div className="pillar">
                <div className="num">0{i+1}</div>
                <div className="icon">{p.icon}</div>
                <h3>{p.title}</h3>
                <p>{p.body}</p>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function HowItWorks() {
  return (
    <section className="section">
      <div className="wrap">
        <div className="steps">
          <div className="steps-head">
            <Eyebrow>Comment ça marche</Eyebrow>
            <h2>De votre premier appel au premier cours : 24h.</h2>
          </div>
          <div className="steps-grid">
            {STEPS.map((s, i) => (
              <div key={s.title} className="step">
                <div className="step-num">0{i+1} / 04</div>
                <h4>{s.title}</h4>
                <p>{s.body}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function StatsSection() {
  return (
    <section className="section-sm">
      <div className="wrap">
        <div className="stats">
          {STATS.map(s => (
            <div key={s.label} className="stat">
              <div className="stat-num">{s.num}<span>{s.suffix}</span></div>
              <div className="stat-label">{s.label}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function TestimonialsSection() {
  return (
    <section className="section">
      <div className="wrap">
        <div className="sec-head">
          <div className="left">
            <Eyebrow>Paroles de parents</Eyebrow>
            <h2>Ils nous ont fait confiance.</h2>
          </div>
        </div>
        <div className="testimonials">
          {TESTIMONIALS.map((t, i) => (
            <Reveal key={t.name} delay={i * 80}>
              <div className="testimonial">
                <Stars value={5} />
                <div className="quote">« {t.quote} »</div>
                <div className="author">
                  <div className={`avatar ${t.v}`}>{t.avatar}</div>
                  <div className="author-meta">
                    <div className="name">{t.name}</div>
                    <div className="sub">{t.sub}</div>
                  </div>
                </div>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function SubjectsSection() {
  return (
    <section className="section">
      <div className="wrap">
        <div className="sec-head">
          <div className="left">
            <Eyebrow>Matières enseignées</Eyebrow>
            <h2>Du collège à la prépa, toutes matières couvertes.</h2>
          </div>
        </div>
        <div className="subjects">
          {SUBJECTS.map(s => (
            <div key={s.name} className="subject">
              <div className="sub-ic">{s.tag}</div>
              <div>
                <h5>{s.name}</h5>
                <p>{s.note}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function FAQSection({ items, title = "Questions fréquentes" }) {
  const list = items || FAQS;
  const [open, setOpen] = useState(0);
  return (
    <section className="section">
      <div className="wrap">
        <div className="sec-head" style={{ justifyContent: "center", textAlign: "center", flexDirection: "column", alignItems: "center" }}>
          <div className="left">
            <Eyebrow>FAQ</Eyebrow>
            <h2>{title}</h2>
          </div>
        </div>
        <div className="faq">
          {list.map((item, i) => (
            <div key={i} className={`faq-item ${open === i ? "open" : ""}`}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)} aria-expanded={open === i}>
                <span>{item.q}</span>
                <span className="faq-icon">
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M12 5v14M5 12h14"/></svg>
                </span>
              </button>
              <div className="faq-a" style={{ maxHeight: open === i ? 400 : 0 }}>
                <div className="faq-a-inner">{item.a}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function CTABand({ openModal }) {
  return (
    <section className="section-sm">
      <div className="wrap">
        <div className="cta-band">
          <div>
            <h2>Trouvons le professeur idéal pour votre enfant.</h2>
            <p>Un appel de 10 minutes pour comprendre vos besoins. Un prof proposé sous 24h.</p>
          </div>
          <button className="btn btn-accent btn-lg" onClick={openModal}>Prendre rendez-vous <ArrowIcon /></button>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  Stars, Reveal, Eyebrow, PhoneIcon, ArrowIcon,
  Header, StickyCTA, Footer, Modal,
  Hero, TrustBar, Pillars, HowItWorks, StatsSection,
  TestimonialsSection, SubjectsSection, FAQSection, CTABand,
});
