/* global React */
// Booking flow — multi-step modal/inline: service → date → time → infos → confirm

const BookingFlow = ({ compact = false }) => {
  const [step, setStep] = React.useState(0);
  const [service, setService] = React.useState(null);
  const [date, setDate] = React.useState(null);
  const [time, setTime] = React.useState(null);
  const [infos, setInfos] = React.useState({
    prenom: 'Claire', nom: 'Lefèvre', email: 'claire.lefevre@proton.me', tel: '+32 478 12 34 56', note: '', consent: true,
  });

  const services = window.SERVICES;

  // Calendar state — fixed "current" date for mock
  const TODAY = new Date(2026, 4, 18); // May 18, 2026 (Mon)
  const [viewMonth, setViewMonth] = React.useState(new Date(2026, 4, 1));

  const steps = ['Soin', 'Date', 'Coordonnées', 'Confirmation'];

  const canNext = () => {
    if (step === 0) return service !== null;
    if (step === 1) return date !== null && time !== null;
    if (step === 2) return infos.prenom && infos.email && infos.tel && infos.consent;
    return false;
  };

  const monthName = viewMonth.toLocaleDateString('fr-FR', { month: 'long', year: 'numeric' });
  const daysInMonth = new Date(viewMonth.getFullYear(), viewMonth.getMonth() + 1, 0).getDate();
  // Monday-first index of 1st
  const firstDow = (new Date(viewMonth.getFullYear(), viewMonth.getMonth(), 1).getDay() + 6) % 7;

  const isPast = (d) => {
    const dt = new Date(viewMonth.getFullYear(), viewMonth.getMonth(), d);
    return dt < new Date(TODAY.getFullYear(), TODAY.getMonth(), TODAY.getDate());
  };
  const dowOf = (d) => (new Date(viewMonth.getFullYear(), viewMonth.getMonth(), d).getDay() + 6) % 7;
  // Closed: Mon (0) + Tue (1). Open wed morning, thu/fri full, sat full, sun off.
  const isClosedDay = (d) => {
    const dow = dowOf(d);
    return dow === 0 || dow === 1 || dow === 6;
  };
  const timeSlotsFor = (dow) => {
    if (dow === 2) return ['09:00', '10:30']; // wed morning
    if (dow === 3 || dow === 4) return ['10:00', '11:30', '14:00', '15:30', '17:00'];
    if (dow === 5) return ['09:30', '11:00', '13:00', '14:30', '16:00', '17:30'];
    return [];
  };
  const bookedSlots = new Set(['14:00', '17:00']); // mock taken slots
  const dowLabels = ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim'];

  const days = [];
  for (let i = 0; i < firstDow; i++) days.push({ empty: true, key: 'e' + i });
  for (let d = 1; d <= daysInMonth; d++) {
    const isToday = d === TODAY.getDate() && viewMonth.getMonth() === TODAY.getMonth();
    days.push({
      key: 'd' + d,
      d,
      disabled: isPast(d) || isClosedDay(d),
      today: isToday,
    });
  }

  const selectedDow = date ? dowOf(date) : null;
  const availableTimes = selectedDow !== null ? timeSlotsFor(selectedDow) : [];

  const reset = () => {
    setStep(0); setService(null); setDate(null); setTime(null);
  };

  const formatDateLong = (d) => {
    if (!d) return '';
    const dt = new Date(viewMonth.getFullYear(), viewMonth.getMonth(), d);
    return dt.toLocaleDateString('fr-FR', { weekday: 'long', day: 'numeric', month: 'long' });
  };

  return (
    <div className="booking-form">
      <div className="stepper">
        {steps.map((s, i) => (
          <div key={s} className={`step ${i === step ? 'active' : ''} ${i < step ? 'done' : ''}`} />
        ))}
      </div>

      <div className="step-header">
        <span className="count">Étape {step + 1} / {steps.length}</span>
        {step > 0 && step < 3 && (
          <button className="back" onClick={() => setStep(step - 1)}>← Retour</button>
        )}
      </div>

      {step === 0 && (
        <>
          <div className="step-title">Quel soin vous fait envie ?</div>
          <div className="svc-picker">
            {services.map((s, i) => (
              <button
                key={s.name}
                className={`svc-option ${service === i ? 'selected' : ''}`}
                onClick={() => setService(i)}
              >
                <div>
                  <div className="n">{s.name}</div>
                  <div className="d">{s.duration} · {s.short}</div>
                </div>
                <div className="p">{s.price}€</div>
              </button>
            ))}
          </div>
        </>
      )}

      {step === 1 && (
        <>
          <div className="step-title">Choisissez un créneau</div>
          <div className="cal">
            <div className="cal-head">
              <button className="nav-btn" onClick={() => setViewMonth(new Date(viewMonth.getFullYear(), viewMonth.getMonth() - 1, 1))}
                disabled={viewMonth.getMonth() <= TODAY.getMonth() && viewMonth.getFullYear() <= TODAY.getFullYear()}>‹</button>
              <div className="mo">{monthName}</div>
              <button className="nav-btn" onClick={() => setViewMonth(new Date(viewMonth.getFullYear(), viewMonth.getMonth() + 1, 1))}>›</button>
            </div>
            <div className="cal-grid">
              {dowLabels.map((l) => <div key={l} className="cal-dow">{l}</div>)}
              {days.map((x) => x.empty ? (
                <div key={x.key} className="cal-day empty" />
              ) : (
                <button
                  key={x.key}
                  className={`cal-day ${x.disabled ? 'unavailable' : ''} ${x.today ? 'today' : ''} ${date === x.d ? 'selected' : ''}`}
                  onClick={() => !x.disabled && (setDate(x.d), setTime(null))}
                  disabled={x.disabled}
                >{x.d}</button>
              ))}
            </div>
            {date !== null && (
              <>
                <div className="cal-times">
                  {availableTimes.map((t) => {
                    const taken = bookedSlots.has(t) && date === 20;
                    return (
                      <button key={t}
                        className={`cal-time ${time === t ? 'selected' : ''}`}
                        onClick={() => !taken && setTime(t)}
                        disabled={taken}>{t}</button>
                    );
                  })}
                </div>
              </>
            )}
          </div>
        </>
      )}

      {step === 2 && (
        <>
          <div className="step-title">Vos coordonnées</div>
          <div className="recap">
            <div className="recap-row">
              <span className="k">Soin</span>
              <span className="v">{services[service].name}</span>
            </div>
            <div className="recap-row">
              <span className="k">Date</span>
              <span className="v">{formatDateLong(date)} · {time}</span>
            </div>
            <div className="recap-row">
              <span className="k">Total</span>
              <span className="v">{services[service].price}€</span>
            </div>
          </div>
          <div className="fields">
            <div className="field-row">
              <div className="field">
                <label>Prénom</label>
                <input value={infos.prenom} onChange={(e) => setInfos({...infos, prenom: e.target.value})} />
              </div>
              <div className="field">
                <label>Nom</label>
                <input value={infos.nom} onChange={(e) => setInfos({...infos, nom: e.target.value})} />
              </div>
            </div>
            <div className="field">
              <label>Email</label>
              <input type="email" value={infos.email} onChange={(e) => setInfos({...infos, email: e.target.value})} />
            </div>
            <div className="field">
              <label>Téléphone</label>
              <input value={infos.tel} onChange={(e) => setInfos({...infos, tel: e.target.value})} />
            </div>
            <label className="checkbox-row">
              <input type="checkbox" checked={infos.consent} onChange={(e) => setInfos({...infos, consent: e.target.checked})} />
              <span>J'accepte de recevoir un rappel par email 48h avant le rendez-vous. Annulation gratuite jusqu'à 24h avant.</span>
            </label>
          </div>
        </>
      )}

      {step === 3 && (
        <div className="confirm">
          <div className="check">✓</div>
          <h3>Votre séance est réservée</h3>
          <p>Un email de confirmation vient de partir vers <span className="email">{infos.email}</span>. Vous recevrez un rappel 48h avant.</p>
          <div className="details">
            <div className="k">Soin</div>
            <div className="v">{services[service].name}</div>
            <div className="k">Quand</div>
            <div className="v">{formatDateLong(date)} · {time}</div>
            <div className="k">Adresse</div>
            <div className="v">Rue du Page 14 · 1050 Ixelles</div>
          </div>
          <button className="btn-booking btn-booking-ghost" style={{marginTop: 24}} onClick={reset}>
            Nouvelle réservation
          </button>
        </div>
      )}

      {step < 3 && (
        <div className="step-actions">
          <button
            className="btn-booking"
            disabled={!canNext()}
            onClick={() => setStep(step + 1)}
          >
            {step === 2 ? 'Confirmer la réservation' : 'Continuer'} <span>→</span>
          </button>
        </div>
      )}
    </div>
  );
};

window.BookingFlow = BookingFlow;
