// rdv.jsx — Page Rendez-vous 2C ITECH
const { useState: useStateR, useEffect: useEffectR, useMemo: useMemoR } = React;

const PRIX_DIAG = 49;

function RdvPage() {
  return (
    <>
      <UrgenceBar level="medium" />
      <Header active="rdv" />
      <main>
        <BookingFlow prixDiag={PRIX_DIAG} />
      </main>
      <Footer />
      <ChatBubble />
    </>
  );
}

function BookingFlow({ prixDiag }) {
  const params = new URLSearchParams(location.search);
  const presetBesoin = params.get("besoin") || "";

  const [step, setStep] = useStateR(1);
  const [besoin, setBesoin] = useStateR(presetBesoin);
  const [date, setDate] = useStateR(null);
  const [slot, setSlot] = useStateR(null);
  const [priority, setPriority] = useStateR(false);
  const [info, setInfo] = useStateR({ nom: "", email: "", telephone: "", message: "" });
  const [confirmed, setConfirmed] = useStateR(false);
  const [submitting, setSubmitting] = useStateR(false);

  const needsPayment = priority && !["depannage", "installation", "autre"].includes(besoin);

  const submit = async (e) => {
    e?.preventDefault();
    setSubmitting(true);
    try {
      await fetch("/api/rdv", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          nom: info.nom,
          email: info.email,
          telephone: info.telephone,
          message: info.message,
          besoin,
          date: date ? date.toISOString().split("T")[0] : null,
          heure: slot,
          prioritaire: priority,
        }),
      });
    } catch (err) {
      console.error("RDV submit error", err);
    }
    setSubmitting(false);
    setConfirmed(true);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  if (confirmed) return <ConfirmedScreen besoin={besoin} date={date} slot={slot} info={info} priority={priority} />;

  return (
    <section style={{ paddingBlock: 60 }}>
      <div className="container">
        <div className="rdv-head">
          <span className="eyebrow">Prise de rendez-vous</span>
          <h1 className="h-display" style={{ marginTop: 12, fontSize: "clamp(40px, 5vw, 64px)" }}>
            Choisissez votre créneau —<br /><em>30 min, sans engagement.</em>
          </h1>
        </div>
        <div className="rdv-stepper">
          <Step n={1} label="Besoin" active={step === 1} done={step > 1} onClick={() => setStep(1)} />
          <Step n={2} label="Créneau" active={step === 2} done={step > 2} onClick={() => step > 1 && setStep(2)} />
          <Step n={3} label="Vos infos" active={step === 3} done={false} onClick={() => step > 2 && setStep(3)} />
        </div>
        <div className="rdv-grid">
          <div className="rdv-main">
            {step === 1 && <StepBesoin besoin={besoin} setBesoin={setBesoin} onNext={() => setStep(2)} />}
            {step === 2 && <StepSlot date={date} setDate={setDate} slot={slot} setSlot={setSlot} priority={priority} setPriority={setPriority} besoin={besoin} onNext={() => setStep(3)} prixDiag={prixDiag} />}
            {step === 3 && <StepInfo info={info} setInfo={setInfo} onSubmit={submit} needsPayment={needsPayment} prixDiag={prixDiag} submitting={submitting} />}
          </div>
          <aside className="rdv-summary">
            <div className="sum-head">
              <span className="mono" style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-3)" }}>Récapitulatif</span>
              <h3 style={{ fontSize: 18, marginTop: 6, marginBottom: 0 }}>Votre rendez-vous</h3>
            </div>
            <ul className="sum-list">
              <li><span>Type</span><b>{labelBesoin(besoin) || "—"}</b></li>
              <li><span>Date</span><b>{date ? formatDateLong(date) : "—"}</b></li>
              <li><span>Heure</span><b>{slot || "—"}</b></li>
              <li><span>Format</span><b>{priority ? "Prioritaire 24h" : "Standard"}</b></li>
            </ul>
            <hr className="divider" />
            <div className="sum-price">
              <span>{priority && needsPayment ? "Diagnostic prioritaire" : "Premier RDV"}</span>
              <b>{priority && needsPayment ? `${prixDiag}€` : "Gratuit"}</b>
            </div>
            {priority && needsPayment && (
              <p className="muted" style={{ fontSize: 12, marginTop: 8 }}>Paiement sécurisé · 100% remboursable jusqu'à 24h avant</p>
            )}
            <div className="sum-foot">
              <a href="tel:+33500000000" className="btn-link" style={{ display: "inline-flex", gap: 6, alignItems: "center", fontSize: 13 }}>
                <PhoneIcon /> Préférez-vous appeler ? 05 00 00 00 00
              </a>
            </div>
          </aside>
        </div>
      </div>
      <style>{`
        .rdv-head { text-align: center; margin-bottom: 40px; }
        .rdv-stepper { display: flex; gap: 0; justify-content: center; margin-bottom: 40px; flex-wrap: wrap; }
        .rdv-step { display: flex; align-items: center; gap: 10px; padding: 8px 16px; border-radius: 999px; cursor: pointer; color: var(--ink-3); font-size: 14px; font-weight: 500; background: transparent; border: 0; }
        .rdv-step .num { width: 24px; height: 24px; border-radius: 50%; background: var(--line); display: grid; place-items: center; font-family: var(--font-mono); font-size: 12px; }
        .rdv-step.active { background: var(--bg-deep); color: white; }
        .rdv-step.active .num { background: var(--accent); color: white; }
        .rdv-step.done { color: var(--success); }
        .rdv-step.done .num { background: var(--success); color: white; }
        .rdv-step + .rdv-step::before { content: ""; width: 24px; height: 1px; background: var(--line-strong); margin-right: 8px; align-self: center; }
        .rdv-grid { display: grid; grid-template-columns: 1.5fr 1fr; gap: 32px; align-items: start; }
        @media (max-width: 920px) { .rdv-grid { grid-template-columns: 1fr; } }
        .rdv-main { background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius-lg); padding: 36px; }
        .rdv-summary { position: sticky; top: 90px; background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius-lg); padding: 28px; }
        .sum-list { list-style: none; padding: 0; margin: 20px 0; display: flex; flex-direction: column; gap: 10px; font-size: 14px; }
        .sum-list li { display: flex; justify-content: space-between; gap: 12px; }
        .sum-list span { color: var(--ink-3); }
        .sum-list b { font-weight: 500; text-align: right; }
        .sum-price { display: flex; justify-content: space-between; align-items: baseline; margin-top: 16px; }
        .sum-price b { font-family: var(--font-serif); font-size: 32px; font-weight: 400; color: var(--accent); }
        .sum-foot { margin-top: 20px; padding-top: 16px; border-top: 1px dashed var(--line); }
      `}</style>
    </section>
  );
}

function Step({ n, label, active, done, onClick }) {
  return (
    <button className={`rdv-step ${active ? "active" : ""} ${done ? "done" : ""}`} onClick={onClick} type="button">
      <span className="num">{done ? "✓" : n}</span>
      <span>{label}</span>
    </button>
  );
}

function StepBesoin({ besoin, setBesoin, onNext }) {
  const opts = [
    { v: "facturation", t: "Facturation électronique 2026", d: "Diagnostic + plan de mise en conformité", icon: "📋", featured: true },
    { v: "ia", t: "Automatisation / IA", d: "Gagner du temps sur devis, factures, emails", icon: "⚡", featured: true },
    { v: "depannage", t: "Dépannage informatique", d: "PC, imprimante, réseau, virus, lenteurs", icon: "🔧" },
    { v: "maintenance", t: "Maintenance / abonnement", d: "Support illimité, sauvegarde, surveillance", icon: "🛡" },
    { v: "installation", t: "Installation matériel/logiciel", d: "Nouveau PC, NAS, suite Microsoft 365", icon: "📦" },
    { v: "autre", t: "Autre besoin", d: "Décrivez-nous votre situation", icon: "?" },
  ];
  return (
    <>
      <h2 className="h2">1. Quel est votre besoin ?</h2>
      <p className="muted" style={{ fontSize: 14, marginTop: 4 }}>Pour préparer le rendez-vous au plus juste.</p>
      <div className="bes-grid">
        {opts.map(o => (
          <button key={o.v} type="button" className={`bes-opt ${besoin === o.v ? "sel" : ""} ${o.featured ? "fea" : ""}`} onClick={() => setBesoin(o.v)}>
            <span className="bes-ic">{o.icon}</span>
            <div><b>{o.t}</b><span>{o.d}</span></div>
            <span className="bes-check">{besoin === o.v && "✓"}</span>
          </button>
        ))}
      </div>
      <div className="row" style={{ marginTop: 28, justifyContent: "flex-end" }}>
        <button type="button" className="btn btn-primary" disabled={!besoin} style={{ opacity: besoin ? 1 : 0.4 }} onClick={onNext}>
          Continuer <span className="arrow">→</span>
        </button>
      </div>
      <style>{`
        .bes-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-top: 24px; }
        @media (max-width: 600px) { .bes-grid { grid-template-columns: 1fr; } }
        .bes-opt { background: var(--bg); border: 1px solid var(--line); border-radius: var(--radius); padding: 18px; display: flex; gap: 14px; align-items: flex-start; text-align: left; cursor: pointer; transition: border-color .15s, transform .15s; position: relative; }
        .bes-opt:hover { border-color: var(--accent); transform: translateY(-1px); }
        .bes-opt.sel { border-color: var(--accent); background: var(--accent-soft); }
        .bes-opt.fea::after { content: "Cœur de métier"; position: absolute; top: 8px; right: 12px; font-family: var(--font-mono); font-size: 9px; letter-spacing: 0.12em; text-transform: uppercase; color: var(--accent); }
        .bes-ic { width: 36px; height: 36px; border-radius: 8px; background: var(--bg-elev); display: grid; place-items: center; font-size: 18px; flex-shrink: 0; }
        .bes-opt b { display: block; font-size: 14px; font-weight: 600; }
        .bes-opt span:nth-of-type(2) { display: block; font-size: 13px; color: var(--ink-3); margin-top: 2px; }
        .bes-check { position: absolute; bottom: 12px; right: 14px; color: var(--accent); font-weight: 700; }
      `}</style>
    </>
  );
}

const TZ_HOURS = ["10:00", "11:30", "14:00", "15:30", "17:00"];

function getNextDays(count = 8) {
  const days = [];
  let d = new Date();
  d.setHours(0, 0, 0, 0);
  while (days.length < count) {
    d.setDate(d.getDate() + 1);
    const day = d.getDay();
    if (day === 2 || day === 3 || day === 4) days.push(new Date(d));
  }
  return days;
}

function remainingForDay(d) {
  const seed = d.getDate() + d.getMonth();
  return ((seed * 7) % 5) + 1;
}
function takenForDay(d) {
  const seed = (d.getDate() * 13 + d.getMonth() * 7) % 5;
  const idxs = [seed, (seed + 2) % 5];
  return idxs.slice(0, 5 - remainingForDay(d));
}
function formatDateLong(d) { return d.toLocaleDateString("fr-FR", { weekday: "long", day: "numeric", month: "long" }); }

function StepSlot({ date, setDate, slot, setSlot, priority, setPriority, besoin, onNext, prixDiag }) {
  const days = useMemoR(() => getNextDays(8), []);
  const canPay = !["depannage", "installation", "autre"].includes(besoin);
  return (
    <>
      <h2 className="h2">2. Choisissez votre créneau</h2>
      <p className="muted" style={{ fontSize: 14, marginTop: 4 }}>5 créneaux par jour — mardi, mercredi, jeudi.</p>
      <div className="cal-days">
        {days.map((d, i) => {
          const remaining = remainingForDay(d);
          const sel = date && date.toDateString() === d.toDateString();
          return (
            <button key={i} type="button" className={`cal-day ${sel ? "sel" : ""} ${remaining === 0 ? "full" : ""}`} disabled={remaining === 0} onClick={() => { setDate(d); setSlot(null); }}>
              <span className="cd-day">{d.toLocaleDateString("fr-FR", { weekday: "short" })}</span>
              <span className="cd-num">{d.getDate()}</span>
              <span className="cd-month">{d.toLocaleDateString("fr-FR", { month: "short" })}</span>
              <span className={`cd-left ${remaining <= 2 ? "low" : ""}`}>{remaining === 0 ? "Complet" : `${remaining} restant${remaining > 1 ? "s" : ""}`}</span>
            </button>
          );
        })}
      </div>
      {date && (
        <div className="cal-slots">
          <div className="cs-head">
            <b>{formatDateLong(date)}</b>
            <span className="muted" style={{ fontSize: 13 }}>{remainingForDay(date)} créneaux disponibles</span>
          </div>
          <div className="cs-grid">
            {TZ_HOURS.map((h, i) => {
              const taken = takenForDay(date).includes(i);
              const sel = slot === h;
              return (
                <button key={h} type="button" disabled={taken} className={`cs-slot ${sel ? "sel" : ""} ${taken ? "taken" : ""}`} onClick={() => setSlot(h)}>
                  {h}{taken && <span>Pris</span>}
                </button>
              );
            })}
          </div>
        </div>
      )}
      {canPay && (
        <div className="prio-card">
          <label className="prio-row">
            <input type="checkbox" checked={priority} onChange={e => setPriority(e.target.checked)} />
            <div>
              <b>🔥 Créneau prioritaire (sous 24h)</b>
              <span>Paiement Diagnostic Express ({prixDiag}€) — places limitées, déduit du pack si vous donnez suite. Remboursable 24h avant.</span>
            </div>
            <span className="prio-tag">+{prixDiag}€</span>
          </label>
        </div>
      )}
      <div className="row" style={{ marginTop: 28, justifyContent: "flex-end" }}>
        <button type="button" className="btn btn-primary" disabled={!date || !slot} style={{ opacity: (date && slot) ? 1 : 0.4 }} onClick={onNext}>
          Continuer <span className="arrow">→</span>
        </button>
      </div>
      <style>{`
        .cal-days { display: grid; grid-template-columns: repeat(8, 1fr); gap: 8px; margin-top: 24px; }
        @media (max-width: 820px) { .cal-days { grid-template-columns: repeat(4, 1fr); } }
        .cal-day { background: var(--bg); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px 8px; display: flex; flex-direction: column; align-items: center; gap: 4px; cursor: pointer; transition: border-color .15s; }
        .cal-day:hover:not(.full) { border-color: var(--accent); }
        .cal-day.sel { background: var(--bg-deep); color: white; border-color: var(--bg-deep); }
        .cal-day.full { opacity: 0.4; cursor: not-allowed; }
        .cd-day { font-size: 11px; text-transform: uppercase; letter-spacing: 0.1em; color: var(--ink-3); font-family: var(--font-mono); }
        .cal-day.sel .cd-day { color: rgba(255,255,255,0.6); }
        .cd-num { font-family: var(--font-serif); font-size: 32px; line-height: 1; }
        .cd-month { font-size: 11px; text-transform: uppercase; color: var(--ink-3); font-family: var(--font-mono); letter-spacing: 0.1em; }
        .cal-day.sel .cd-month { color: rgba(255,255,255,0.6); }
        .cd-left { font-size: 11px; padding: 3px 8px; border-radius: 999px; background: rgba(31,138,91,0.12); color: var(--success); margin-top: 4px; }
        .cd-left.low { background: rgba(255,106,26,0.15); color: var(--accent); }
        .cal-day.sel .cd-left { background: rgba(255,255,255,0.15); color: white; }
        .cal-slots { margin-top: 24px; padding: 20px; background: var(--bg); border-radius: var(--radius); border: 1px solid var(--line); }
        .cs-head { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 14px; }
        .cs-head b { font-family: var(--font-serif); font-size: 20px; text-transform: capitalize; font-weight: 400; }
        .cs-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 8px; }
        @media (max-width: 600px) { .cs-grid { grid-template-columns: repeat(2, 1fr); } }
        .cs-slot { padding: 14px; background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius); font-weight: 600; cursor: pointer; transition: border-color .15s; display: flex; flex-direction: column; gap: 2px; align-items: center; }
        .cs-slot:hover:not(.taken) { border-color: var(--accent); }
        .cs-slot.sel { background: var(--accent); color: white; border-color: var(--accent); }
        .cs-slot.taken { opacity: 0.4; cursor: not-allowed; }
        .cs-slot.taken span { font-size: 10px; font-weight: 400; color: var(--ink-3); text-transform: uppercase; letter-spacing: 0.1em; }
        .prio-card { margin-top: 24px; background: linear-gradient(90deg, var(--accent-soft), var(--bg)); border: 1px solid var(--accent); border-radius: var(--radius); padding: 18px; }
        .prio-row { display: flex; gap: 14px; align-items: flex-start; cursor: pointer; }
        .prio-row input { width: 18px; height: 18px; flex-shrink: 0; margin-top: 4px; accent-color: var(--accent); }
        .prio-row b { display: block; font-size: 14px; }
        .prio-row span { display: block; font-size: 13px; color: var(--ink-3); margin-top: 4px; }
        .prio-tag { margin-left: auto; background: var(--accent); color: white; padding: 6px 12px; border-radius: 999px; font-weight: 600; font-size: 13px; flex-shrink: 0; }
      `}</style>
    </>
  );
}

function StepInfo({ info, setInfo, onSubmit, needsPayment, prixDiag, submitting }) {
  return (
    <form onSubmit={onSubmit}>
      <h2 className="h2">3. Vos coordonnées</h2>
      <p className="muted" style={{ fontSize: 14, marginTop: 4 }}>Ces informations restent confidentielles.</p>
      <div className="form-grid">
        <div><label>Nom complet *</label><input type="text" required value={info.nom} onChange={e => setInfo({ ...info, nom: e.target.value })} placeholder="Marie Lacombe" /></div>
        <div><label>Email *</label><input type="email" required value={info.email} onChange={e => setInfo({ ...info, email: e.target.value })} placeholder="vous@entreprise.fr" /></div>
        <div><label>Téléphone *</label><input type="tel" required value={info.telephone} onChange={e => setInfo({ ...info, telephone: e.target.value })} placeholder="06 00 00 00 00" /></div>
        <div><label>Entreprise</label><input type="text" value={info.entreprise || ""} onChange={e => setInfo({ ...info, entreprise: e.target.value })} placeholder="optionnel" /></div>
        <div className="full"><label>Décrivez brièvement votre situation</label><textarea rows="4" value={info.message} onChange={e => setInfo({ ...info, message: e.target.value })} placeholder="Quelques mots — pas besoin d'être exhaustif." /></div>
      </div>
      {needsPayment && (
        <div className="pay-card">
          <div className="pay-head"><span className="chip accent">🔥 Prioritaire</span><b>Diagnostic Express — {prixDiag}€</b></div>
          <div className="pay-method">
            <div className="pay-row"><span>Carte bancaire</span><span className="brands">VISA · Mastercard · Amex</span></div>
            <div className="pay-row"><span>Sécurisé par</span><span className="mono" style={{ color: "#635BFF" }}>Stripe</span></div>
            <div className="pay-row"><span>Remboursement</span><span>24h avant — 100%</span></div>
          </div>
        </div>
      )}
      <div className="row" style={{ marginTop: 28, justifyContent: "flex-end" }}>
        <button type="submit" className="btn btn-primary" disabled={submitting}>
          {submitting ? "Envoi en cours…" : (needsPayment ? `Payer ${prixDiag}€ et confirmer` : "Confirmer le rendez-vous")} <span className="arrow">→</span>
        </button>
      </div>
      <p className="muted" style={{ fontSize: 12, marginTop: 16, textAlign: "right" }}>En confirmant, vous acceptez d'être contacté pour ce rendez-vous. Aucun spam.</p>
      <style>{`
        .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-top: 20px; }
        .form-grid .full { grid-column: 1 / -1; }
        @media (max-width: 600px) { .form-grid { grid-template-columns: 1fr; } }
        .pay-card { margin-top: 24px; padding: 20px; background: var(--bg); border: 1px solid var(--line); border-radius: var(--radius); }
        .pay-head { display: flex; align-items: center; gap: 12px; }
        .pay-head b { font-family: var(--font-serif); font-size: 22px; font-weight: 400; }
        .pay-method { margin-top: 16px; display: flex; flex-direction: column; gap: 8px; }
        .pay-row { display: flex; justify-content: space-between; font-size: 13px; padding: 8px 0; border-top: 1px dashed var(--line); }
        .pay-row .brands { font-family: var(--font-mono); font-size: 12px; color: var(--ink-3); }
      `}</style>
    </form>
  );
}

function ConfirmedScreen({ besoin, date, slot, info, priority }) {
  return (
    <section style={{ paddingBlock: 80 }}>
      <div className="container" style={{ maxWidth: 720, textAlign: "center" }}>
        <div style={{ width: 80, height: 80, borderRadius: "50%", background: "var(--success)", color: "white", display: "grid", placeItems: "center", margin: "0 auto", fontSize: 40 }}>✓</div>
        <h1 className="h-display" style={{ marginTop: 24, fontSize: "clamp(36px, 5vw, 56px)" }}>
          C'est confirmé,<br /><em>{info.nom?.split(" ")[0] || "merci"}.</em>
        </h1>
        <p className="lede" style={{ margin: "20px auto 0" }}>
          Vous recevrez un email de confirmation sur <b>{info.email}</b> dans les minutes qui viennent.
        </p>
        <div className="conf-card">
          <div className="conf-row"><span>Date</span><b>{date && formatDateLong(date)}</b></div>
          <div className="conf-row"><span>Heure</span><b>{slot}</b></div>
          <div className="conf-row"><span>Type</span><b>{labelBesoin(besoin)}</b></div>
          <div className="conf-row"><span>Format</span><b>{priority ? "Prioritaire 24h" : "Standard"}</b></div>
          <div className="conf-row"><span>Lieu</span><b>Visio + numéro envoyé par mail</b></div>
        </div>
        <div className="row" style={{ justifyContent: "center", marginTop: 32 }}>
          <a href="/index.html" className="btn btn-dark">← Retour à l'accueil</a>
        </div>
        <style>{`
          .conf-card { background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius-lg); padding: 28px; margin-top: 32px; text-align: left; }
          .conf-row { display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px dashed var(--line); }
          .conf-row:last-child { border-bottom: 0; }
          .conf-row span { color: var(--ink-3); }
          .conf-row b { font-weight: 500; text-transform: capitalize; }
        `}</style>
      </div>
    </section>
  );
}

function labelBesoin(b) {
  return ({ facturation: "Facturation 2026", ia: "Automatisation / IA", depannage: "Dépannage", maintenance: "Maintenance / abonnement", installation: "Installation", autre: "Autre", conformite: "Pack Conformité", diagnostic: "Diagnostic Express", assistance: "Assistance à distance", sauvegarde: "Sauvegarde" })[b] || "";
}

Object.assign(window, { RdvPage });
