/* booking.jsx — Interactive booking flow for D'SHINE
   4 steps: service → date → time → contact
*/

const { useState: bkUseState, useMemo: bkUseMemo, useEffect: bkUseEffect } = React;

const BK_SERVICES = [
  {
    id: "facial",
    icn: "✦",
    name: "Cuidado facial",
    desc: "Limpieza profunda · DermaPen · Hidratación",
    dur: "60 min",
    pr: "$180k",
  },
  {
    id: "laser",
    icn: "❀",
    name: "Depilación láser",
    desc: "Bikini, axilas, piernas y más",
    dur: "45 min",
    pr: "Desde $90k",
  },
  {
    id: "makeup",
    icn: "✺",
    name: "Maquillaje social",
    desc: "Eventos, novias, sesión fotográfica",
    dur: "75 min",
    pr: "$150k",
  },
];

const BK_SLOTS = [
  "08:00", "09:00", "10:00", "11:00",
  "13:00", "14:00", "15:00", "16:00", "17:00",
];

const MONTHS_ES = [
  "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio",
  "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre",
];
const DAY_NAMES = ["L", "M", "M", "J", "V", "S", "D"];

function buildMonthGrid(year, month /* 0-indexed */) {
  const first = new Date(year, month, 1);
  // Make Monday the first column. JS getDay: Sun=0..Sat=6 → shift so Mon=0..Sun=6
  const firstCol = (first.getDay() + 6) % 7;
  const daysInMonth = new Date(year, month + 1, 0).getDate();

  const cells = [];
  for (let i = 0; i < firstCol; i++) cells.push({ muted: true });
  for (let d = 1; d <= daysInMonth; d++) {
    cells.push({ day: d, date: new Date(year, month, d) });
  }
  while (cells.length % 7 !== 0) cells.push({ muted: true });
  return cells;
}

function sameDay(a, b) {
  return a && b && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
}

function fmtLongDate(d) {
  if (!d) return "—";
  const wk = ["domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"][d.getDay()];
  return `${wk}, ${d.getDate()} de ${MONTHS_ES[d.getMonth()].toLowerCase()}`;
}

function Booking() {
  const today = bkUseMemo(() => {
    const t = new Date();
    t.setHours(0, 0, 0, 0);
    return t;
  }, []);

  const [step, setStep] = bkUseState(1);
  const [svc, setSvc] = bkUseState(null);
  const [viewYM, setViewYM] = bkUseState({ y: today.getFullYear(), m: today.getMonth() });
  const [date, setDate] = bkUseState(null);
  const [time, setTime] = bkUseState(null);
  const [form, setForm] = bkUseState({ name: "", phone: "", notes: "" });
  const [done, setDone] = bkUseState(false);

  // Pre-compute disabled slots for a given date so the UI feels populated but realistic
  const slotsForDate = bkUseMemo(() => {
    if (!date) return [];
    // Seed disabled slots based on date so it's stable & realistic-looking
    const seed = date.getDate() * 7 + (date.getMonth() + 1) * 13;
    return BK_SLOTS.map((s, i) => ({
      time: s,
      disabled: ((seed + i * 5) % 7) === 0,
    }));
  }, [date]);

  const grid = bkUseMemo(() => buildMonthGrid(viewYM.y, viewYM.m), [viewYM]);
  const monthLabel = `${MONTHS_ES[viewYM.m]} ${viewYM.y}`;

  // Disable months strictly in the past
  const canPrev = !(viewYM.y === today.getFullYear() && viewYM.m === today.getMonth());

  const movePrev = () => {
    if (!canPrev) return;
    setViewYM(({ y, m }) => (m === 0 ? { y: y - 1, m: 11 } : { y, m: m - 1 }));
  };
  const moveNext = () => {
    setViewYM(({ y, m }) => (m === 11 ? { y: y + 1, m: 0 } : { y, m: m + 1 }));
  };

  const isAvailable = (d) => {
    if (!d) return false;
    if (d < today) return false;
    // Sundays unavailable
    if (d.getDay() === 0) return false;
    return true;
  };

  const canStep2 = !!svc;
  const canStep3 = !!date;
  const canStep4 = !!time;
  const canFinish = form.name.trim() && form.phone.trim();

  const goNext = () => {
    if (step === 1 && canStep2) setStep(2);
    else if (step === 2 && canStep3) setStep(3);
    else if (step === 3 && canStep4) setStep(4);
  };
  const goBack = () => setStep((s) => Math.max(1, s - 1));

  const submit = () => {
    if (!canFinish) return;
    setDone(true);
  };

  const waUrl = bkUseMemo(() => {
    const lines = [
      "Hola D'SHINE ✨ quiero confirmar mi reserva:",
      svc ? `• Servicio: ${svc.name}` : "",
      date ? `• Fecha: ${fmtLongDate(date)}` : "",
      time ? `• Hora: ${time}` : "",
      form.name ? `• Nombre: ${form.name}` : "",
      form.phone ? `• Tel: ${form.phone}` : "",
      form.notes ? `• Nota: ${form.notes}` : "",
    ].filter(Boolean).join("\n");
    return "https://wa.me/573002031782?text=" + encodeURIComponent(lines);
  }, [svc, date, time, form]);

  if (done) {
    return (
      <div className="booking-card bk-success">
        <div className="ico"><span className="sparkle" /></div>
        <h3>¡Cita <em>preparada</em>!</h3>
        <p>
          Gracias <strong>{form.name.split(" ")[0]}</strong>. Para confirmar tu cita
          de {svc.name.toLowerCase()} el {fmtLongDate(date)} a las {time}, envíanos
          un toque por WhatsApp.
        </p>
        <a className="wa-btn" href={waUrl} target="_blank" rel="noopener">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
            <path d="M20.5 3.5A11 11 0 0 0 3.6 17.6L2 22l4.5-1.5A11 11 0 1 0 20.5 3.5Z"/>
          </svg>
          Confirmar por WhatsApp
        </a>
        <div style={{ marginTop: 26 }}>
          <button
            className="bk-back"
            onClick={() => { setDone(false); setStep(1); setSvc(null); setDate(null); setTime(null); setForm({ name: "", phone: "", notes: "" }); }}
          >
            ← Reservar otra cita
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="booking-card">
      <div className="bk-steps" role="tablist">
        {["Servicio", "Fecha", "Hora", "Datos"].map((label, i) => {
          const n = i + 1;
          const state = step === n ? "active" : step > n ? "done" : "";
          return (
            <React.Fragment key={n}>
              <span className={`step ${state}`}>
                <span className="n">{step > n ? "✓" : n}</span>
                <span className="label">{label}</span>
              </span>
              {n < 4 && <span className="sep">·</span>}
            </React.Fragment>
          );
        })}
      </div>

      {step === 1 && (
        <div>
          <p className="bk-label">Selecciona el servicio que quieres reservar</p>
          <div className="bk-svcs">
            {BK_SERVICES.map((s) => (
              <button
                key={s.id}
                className={`bk-svc ${svc?.id === s.id ? "selected" : ""}`}
                onClick={() => setSvc(s)}
              >
                <span className="icn">{s.icn}</span>
                <div className="info">
                  <div className="n">{s.name}</div>
                  <div className="d">{s.desc}</div>
                </div>
                <div className="meta">
                  <div className="dur">{s.dur}</div>
                  <div className="pr">{s.pr}</div>
                </div>
              </button>
            ))}
          </div>
        </div>
      )}

      {step === 2 && (
        <div>
          <p className="bk-label">Elige una fecha para tu cita</p>
          <div className="bk-cal">
            <div>
              <div className="bk-cal-head">
                <div className="mlbl">{monthLabel}</div>
                <div className="nav-btns">
                  <button onClick={movePrev} disabled={!canPrev} aria-label="Mes anterior">‹</button>
                  <button onClick={moveNext} aria-label="Mes siguiente">›</button>
                </div>
              </div>
              <div className="bk-cal-grid">
                {DAY_NAMES.map((d, i) => <div key={i} className="dn">{d}</div>)}
                {grid.map((c, i) => {
                  if (c.muted) return <span key={i} className="d muted" />;
                  const avail = isAvailable(c.date);
                  const isToday = sameDay(c.date, today);
                  const isSel = sameDay(c.date, date);
                  return (
                    <button
                      key={i}
                      className={`d ${avail ? "available" : ""} ${isToday ? "today" : ""} ${isSel ? "selected" : ""}`}
                      disabled={!avail}
                      onClick={() => setDate(c.date)}
                    >
                      {c.day}
                    </button>
                  );
                })}
              </div>
            </div>
            <div>
              <div className="bk-cal-head">
                <div className="mlbl" style={{ fontSize: 17, color: "var(--text-dark-mut)" }}>
                  {date ? fmtLongDate(date) : "Selecciona un día"}
                </div>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                <p style={{ fontSize: 13, color: "var(--text-dark-mut)", lineHeight: 1.55, margin: 0 }}>
                  Atendemos de lunes a sábado, 8:00 am – 7:00 pm.
                  Los puntos dorados indican días con cupos disponibles.
                </p>
                <div className="bk-summary" style={{ margin: 0 }}>
                  <div className="row">
                    <span className="k">Servicio</span>
                    <span className="v">{svc?.name}</span>
                  </div>
                  <div className="row">
                    <span className="k">Duración</span>
                    <span className="v" style={{ fontSize: 14 }}>{svc?.dur}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {step === 3 && (
        <div>
          <p className="bk-label">
            Horarios disponibles · <span style={{ color: "var(--cream)" }}>{fmtLongDate(date)}</span>
          </p>
          <div className="bk-slots">
            {slotsForDate.map((s) => (
              <button
                key={s.time}
                className={`slot ${time === s.time ? "selected" : ""}`}
                disabled={s.disabled}
                onClick={() => setTime(s.time)}
              >
                {s.time}
              </button>
            ))}
          </div>
          <div className="bk-summary" style={{ marginTop: 22 }}>
            <div className="row">
              <span className="k">Cita</span>
              <span className="v"><em>{svc?.name}</em></span>
            </div>
            <div className="row">
              <span className="k">Fecha</span>
              <span className="v" style={{ fontSize: 14 }}>{fmtLongDate(date)}</span>
            </div>
          </div>
        </div>
      )}

      {step === 4 && (
        <div>
          <p className="bk-label">Cuéntanos un poco sobre ti</p>
          <div className="bk-form">
            <div className="bk-field">
              <label>Nombre completo</label>
              <input
                type="text"
                placeholder="Tu nombre"
                value={form.name}
                onChange={(e) => setForm({ ...form, name: e.target.value })}
              />
            </div>
            <div className="bk-field">
              <label>WhatsApp</label>
              <input
                type="tel"
                placeholder="+57 300 000 0000"
                value={form.phone}
                onChange={(e) => setForm({ ...form, phone: e.target.value })}
              />
            </div>
            <div className="bk-field full">
              <label>Notas (opcional)</label>
              <textarea
                placeholder="Alergias, preferencias, primera cita..."
                value={form.notes}
                onChange={(e) => setForm({ ...form, notes: e.target.value })}
              />
            </div>
          </div>

          <div className="bk-summary" style={{ marginTop: 22 }}>
            <div className="row">
              <span className="k">Servicio</span>
              <span className="v"><em>{svc?.name}</em></span>
            </div>
            <div className="row">
              <span className="k">Cuándo</span>
              <span className="v" style={{ fontSize: 14 }}>{fmtLongDate(date)} · {time}</span>
            </div>
            <div className="row">
              <span className="k">Inversión</span>
              <span className="v">{svc?.pr}</span>
            </div>
          </div>
        </div>
      )}

      <div className="bk-actions">
        {step > 1 ? (
          <button className="bk-back" onClick={goBack}>← Volver</button>
        ) : (
          <span />
        )}
        {step < 4 ? (
          <button
            className="bk-next"
            onClick={goNext}
            disabled={
              (step === 1 && !canStep2) ||
              (step === 2 && !canStep3) ||
              (step === 3 && !canStep4)
            }
          >
            Continuar →
          </button>
        ) : (
          <button className="bk-next" onClick={submit} disabled={!canFinish}>
            Confirmar reserva ✦
          </button>
        )}
      </div>
    </div>
  );
}

window.Booking = Booking;
