// Booking / Appointment reservation section

const MONTHS = ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
const DAYS_SHORT = ['Dom','Lun','Mar','Mié','Jue','Vie','Sáb'];
const TIME_SLOTS = ['09:00','10:00','11:00','12:00','14:00','15:00','16:00','17:00'];

const Booking = () => {
  const today = new Date();
  const [view, setView] = React.useState(new Date(today.getFullYear(), today.getMonth(), 1));
  const [step, setStep] = React.useState(1);
  const [selDate, setSelDate] = React.useState(null);
  const [selTime, setSelTime] = React.useState(null);
  const [mode, setMode] = React.useState('Presencial');
  const [area, setArea] = React.useState(SERVICES[0].id);
  const [form, setForm] = React.useState({ name: '', phone: '', email: '', notes: '' });
  const [confirmed, setConfirmed] = React.useState(false);
  const [busy, setBusy] = React.useState([]);
  const [loadingSlots, setLoadingSlots] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState('');

  const isoDate = (d) => d ? `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}` : '';

  // Cargar horarios ya ocupados (Google Calendar) al elegir fecha
  React.useEffect(() => {
    if (!selDate) { setBusy([]); return; }
    let cancel = false;
    setLoadingSlots(true);
    setSelTime(null);
    fetch(`/api/availability?date=${isoDate(selDate)}`)
      .then(r => (r.ok ? r.json() : { busy: [] }))
      .then(d => { if (!cancel) setBusy(Array.isArray(d.busy) ? d.busy : []); })
      .catch(() => { if (!cancel) setBusy([]); })
      .finally(() => { if (!cancel) setLoadingSlots(false); });
    return () => { cancel = true; };
  }, [selDate]);

  const monthName = MONTHS[view.getMonth()] + ' ' + view.getFullYear();

  // Build calendar grid
  const firstDay = new Date(view.getFullYear(), view.getMonth(), 1);
  const daysInMonth = new Date(view.getFullYear(), view.getMonth() + 1, 0).getDate();
  const startCol = firstDay.getDay();
  const cells = [];
  for (let i = 0; i < startCol; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);

  const isPast = (d) => {
    const dt = new Date(view.getFullYear(), view.getMonth(), d);
    return dt < new Date(today.getFullYear(), today.getMonth(), today.getDate());
  };
  const isWeekend = (d) => {
    const dt = new Date(view.getFullYear(), view.getMonth(), d);
    return dt.getDay() === 0 || dt.getDay() === 6;
  };
  const isSelected = (d) => selDate && selDate.getFullYear() === view.getFullYear() && selDate.getMonth() === view.getMonth() && selDate.getDate() === d;
  const isToday = (d) => today.getFullYear() === view.getFullYear() && today.getMonth() === view.getMonth() && today.getDate() === d;

  const prevMonth = () => {
    const next = new Date(view.getFullYear(), view.getMonth() - 1, 1);
    if (next < new Date(today.getFullYear(), today.getMonth(), 1)) return;
    setView(next);
  };
  const nextMonth = () => setView(new Date(view.getFullYear(), view.getMonth() + 1, 1));

  const formatDate = (d) => {
    if (!d) return '';
    return `${DAYS_SHORT[d.getDay()]} ${d.getDate()} de ${MONTHS[d.getMonth()]}`;
  };

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    setSubmitting(true);
    try {
      const res = await fetch('/api/book', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          date: isoDate(selDate),
          time: selTime,
          mode,
          area: SERVICES.find(s => s.id === area)?.title || area,
          name: form.name,
          phone: form.phone,
          email: form.email,
          notes: form.notes,
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.ok) throw new Error(data.error || 'No se pudo confirmar la reserva. Probá otro horario.');
      setConfirmed(true);
    } catch (err) {
      setError(err.message || 'Error de conexión. Probá de nuevo o escribime por WhatsApp.');
    } finally {
      setSubmitting(false);
    }
  };

  const reset = () => {
    setConfirmed(false);
    setStep(1);
    setSelDate(null);
    setSelTime(null);
    setBusy([]);
    setError('');
    setForm({ name: '', phone: '', email: '', notes: '' });
  };

  return (
    <section id="booking" style={{ padding: '120px 32px', background: 'var(--cream-warm)' }}>
      <div style={{ maxWidth: 1180, margin: '0 auto' }}>
        <div style={{ textAlign: 'center', marginBottom: 64 }}>
          <div className="gold-rule serif italic-serif" style={{ fontSize: 14, color: 'var(--gold-deep)' }}>
            Reserva de citas
          </div>
          <h2 className="serif" style={{
            fontSize: 'clamp(36px, 4.5vw, 56px)', color: 'var(--burgundy)',
            fontWeight: 500, lineHeight: 1.1, margin: '20px 0 16px',
          }}>
            Reservá tu <span className="italic-serif" style={{ color: 'var(--gold-deep)' }}>consulta</span>
          </h2>
          <p style={{ fontSize: 17, color: 'var(--ink-soft)', maxWidth: 580, margin: '0 auto' }}>
            Elegí día y horario. Te confirmo por WhatsApp o email dentro de las próximas horas.
          </p>
        </div>

        <div style={{
          background: 'white', border: '1px solid var(--line-gold)',
          position: 'relative', overflow: 'hidden',
        }}>
          {/* Stepper */}
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
            borderBottom: '1px solid var(--line-gold)',
          }}>
            {[
              { n: 1, t: 'Fecha y hora' },
              { n: 2, t: 'Tipo y área' },
              { n: 3, t: 'Tus datos' },
            ].map(s => (
              <div key={s.n} style={{
                padding: '20px 24px',
                background: step === s.n ? 'var(--cream)' : 'transparent',
                borderRight: s.n < 3 ? '1px solid var(--line-gold)' : 'none',
                display: 'flex', alignItems: 'center', gap: 14,
              }}>
                <div className="serif italic-serif" style={{
                  width: 36, height: 36, borderRadius: '50%',
                  background: step >= s.n ? 'var(--burgundy)' : 'transparent',
                  color: step >= s.n ? 'var(--gold-bright)' : 'var(--gold-deep)',
                  border: step >= s.n ? 'none' : '1px solid var(--gold)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 18, fontWeight: 500,
                }}>
                  {step > s.n ? <Icon.Check size={16} color="var(--gold-bright)" /> : s.n}
                </div>
                <div>
                  <div style={{ fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-soft)' }}>
                    Paso {s.n}
                  </div>
                  <div className="serif" style={{ fontSize: 17, color: 'var(--burgundy)', fontWeight: 500 }}>
                    {s.t}
                  </div>
                </div>
              </div>
            ))}
          </div>

          {/* Step content */}
          <div style={{ padding: 40 }}>
            {step === 1 && (
              <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 0.9fr', gap: 48 }} className="booking-step1">
                {/* Calendar */}
                <div>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
                    <button onClick={prevMonth} style={{
                      background: 'none', border: '1px solid var(--line-gold)', cursor: 'pointer',
                      width: 36, height: 36, borderRadius: '50%', color: 'var(--burgundy)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }} aria-label="Mes anterior">
                      <span style={{ transform: 'rotate(180deg)', display: 'inline-flex' }}><Icon.Arrow size={14} /></span>
                    </button>
                    <div className="serif" style={{ fontSize: 24, color: 'var(--burgundy)', fontWeight: 500, textTransform: 'capitalize' }}>
                      {monthName}
                    </div>
                    <button onClick={nextMonth} style={{
                      background: 'none', border: '1px solid var(--line-gold)', cursor: 'pointer',
                      width: 36, height: 36, borderRadius: '50%', color: 'var(--burgundy)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }} aria-label="Mes siguiente">
                      <Icon.Arrow size={14} />
                    </button>
                  </div>

                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 6, marginBottom: 8 }}>
                    {DAYS_SHORT.map(d => (
                      <div key={d} style={{
                        textAlign: 'center', fontSize: 11, letterSpacing: '0.12em',
                        textTransform: 'uppercase', color: 'var(--gold-deep)', padding: '8px 0',
                      }}>{d}</div>
                    ))}
                  </div>

                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 6 }}>
                    {cells.map((d, i) => {
                      if (d === null) return <div key={i}></div>;
                      const past = isPast(d);
                      const weekend = isWeekend(d);
                      const disabled = past || weekend;
                      const sel = isSelected(d);
                      const td = isToday(d);
                      return (
                        <button
                          key={i}
                          disabled={disabled}
                          onClick={() => setSelDate(new Date(view.getFullYear(), view.getMonth(), d))}
                          className="serif"
                          style={{
                            aspectRatio: '1', border: '1px solid', borderColor: sel ? 'var(--burgundy)' : 'var(--line)',
                            background: sel ? 'var(--burgundy)' : 'white',
                            color: sel ? 'var(--cream)' : disabled ? 'rgba(0,0,0,0.2)' : 'var(--ink)',
                            cursor: disabled ? 'not-allowed' : 'pointer',
                            fontSize: 16, fontWeight: 500, position: 'relative',
                            fontFamily: 'inherit',
                            textDecoration: disabled && !past ? 'none' : 'none',
                            opacity: disabled ? 0.5 : 1,
                          }}>
                          {d}
                          {td && (
                            <span style={{
                              position: 'absolute', bottom: 4, left: '50%', transform: 'translateX(-50%)',
                              width: 4, height: 4, borderRadius: '50%',
                              background: sel ? 'var(--gold-bright)' : 'var(--gold)',
                            }}></span>
                          )}
                        </button>
                      );
                    })}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--ink-soft)', marginTop: 14, display: 'flex', gap: 16 }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                      <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--gold)' }}></span>
                      Hoy
                    </span>
                    <span style={{ opacity: 0.7 }}>Fines de semana no disponibles</span>
                  </div>
                </div>

                {/* Times */}
                <div>
                  <div style={{ fontSize: 11, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--gold-deep)', marginBottom: 8 }}>
                    Horario disponible
                  </div>
                  <div className="serif" style={{ fontSize: 20, color: 'var(--burgundy)', fontWeight: 500, marginBottom: 24 }}>
                    {selDate ? formatDate(selDate) : 'Elegí una fecha primero'}
                  </div>
                  {selDate ? (
                    <div>
                      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                        {TIME_SLOTS.map(t => {
                          const taken = busy.includes(t);
                          return (
                            <button key={t}
                              disabled={taken || loadingSlots}
                              onClick={() => setSelTime(t)}
                              className={`pill ${selTime === t ? 'selected' : ''} ${taken ? 'disabled' : ''}`}
                              style={{ fontFamily: 'inherit' }}>
                              {t}
                            </button>
                          );
                        })}
                      </div>
                      <div style={{ fontSize: 12, color: 'var(--ink-soft)', marginTop: 12, minHeight: 18 }}>
                        {loadingSlots ? 'Cargando horarios disponibles…' : 'Los horarios tachados ya están reservados.'}
                      </div>
                    </div>
                  ) : (
                    <div style={{
                      padding: '40px 24px', textAlign: 'center', border: '1px dashed var(--line)',
                      color: 'var(--ink-soft)', fontSize: 14,
                    }}>
                      <Icon.Calendar size={28} color="var(--gold-deep)" />
                      <div style={{ marginTop: 12 }}>Seleccioná un día del calendario</div>
                    </div>
                  )}

                  <button
                    disabled={!selDate || !selTime}
                    onClick={() => setStep(2)}
                    className="btn btn-primary"
                    style={{
                      width: '100%', marginTop: 32,
                      opacity: (!selDate || !selTime) ? 0.4 : 1,
                      cursor: (!selDate || !selTime) ? 'not-allowed' : 'pointer',
                    }}>
                    Continuar
                    <Icon.Arrow size={14} />
                  </button>
                </div>
              </div>
            )}

            {step === 2 && (
              <div style={{ maxWidth: 640, margin: '0 auto' }}>
                <div style={{ marginBottom: 32 }}>
                  <div className="label" style={{ marginBottom: 14 }}>Modalidad de la consulta</div>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
                    {['Presencial', 'Videollamada', 'Telefónica'].map(m => (
                      <button key={m} onClick={() => setMode(m)} style={{
                        padding: '20px 12px', cursor: 'pointer',
                        background: mode === m ? 'var(--burgundy)' : 'white',
                        color: mode === m ? 'var(--cream)' : 'var(--ink)',
                        border: '1px solid', borderColor: mode === m ? 'var(--burgundy)' : 'var(--line-gold)',
                        fontFamily: 'inherit', fontSize: 14, fontWeight: 500,
                        transition: 'all 0.2s ease',
                      }}>
                        {m}
                      </button>
                    ))}
                  </div>
                </div>

                <div style={{ marginBottom: 32 }}>
                  <div className="label" style={{ marginBottom: 14 }}>Área de consulta</div>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }} className="booking-area-grid">
                    {SERVICES.map(s => {
                      const I = Icon[s.icon];
                      return (
                        <button key={s.id} onClick={() => setArea(s.id)} style={{
                          padding: '14px 16px', cursor: 'pointer',
                          background: area === s.id ? 'var(--burgundy)' : 'white',
                          color: area === s.id ? 'var(--cream)' : 'var(--ink)',
                          border: '1px solid', borderColor: area === s.id ? 'var(--burgundy)' : 'var(--line-gold)',
                          display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left',
                          fontFamily: 'inherit', fontSize: 14, fontWeight: 500,
                        }}>
                          <I size={20} color={area === s.id ? 'var(--gold-bright)' : 'var(--gold-deep)'} />
                          {s.title}
                        </button>
                      );
                    })}
                  </div>
                </div>

                <div style={{ display: 'flex', gap: 12, justifyContent: 'space-between' }}>
                  <button onClick={() => setStep(1)} className="btn btn-gold">
                    Volver
                  </button>
                  <button onClick={() => setStep(3)} className="btn btn-primary">
                    Continuar
                    <Icon.Arrow size={14} />
                  </button>
                </div>
              </div>
            )}

            {step === 3 && (
              <form onSubmit={submit} style={{ maxWidth: 720, margin: '0 auto' }}>
                {/* Summary card */}
                <div style={{
                  background: 'var(--cream)', padding: 24, marginBottom: 32,
                  borderLeft: '2px solid var(--gold)',
                  display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24,
                }} className="booking-summary">
                  <div>
                    <div style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-soft)' }}>Fecha</div>
                    <div className="serif" style={{ fontSize: 16, color: 'var(--burgundy)', fontWeight: 500, marginTop: 4 }}>
                      {formatDate(selDate)}
                    </div>
                  </div>
                  <div>
                    <div style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-soft)' }}>Hora</div>
                    <div className="serif" style={{ fontSize: 16, color: 'var(--burgundy)', fontWeight: 500, marginTop: 4 }}>
                      {selTime} hs
                    </div>
                  </div>
                  <div>
                    <div style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-soft)' }}>Modalidad</div>
                    <div className="serif" style={{ fontSize: 16, color: 'var(--burgundy)', fontWeight: 500, marginTop: 4 }}>
                      {mode}
                    </div>
                  </div>
                  <div>
                    <div style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-soft)' }}>Área</div>
                    <div className="serif" style={{ fontSize: 16, color: 'var(--burgundy)', fontWeight: 500, marginTop: 4 }}>
                      {SERVICES.find(s => s.id === area)?.title}
                    </div>
                  </div>
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, marginBottom: 22 }}>
                  <div>
                    <div className="label">Nombre completo</div>
                    <input className="input" required value={form.name} onChange={e => setForm({...form, name: e.target.value})} />
                  </div>
                  <div>
                    <div className="label">Teléfono / WhatsApp</div>
                    <input className="input" type="tel" required value={form.phone} onChange={e => setForm({...form, phone: e.target.value})} />
                  </div>
                </div>

                <div style={{ marginBottom: 22 }}>
                  <div className="label">Email</div>
                  <input className="input" type="email" required value={form.email} onChange={e => setForm({...form, email: e.target.value})} />
                </div>

                <div style={{ marginBottom: 32 }}>
                  <div className="label">Comentarios (opcional)</div>
                  <textarea className="textarea" rows={3} value={form.notes} onChange={e => setForm({...form, notes: e.target.value})} />
                </div>

                {error && (
                  <div style={{
                    background: 'rgba(140,44,77,0.08)', border: '1px solid var(--line)',
                    color: 'var(--burgundy)', padding: '12px 16px', fontSize: 14, marginBottom: 16,
                  }}>
                    {error}
                  </div>
                )}
                <div style={{ display: 'flex', gap: 12, justifyContent: 'space-between' }}>
                  <button type="button" onClick={() => setStep(2)} className="btn btn-gold">
                    Volver
                  </button>
                  <button type="submit" disabled={submitting} className="btn btn-primary"
                    style={{ opacity: submitting ? 0.6 : 1, cursor: submitting ? 'wait' : 'pointer' }}>
                    {submitting ? 'Confirmando…' : 'Confirmar reserva'}
                    <Icon.Arrow size={14} />
                  </button>
                </div>
              </form>
            )}
          </div>

          {/* Confirmation overlay */}
          {confirmed && (
            <div style={{
              position: 'absolute', inset: 0, background: 'rgba(245,239,230,0.98)',
              display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
              padding: 60, textAlign: 'center',
            }}>
              <div className="burgundy-bg" style={{
                width: 80, height: 80, borderRadius: '50%',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                marginBottom: 28,
              }}>
                <Icon.Check size={36} color="var(--gold-bright)" />
              </div>
              <h3 className="serif" style={{ fontSize: 38, color: 'var(--burgundy)', fontWeight: 500, margin: 0 }}>
                ¡Cita reservada!
              </h3>
              <p className="serif italic-serif" style={{ fontSize: 19, color: 'var(--gold-deep)', marginTop: 8 }}>
                {formatDate(selDate)} · {selTime} hs · {mode}
              </p>
              <p style={{ color: 'var(--ink-soft)', marginTop: 16, maxWidth: 420 }}>
                Te envío la confirmación a <strong>{form.email}</strong> y por WhatsApp al <strong>{form.phone}</strong>.
              </p>
              <div style={{ display: 'flex', gap: 12, marginTop: 32 }}>
                <button onClick={reset} className="btn btn-gold">
                  Reservar otra
                </button>
                <a href={`https://wa.me/${CONTACT.phoneIntl.replace(/\D/g,'')}?text=${encodeURIComponent('Hola Suyai, acabo de reservar una cita para ' + formatDate(selDate) + ' a las ' + selTime + '.')}`}
                  target="_blank" rel="noopener noreferrer" className="btn btn-primary">
                  <Icon.WhatsApp size={16} color="white" />
                  Confirmar por WhatsApp
                </a>
              </div>
            </div>
          )}
        </div>
      </div>

      <style>{`
        @media (max-width: 880px) {
          .booking-step1 { grid-template-columns: 1fr !important; gap: 32px !important; }
          .booking-summary { grid-template-columns: 1fr 1fr !important; }
          .booking-area-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
};

Object.assign(window, { Booking });
