/* ============================================================
   PURE SPA — AGENDA · Reserva pública  /booking
   Flujo de 5 pasos, móvil primero, disponibilidad por camilla.
   ============================================================ */
function BookingProgress({ step }) {
  const steps = ["Experiencia", "Fecha", "Hora", "Datos", "Confirma"];
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 6, justifyContent: "center", marginBottom: 26, flexWrap: "wrap" }}>
      {steps.map((s, i) => (
        <React.Fragment key={s}>
          <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
            <span style={{ width: 22, height: 22, borderRadius: 999, display: "flex", alignItems: "center", justifyContent: "center",
              fontSize: 10, fontWeight: 600, fontFamily: "var(--font-body)",
              background: i < step ? C.gold : (i === step ? C.espresso : C.white),
              color: i <= step ? (i === step ? C.ivory : C.espresso) : C.taupe,
              border: i > step ? `1px solid ${C.line}` : "none" }}>
              {i < step ? "✓" : i + 1}
            </span>
            <span style={{ fontFamily: "var(--font-body)", fontSize: 10, fontWeight: 600, letterSpacing: "0.08em",
              textTransform: "uppercase", color: i === step ? C.espresso : C.taupe }} className="bk-steplabel">{s}</span>
          </div>
          {i < steps.length - 1 && <span style={{ width: 14, height: 1, background: C.line }} className="bk-stepline" />}
        </React.Fragment>
      ))}
    </div>
  );
}

/* ---- calendario simple del mes ---- */
function MiniCalendar({ value, onChange }) {
  const today = new Date(); today.setHours(0, 0, 0, 0);
  const [view, setView] = useState({ y: today.getFullYear(), m: today.getMonth() });
  const meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
  const first = new Date(view.y, view.m, 1);
  const startDow = (first.getDay() + 6) % 7; // lunes primero
  const days = new Date(view.y, view.m + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < startDow; i++) cells.push(null);
  for (let d = 1; d <= days; d++) cells.push(d);
  const pad = (n) => String(n).padStart(2, "0");
  const shift = (dir) => { let m = view.m + dir, y = view.y; if (m < 0) { m = 11; y--; } if (m > 11) { m = 0; y++; } setView({ y, m }); };
  return (
    <div style={{ background: C.white, borderRadius: 14, border: `1px solid ${C.line}`, padding: 16 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
        <button onClick={() => shift(-1)} style={navBtn}><Icon name="ChevronLeft" size={16} color={C.taupe} /></button>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 19, color: C.espresso }}>{meses[view.m]} {view.y}</div>
        <button onClick={() => shift(1)} style={navBtn}><Icon name="ChevronRight" size={16} color={C.taupe} /></button>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 4, marginBottom: 6 }}>
        {["L", "M", "M", "J", "V", "S", "D"].map((d, i) => (
          <div key={i} style={{ textAlign: "center", fontSize: 10, fontWeight: 600, color: C.taupe, letterSpacing: "0.05em" }}>{d}</div>
        ))}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 4 }}>
        {cells.map((d, i) => {
          if (!d) return <div key={i} />;
          const iso = `${view.y}-${pad(view.m + 1)}-${pad(d)}`;
          const dateObj = new Date(view.y, view.m, d);
          const past = dateObj < today;
          const dow = dateObj.getDay();
          const closed = dow === 0; // domingo cerrado
          const disabled = past || closed;
          const sel = value === iso;
          return (
            <button key={i} disabled={disabled} onClick={() => onChange(iso)}
              style={{ aspectRatio: "1", borderRadius: 10, border: sel ? `1.5px solid ${C.gold}` : "1px solid transparent",
                background: sel ? C.gold : "transparent", color: disabled ? "#D8CFBE" : (sel ? C.espresso : C.espresso),
                fontFamily: "var(--font-body)", fontSize: 13, fontWeight: sel ? 600 : 400,
                cursor: disabled ? "default" : "pointer", transition: "all .15s",
                textDecoration: disabled && !past ? "line-through" : "none" }}>
              {d}
            </button>
          );
        })}
      </div>
    </div>
  );
}
const navBtn = { background: C.ivory, border: `1px solid ${C.line}`, borderRadius: 999, width: 32, height: 32,
  display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" };

function PublicBooking() {
  const [step, setStep] = useState(0);
  const [svc, setSvc] = useState(null);
  const [date, setDate] = useState(null);
  const [time, setTime] = useState(null);
  const [form, setForm] = useState({ name: "", phone: "", email: "", comment: "" });
  const [errors, setErrors] = useState({});
  const [done, setDone] = useState(false);
  const [_bv, _setBv] = useState(0);
  useEffect(() => PureApi.subscribe(() => _setBv(v => v + 1)), []);
  const services = useMemo(() => PureApi.getServices().filter((s) => s.online && s.active), [_bv]);
  const slots = useMemo(() => (svc && date) ? PureApi.getAvailability(svc.id, date) : [], [svc, date, _bv]);

  const go = (n) => setStep(n);
  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = "Necesitamos tu nombre.";
    if (!form.phone.trim()) e.phone = "Necesitamos un teléfono de contacto.";
    if (!form.email.trim() || !/.+@.+\..+/.test(form.email)) e.email = "Ingresa un email válido.";
    setErrors(e); return Object.keys(e).length === 0;
  };
  const submit = async () => {
    try {
      await PureApi.createBooking({
        customerId: null, serviceId: svc.id, date, start: time, bedId: null,
        status: "pending_confirmation", origin: "Web",
        _customerName: form.name, _customerPhone: form.phone, _customerEmail: form.email, comment: form.comment,
      });
      setDone(true);
    } catch (err) {
      setErrors({ global: err.message || "Error al confirmar la reserva. Intenta de nuevo." });
    }
  };

  return (
    <div style={{ minHeight: "100vh", background: C.ivory, display: "flex", justifyContent: "center" }}>
      <div style={{ width: "100%", maxWidth: 560, padding: "0 20px 60px" }}>
        {/* header */}
        <div style={{ textAlign: "center", paddingTop: 38, paddingBottom: 28 }}>
          <img src="assets/logo-gold.png" style={{ height: 50 }} alt="Pure Spa" />
          <div style={{ fontFamily: "var(--font-body)", fontSize: 10, fontWeight: 600, letterSpacing: "0.22em",
            textTransform: "uppercase", color: C.taupe, marginTop: 10 }}>Spa Capilar · Ritual Japonés</div>
        </div>

        {done ? <SuccessScreen svc={svc} date={date} time={time} form={form} onReset={() => { setDone(false); setStep(0); setSvc(null); setDate(null); setTime(null); setForm({ name: "", phone: "", email: "", comment: "" }); }} />
          : <>
            <BookingProgress step={step} />

            {step === 0 && (
              <div>
                <StepHead title="Elige tu experiencia" sub="Cada ritual es una pausa distinta. Elige la que tu cabeza necesita hoy." />
                <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                  {services.map((s) => (
                    <button key={s.id} onClick={() => { setSvc(s); go(1); }} style={{ textAlign: "left", cursor: "pointer",
                      display: "flex", gap: 14, alignItems: "stretch", background: C.white, borderRadius: 16, padding: 12,
                      border: `1px solid ${C.line}`, boxShadow: "0 2px 14px rgba(43,37,32,0.05)", transition: "transform .2s, box-shadow .2s" }}
                      onMouseEnter={(e) => { e.currentTarget.style.boxShadow = "0 10px 30px rgba(43,37,32,0.1)"; e.currentTarget.style.transform = "translateY(-2px)"; }}
                      onMouseLeave={(e) => { e.currentTarget.style.boxShadow = "0 2px 14px rgba(43,37,32,0.05)"; e.currentTarget.style.transform = "none"; }}>
                      <div style={{ width: 92, borderRadius: 12, flexShrink: 0, background: `url('${s.photo}') center/cover`, minHeight: 92 }} />
                      <div style={{ flex: 1, minWidth: 0, paddingRight: 4 }}>
                        <Eyebrow color={C.gold} style={{ marginBottom: 4 }}>{s.eyebrow}</Eyebrow>
                        <div style={{ fontFamily: "var(--font-display)", fontSize: 21, color: C.espresso, lineHeight: 1.1 }}>{s.name}</div>
                        <p style={{ fontFamily: "var(--font-body)", fontWeight: 300, fontSize: 12.5, color: C.taupe, lineHeight: 1.55, margin: "6px 0 8px" }}>{s.desc}</p>
                        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                          <span style={{ fontFamily: "var(--font-body)", fontSize: 11.5, color: C.taupe, fontWeight: 400 }}>{s.duration} min</span>
                          <span style={{ fontFamily: "var(--font-display)", fontSize: 19, color: C.espresso }}>{clp(s.price)}</span>
                        </div>
                      </div>
                    </button>
                  ))}
                </div>
              </div>
            )}

            {step === 1 && (
              <div>
                <StepHead title="Selecciona el día que más te acomode" sub={svc.name} />
                <MiniCalendar value={date} onChange={(d) => { setDate(d); setTime(null); }} />
                <FooterNav back={() => go(0)} next={() => go(2)} nextLabel="Ver horarios" disabled={!date} />
              </div>
            )}

            {step === 2 && (
              <div>
                <StepHead title="Elige un horario disponible" sub={`${svc.name} · ${fullDate(date)}`} />
                <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(88px, 1fr))", gap: 12 }}>
                  {slots.map((sl) => {
                    const sel = time === sl.time;
                    return (
                      <button key={sl.time} disabled={!sl.available} onClick={() => setTime(sl.time)}
                        style={{ padding: "15px 0", borderRadius: 12, fontFamily: "var(--font-body)", fontSize: 15,
                          fontWeight: 400, cursor: sl.available ? "pointer" : "default", transition: "all .2s",
                          color: !sl.available ? "#CFC6B4" : C.espresso,
                          background: sel ? C.champagne : (sl.available ? C.white : "transparent"),
                          border: `1.5px solid ${sel ? C.gold : (sl.available ? C.line : "transparent")}`,
                          textDecoration: sl.available ? "none" : "line-through" }}>
                        {sl.time}
                      </button>
                    );
                  })}
                </div>
                {slots.every((s) => !s.available) && (
                  <p style={{ fontFamily: "var(--font-body)", fontWeight: 300, fontSize: 13, color: C.taupe, textAlign: "center", marginTop: 18 }}>
                    No quedan horarios para este día. Prueba otra fecha.
                  </p>
                )}
                <FooterNav back={() => go(1)} next={() => go(3)} nextLabel="Continuar" disabled={!time} />
              </div>
            )}

            {step === 3 && (
              <div>
                <StepHead title="Completa tus datos" sub="Solo lo necesario para recibirte bien." />
                <div style={{ background: C.white, border: `1px solid ${C.line}`, borderRadius: 16, padding: "20px 18px" }}>
                  <Field label="Nombre completo" required error={errors.name}>
                    <Input value={form.name} placeholder="¿Cómo te llamas?" error={errors.name}
                      onChange={(e) => setForm({ ...form, name: e.target.value })} />
                  </Field>
                  <Field label="Teléfono" required error={errors.phone}>
                    <Input value={form.phone} placeholder="+56 9 ..." error={errors.phone}
                      onChange={(e) => setForm({ ...form, phone: e.target.value })} />
                  </Field>
                  <Field label="Email" required error={errors.email}>
                    <Input value={form.email} placeholder="tu@email.cl" error={errors.email}
                      onChange={(e) => setForm({ ...form, email: e.target.value })} />
                  </Field>
                  <Field label="Comentario (opcional)">
                    <Textarea value={form.comment} placeholder="¿Algo que debamos saber para tu ritual?"
                      onChange={(e) => setForm({ ...form, comment: e.target.value })} />
                  </Field>
                </div>
                <FooterNav back={() => go(2)} next={() => { if (validate()) go(4); }} nextLabel="Revisar reserva" />
              </div>
            )}

            {step === 4 && (
              <div>
                <StepHead title="Confirma tu reserva" sub="Tu experiencia en Pure Spa está casi lista." />
                <div style={{ background: C.white, border: `1px solid ${C.line}`, borderRadius: 16, overflow: "hidden", boxShadow: "0 2px 16px rgba(43,37,32,0.06)" }}>
                  <div style={{ height: 120, background: `url('${svc.photo}') center/cover`, position: "relative" }}>
                    <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(43,37,32,0.1), rgba(43,37,32,0.55))" }} />
                    <div style={{ position: "absolute", left: 18, bottom: 14 }}>
                      <Eyebrow color={C.champagne}>{svc.eyebrow}</Eyebrow>
                      <div style={{ fontFamily: "var(--font-display)", fontSize: 24, color: C.ivory, lineHeight: 1.1, marginTop: 2 }}>{svc.name}</div>
                    </div>
                  </div>
                  <div style={{ padding: "8px 20px 18px" }}>
                    {[["Fecha", fullDate(date)], ["Hora", `${time} – ${endTime(time, svc)} hrs`], ["Duración", `${svc.duration} min`],
                      ["A nombre de", form.name], ["Teléfono", form.phone], ["Precio", clp(svc.price)]].map(([k, v], i, a) => (
                      <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "12px 0",
                        borderBottom: i === a.length - 1 ? "none" : `1px solid ${C.line}` }}>
                        <span style={{ fontFamily: "var(--font-body)", fontSize: 12, color: C.taupe, fontWeight: 400 }}>{k}</span>
                        <span style={{ fontFamily: "var(--font-body)", fontSize: 13.5, color: C.espresso, fontWeight: 500, textAlign: "right" }}>{v}</span>
                      </div>
                    ))}
                  </div>
                </div>
                <div style={{ marginTop: 18 }}>
                  {errors.global && <div style={{ background: "#FEF2F2", border: "1px solid #FECACA", borderRadius: 10, padding: "10px 14px", marginBottom: 14, fontFamily: "var(--font-body)", fontSize: 13, color: "#B91C1C" }}>{errors.global}</div>}
                  <Button variant="primary" full onClick={submit} arrow>Confirmar reserva</Button>
                  <button onClick={() => go(3)} style={{ width: "100%", background: "none", border: "none", cursor: "pointer",
                    fontFamily: "var(--font-body)", fontSize: 11, fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase",
                    color: C.taupe, marginTop: 14 }}>Volver a editar</button>
                </div>
              </div>
            )}
          </>}
      </div>
    </div>
  );
}

function StepHead({ title, sub }) {
  return (
    <div style={{ marginBottom: 22, textAlign: "center" }}>
      <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 400, fontSize: 28, color: C.espresso, lineHeight: 1.15, marginBottom: 6 }}>{title}</h2>
      {sub && <div style={{ fontFamily: "var(--font-body)", fontWeight: 300, fontSize: 13, color: C.taupe }}>{sub}</div>}
    </div>
  );
}
function FooterNav({ back, next, nextLabel, disabled }) {
  return (
    <div style={{ display: "flex", gap: 12, marginTop: 24 }}>
      <Button variant="soft" onClick={back}><span style={{ fontSize: 13, marginRight: 4 }}>←</span> Volver</Button>
      <Button variant="primary" full onClick={next} disabled={disabled} arrow>{nextLabel}</Button>
    </div>
  );
}

function SuccessScreen({ svc, date, time, form, onReset }) {
  return (
    <div style={{ background: C.espresso, borderRadius: 20, padding: "44px 28px 36px", position: "relative", overflow: "hidden", textAlign: "center" }}>
      <div style={{ position: "absolute", inset: 0, background: "radial-gradient(ellipse at 50% 24%, rgba(197,161,67,0.22), transparent 58%)" }} />
      <div style={{ position: "relative" }}>
        <div style={{ width: 84, height: 84, borderRadius: 999, margin: "0 auto 24px", background: "#332c25",
          display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 0 36px rgba(197,161,67,0.45)" }}>
          <Icon name="Check" size={38} color={C.gold} />
        </div>
        <div style={{ fontFamily: "var(--font-accent)", fontSize: 36, color: C.gold, lineHeight: 1, marginBottom: 8 }}>Pure Spa</div>
        <div style={{ fontFamily: "var(--font-display)", fontWeight: 300, fontSize: 28, color: C.ivory, lineHeight: 1.15, marginBottom: 12 }}>
          Tu reserva fue recibida correctamente
        </div>
        <p style={{ fontFamily: "var(--font-body)", fontWeight: 300, fontSize: 13.5, color: C.taupe, lineHeight: 1.7, marginBottom: 26 }}>
          Te confirmaremos por WhatsApp en las próximas horas.<br />Baja el ritmo, nosotros nos encargamos del resto.
        </p>
        <div style={{ background: "rgba(248,243,234,0.06)", border: "1px solid #3a3228", borderRadius: 16, padding: 20, textAlign: "left", marginBottom: 24 }}>
          {[["Experiencia", svc.name], ["Fecha", fullDate(date)], ["Hora", `${time} hrs`], ["Precio", clp(svc.price)]].map(([k, v], i, a) => (
            <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "9px 0",
              borderBottom: i === a.length - 1 ? "none" : "1px solid #3a3228" }}>
              <span style={{ fontFamily: "var(--font-body)", fontSize: 11.5, color: C.taupe, fontWeight: 300 }}>{k}</span>
              <span style={{ fontFamily: "var(--font-body)", fontSize: 13, color: C.ivory, fontWeight: 500 }}>{v}</span>
            </div>
          ))}
        </div>
        <button disabled title="Disponible próximamente" style={{ width: "100%", background: "rgba(197,161,67,0.15)", color: C.champagne,
          border: `1px solid ${C.goldDeep}`, borderRadius: 999, padding: "14px 0", fontFamily: "var(--font-body)", fontSize: 11,
          fontWeight: 600, letterSpacing: "0.15em", textTransform: "uppercase", cursor: "not-allowed", opacity: 0.7 }}>
          Continuar al pago · próximamente
        </button>
        <button onClick={onReset} style={{ width: "100%", background: "none", border: "none", cursor: "pointer",
          fontFamily: "var(--font-body)", fontSize: 11, fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase",
          color: C.taupe, marginTop: 16 }}>Hacer otra reserva</button>
      </div>
    </div>
  );
}

Object.assign(window, { PublicBooking });
