// Booking modal
const { useState, useMemo, useEffect } = React;

function dateKey(d) { return d.toISOString().slice(0, 10); }
function seededTakenFor(date) {
  const day = date.getDay();
  if (day === 0) return null;
  const k = date.getDate() + date.getMonth() * 31;
  const slots = ["09:00", "10:30", "12:00", "14:00", "15:30", "17:00"];
  const taken = [];
  if (k % 7 === 0) taken.push("10:30", "15:30");
  else if (k % 7 === 1) taken.push("09:00", "14:00", "17:00");
  else if (k % 7 === 2) taken.push("12:00");
  else if (k % 7 === 3) taken.push("10:30", "17:00");
  else if (k % 7 === 4) taken.push("09:00", "12:00", "15:30");
  else if (k % 7 === 5) taken.push("14:00");
  else taken.push("12:00", "15:30");
  return slots.map(s => ({ time: s, taken: taken.includes(s) }));
}
function buildMonth(year, month) {
  const first = new Date(year, month, 1);
  const startWeekday = (first.getDay() + 6) % 7;
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < startWeekday; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(new Date(year, month, d));
  while (cells.length % 7 !== 0) cells.push(null);
  return cells;
}
const MONTH_NAMES = ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"];
const DAY_NAMES = ["L","M","X","J","V","S","D"];

function BookingModal({ open, onClose, prefillService }) {
  const today = useMemo(() => { const t = new Date(); t.setHours(0,0,0,0); return t; }, []);
  const [view, setView] = useState({ y: today.getFullYear(), m: today.getMonth() });
  const [selectedDate, setSelectedDate] = useState(null);
  const [selectedSlot, setSelectedSlot] = useState(null);
  const [serviceId, setServiceId] = useState(prefillService || (window.ALL_SERVICES[0]?.name));
  const [step, setStep] = useState(1);
  const [contact, setContact] = useState({ name: "", phone: "", notes: "" });
  const [done, setDone] = useState(false);

  useEffect(() => {
    if (open) {
      setSelectedDate(null); setSelectedSlot(null); setStep(1); setDone(false);
      if (prefillService) setServiceId(prefillService);
    }
  }, [open, prefillService]);

  if (!open) return null;
  const cells = buildMonth(view.y, view.m);
  const slots = selectedDate ? seededTakenFor(selectedDate) : null;
  const service = window.ALL_SERVICES.find(s => s.name === serviceId) || window.ALL_SERVICES[0];

  const goPrev = () => { const m = view.m - 1; const y = view.y + (m < 0 ? -1 : 0); setView({ y, m: (m + 12) % 12 }); };
  const goNext = () => { const m = view.m + 1; const y = view.y + (m > 11 ? 1 : 0); setView({ y, m: m % 12 }); };
  const isPast = (d) => d && d < today;
  const isClosed = (d) => d && d.getDay() === 0;

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Cerrar">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
        </button>
        <div className="modal-grid">
          <aside className="modal-aside">
            <img className="aside-flower" src="assets/flower-transparent.png" alt="" aria-hidden="true" />
            <div className="modal-aside-inner">
              <div className="modal-eyebrow">Agenda tu cita</div>
              <h3 className="modal-title">Reserva<br/>tu ritual</h3>
              <p className="modal-lede">Elige el momento. Nosotras preparamos el espacio, los aceites y el silencio.</p>
              <div className="modal-stepper">
                {[1,2,3].map(n => (
                  <div key={n} className={"step " + (step === n ? "is-active" : step > n ? "is-done" : "")}>
                    <span className="step-num">{step > n ? "✓" : n}</span>
                    <span className="step-label">{n === 1 ? "Servicio" : n === 2 ? "Fecha & Hora" : "Datos"}</span>
                  </div>
                ))}
              </div>
              <div className="modal-summary">
                <div className="summary-row"><span>Servicio</span><strong>{service?.name || "—"}</strong></div>
                <div className="summary-row"><span>Fecha</span><strong>{selectedDate ? selectedDate.toLocaleDateString("es-CO", { weekday: "short", day: "numeric", month: "short" }) : "—"}</strong></div>
                <div className="summary-row"><span>Hora</span><strong>{selectedSlot || "—"}</strong></div>
                <div className="summary-row summary-total"><span>Inversión</span><strong>{service ? window.formatCOP(service.price) : "—"}</strong></div>
              </div>
              <div className="buffer-note"><span className="buffer-dot"></span>Reservamos 15 min de margen entre citas para que el espacio respire.</div>
            </div>
          </aside>

          <div className="modal-main">
            {done ? (
              <div style={{ display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", height: "100%", textAlign:"center", padding: "40px 20px" }}>
                <img src="assets/flower-transparent.png" style={{ width: 180, marginBottom: 16, animation: "floatFlower 6s ease-in-out infinite" }} />
                <div style={{ fontFamily:"var(--serif)", fontSize: 44, color:"var(--purple)", marginBottom: 12, fontWeight: 400 }}>¡Lista, <em style={{ fontStyle: "italic", color: "var(--rose)" }}>{contact.name.split(" ")[0] || "preciosa"}</em>!</div>
                <p style={{ fontSize: 16, color:"var(--purple-soft)", maxWidth: 420, marginBottom: 12 }}>Te enviamos los datos por WhatsApp. Recibirás un mensaje de confirmación humano:</p>
                <p style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 18, color: "var(--rose)", maxWidth: 420, marginBottom: 28 }}>"Preparamos tu kit personal y tu té; te esperamos a las {selectedSlot || "..."}".</p>
                <div className="modal-actions">
                  <button className="btn btn-ghost" onClick={onClose}>Cerrar</button>
                  <a className="btn btn-primary" href={`https://wa.me/${window.CONTACT.whatsapp}`} target="_blank" rel="noopener">
                    Continuar por WhatsApp <span className="btn-arrow">→</span>
                  </a>
                </div>
              </div>
            ) : step === 1 ? (
              <div>
                <h4 className="pane-title">Elige tu ritual</h4>
                <p className="pane-sub">Cada experiencia incluye recibimiento con té y un momento de respiración guiada.</p>
                <div className="svc-list">
                  {window.ALL_SERVICES.map(s => (
                    <button key={s.name} className={"svc-row " + (s.name === serviceId ? "is-selected" : "")} onClick={() => setServiceId(s.name)}>
                      <div>
                        <div className="svc-row-name">{s.name}</div>
                        <div className="svc-row-meta">{s.blockTitle} · {s.duration}</div>
                      </div>
                      <div className="svc-row-price">{window.formatCOP(s.price)}</div>
                    </button>
                  ))}
                </div>
                <div className="modal-actions">
                  <button className="btn btn-ghost" onClick={onClose}>Cancelar</button>
                  <button className="btn btn-primary" onClick={() => setStep(2)} disabled={!serviceId}>Continuar <span className="btn-arrow">→</span></button>
                </div>
              </div>
            ) : step === 2 ? (
              <div>
                <h4 className="pane-title">¿Cuándo te esperamos?</h4>
                <p className="pane-sub">Cerramos los domingos. Cada bloque incluye 15 min de buffer.</p>
                <div className="cal-head">
                  <button className="cal-nav" onClick={goPrev} aria-label="Mes anterior">‹</button>
                  <div className="cal-month">{MONTH_NAMES[view.m]} {view.y}</div>
                  <button className="cal-nav" onClick={goNext} aria-label="Mes siguiente">›</button>
                </div>
                <div className="cal-grid">
                  {DAY_NAMES.map(d => <div key={d} className="cal-dayname">{d}</div>)}
                  {cells.map((d, i) => {
                    if (!d) return <div key={i} />;
                    const past = isPast(d), closed = isClosed(d);
                    const sel = selectedDate && dateKey(d) === dateKey(selectedDate);
                    return (
                      <button key={i} className={"cal-cell" + (past?" is-past":"") + (closed?" is-closed":"") + (sel?" is-selected":"")} disabled={past || closed} onClick={() => { setSelectedDate(d); setSelectedSlot(null); }}>
                        <span className="cal-num">{d.getDate()}</span>
                        {!past && !closed && <span className="cal-dot" />}
                      </button>
                    );
                  })}
                </div>
                {selectedDate && (
                  <div className="slots">
                    <div className="slots-title">Horarios disponibles · <span>{selectedDate.toLocaleDateString("es-CO", { weekday: "long", day: "numeric", month: "long" })}</span></div>
                    <div className="slot-grid">
                      {slots.map(s => (
                        <button key={s.time} disabled={s.taken} onClick={() => setSelectedSlot(s.time)} className={"slot " + (s.taken?"is-taken":"") + (selectedSlot === s.time?" is-selected":"")}>
                          {s.time}{s.taken && <span className="slot-tag">Reservada</span>}
                        </button>
                      ))}
                    </div>
                  </div>
                )}
                <div className="modal-actions">
                  <button className="btn btn-ghost" onClick={() => setStep(1)}>← Atrás</button>
                  <button className="btn btn-primary" onClick={() => setStep(3)} disabled={!selectedDate || !selectedSlot}>Continuar <span className="btn-arrow">→</span></button>
                </div>
              </div>
            ) : (
              <div>
                <h4 className="pane-title">Tus datos</h4>
                <p className="pane-sub">Te confirmamos por WhatsApp 24 h antes de tu cita.</p>
                <div className="form-grid">
                  <label className="field"><span>Nombre completo</span>
                    <input value={contact.name} onChange={e => setContact({...contact, name: e.target.value})} placeholder="María Fernanda Gómez" />
                  </label>
                  <label className="field"><span>WhatsApp</span>
                    <input type="tel" value={contact.phone} onChange={e => setContact({...contact, phone: e.target.value})} placeholder="+57 314 000 0000" />
                  </label>
                  <label className="field field-wide"><span>Notas para tu terapeuta <em>(opcional)</em></span>
                    <textarea rows="3" value={contact.notes} onChange={e => setContact({...contact, notes: e.target.value})} placeholder="Alergias, preferencias de aroma, primera visita…" />
                  </label>
                </div>
                <div className="confirm-card">
                  <div className="confirm-flower"><img src="assets/flower-transparent.png" alt="" /></div>
                  <div>
                    <div className="confirm-title">Estás reservando</div>
                    <div className="confirm-line">{service?.name} · {selectedDate?.toLocaleDateString("es-CO", { day: "numeric", month: "long" })} · {selectedSlot}</div>
                  </div>
                  <div className="confirm-price">{service ? window.formatCOP(service.price) : ""}</div>
                </div>
                <div className="modal-actions">
                  <button className="btn btn-ghost" onClick={() => setStep(2)}>← Atrás</button>
                  <a
                    className="btn btn-primary"
                    style={{ pointerEvents: (!contact.name || !contact.phone) ? "none" : "auto", opacity: (!contact.name || !contact.phone) ? 0.4 : 1 }}
                    href={window.buildWhatsAppLink(service, selectedDate, selectedSlot, contact.name)}
                    target="_blank" rel="noopener"
                    onClick={() => setTimeout(() => setDone(true), 300)}
                  >Confirmar por WhatsApp ✿</a>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.BookingModal = BookingModal;
