/* ===== Luxury Academy — Cart / Marketplace (drawer + checkout modal) ===== */

// ── Global store (pub/sub) so any component can read/update the cart ───────────
const cartStore = {
  items: [], drawerOpen: false, checkoutOpen: false,
  _l: new Set(),
  _emit() { this._l.forEach(f => f()); },
  subscribe(f) { this._l.add(f); return () => this._l.delete(f); },
  add(svc) {
    const ex = this.items.find(i => i.id === svc.id);
    this.items = ex
      ? this.items.map(i => i.id === svc.id ? { ...i, qty: i.qty + 1 } : i)
      : [...this.items, { id: svc.id, name: svc.name, price: svc.price, img: svc.img, duration: svc.duration, qty: 1 }];
    this._emit();
  },
  setQty(id, q) {
    q = Math.max(0, q);
    this.items = q === 0 ? this.items.filter(i => i.id !== id) : this.items.map(i => i.id === id ? { ...i, qty: q } : i);
    this._emit();
  },
  remove(id) { this.items = this.items.filter(i => i.id !== id); this._emit(); },
  clear() { this.items = []; this._emit(); },
  openDrawer() { this.drawerOpen = true; this.checkoutOpen = false; this._emit(); },
  closeDrawer() { this.drawerOpen = false; this._emit(); },
  openCheckout() { this.checkoutOpen = true; this.drawerOpen = false; this._emit(); },
  closeCheckout() { this.checkoutOpen = false; this._emit(); },
};
window.cartStore = cartStore;

function useCart() {
  const [, force] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => cartStore.subscribe(force), []);
  const items = cartStore.items;
  return {
    items,
    count: items.reduce((s, i) => s + i.qty, 0),
    subtotal: items.reduce((s, i) => s + i.price * i.qty, 0),
    drawerOpen: cartStore.drawerOpen,
    checkoutOpen: cartStore.checkoutOpen,
  };
}
window.useCart = useCart;

const _fmtCOP = (n, lang) => "$" + Number(n).toLocaleString(lang === "en" ? "en-US" : "es-CO");
const _dstr = d => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;

// Called by service cards — adds to cart and opens the floating drawer (no scroll)
window.lxAddToCart = function (svc, lang) {
  cartStore.add(svc);
  if (window.lxToast) window.lxToast({ type: "ok", msg: lang === "es" ? "Añadido a tu reserva" : "Added to your booking" });
  cartStore.openDrawer();
};

// ── Cart button (nav) — bag + count badge ─────────────────────────────────────
function CartButton({ lang }) {
  const { count } = useCart();
  return (
    <button className="cart-btn" onClick={() => cartStore.openDrawer()}
      aria-label={lang === "es" ? "Ver tu reserva" : "View your booking"}>
      <Icon.Bag size={18} />
      {count > 0 && <span className="cart-badge">{count}</span>}
    </button>
  );
}
window.CartButton = CartButton;

// ── Cart drawer (slide-in floating panel) ─────────────────────────────────────
function CartDrawer({ lang, scrollTo }) {
  const { items, count, subtotal, drawerOpen } = useCart();
  React.useEffect(() => {
    if (!drawerOpen) return;
    const onKey = e => { if (e.key === "Escape") cartStore.closeDrawer(); };
    document.addEventListener("keydown", onKey);
    const ov = document.body.style.overflow; document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = ov; };
  }, [drawerOpen]);
  if (!drawerOpen) return null;

  const goServices = () => { cartStore.closeDrawer(); if (scrollTo) scrollTo("services"); };

  return (
    <div className="drawer-back" onClick={() => cartStore.closeDrawer()}>
      <aside className="cart-drawer" onClick={e => e.stopPropagation()} role="dialog" aria-modal="true"
        aria-label={lang === "es" ? "Tu reserva" : "Your booking"}>
        <header className="cart-drawer-head">
          <div>
            <div className="eyebrow"><span className="dot"></span>{lang === "es" ? "Tu reserva" : "Your booking"}</div>
            <h3>{lang === "es" ? "Carrito" : "Cart"}{count > 0 && <span className="cart-h-count">{count}</span>}</h3>
          </div>
          <button className="cart-x" onClick={() => cartStore.closeDrawer()} aria-label={lang === "es" ? "Cerrar" : "Close"}><Icon.Close size={18} /></button>
        </header>

        {items.length === 0 ? (
          <div className="cart-empty">
            <Icon.Bag size={44} />
            <p>{lang === "es" ? "Aún no has agregado servicios." : "You haven't added any services yet."}</p>
            <button className="btn btn-gold" onClick={goServices}>
              {lang === "es" ? "Explorar servicios" : "Browse services"}
            </button>
          </div>
        ) : (
          <>
            <div className="cart-items">
              {items.map(it => (
                <div key={it.id} className="cart-item">
                  <div className="cart-thumb">
                    {it.img ? <img src={it.img} alt={it.name[lang]} /> : <div className="cart-thumb-ph"><Icon.Sparkle size={18} /></div>}
                  </div>
                  <div className="cart-info">
                    <h4>{it.name[lang]}</h4>
                    {it.duration && <div className="cart-dur">{it.duration[lang]}</div>}
                    <div className="cart-qty">
                      <button onClick={() => cartStore.setQty(it.id, it.qty - 1)} aria-label={lang === "es" ? "Quitar uno" : "Decrease"}>−</button>
                      <span>{it.qty}</span>
                      <button onClick={() => cartStore.setQty(it.id, it.qty + 1)} aria-label={lang === "es" ? "Agregar uno" : "Increase"}>+</button>
                    </div>
                  </div>
                  <div className="cart-right">
                    <div className="cart-price">{_fmtCOP(it.price * it.qty, lang)}</div>
                    <button className="cart-rm" onClick={() => cartStore.remove(it.id)} aria-label={lang === "es" ? "Eliminar" : "Remove"}><Icon.Close size={13} /></button>
                  </div>
                </div>
              ))}
            </div>
            <footer className="cart-foot">
              <button className="cart-addmore" onClick={goServices}>+ {lang === "es" ? "Agregar más servicios" : "Add more services"}</button>
              <div className="cart-subtotal"><span>{lang === "es" ? "Subtotal" : "Subtotal"}</span><strong>{_fmtCOP(subtotal, lang)}</strong></div>
              <button className="btn btn-gold btn-block" onClick={() => cartStore.openCheckout()}>
                <Icon.Calendar size={16} /> {lang === "es" ? "Agendar cita" : "Schedule appointment"}
              </button>
              <button className="cart-clear" onClick={() => cartStore.clear()}>{lang === "es" ? "Vaciar carrito" : "Clear cart"}</button>
            </footer>
          </>
        )}
      </aside>
    </div>
  );
}
window.CartDrawer = CartDrawer;

// ── Checkout modal — date + time + data for the whole cart ─────────────────────
function CartCheckout({ lang, t }) {
  const { items, subtotal, checkoutOpen } = useCart();
  const [calMonth, setCalMonth] = React.useState(new Date());
  const [date, setDate] = React.useState(null);
  const [time, setTime] = React.useState(null);
  const [booked, setBooked] = React.useState([]);
  const [loadingSlots, setLoadingSlots] = React.useState(false);
  const [form, setForm] = React.useState({ name: "", phone: "", notes: "" });
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [done, setDone] = React.useState(null);

  // Reset transient state whenever the modal is closed
  React.useEffect(() => {
    if (!checkoutOpen) { setDone(null); setDate(null); setTime(null); setError(null); }
  }, [checkoutOpen]);

  React.useEffect(() => {
    if (!date) return;
    setLoadingSlots(true); setTime(null);
    lxApi.getBookedSlots(_dstr(date)).then(setBooked).catch(() => setBooked([])).finally(() => setLoadingSlots(false));
  }, [date]);

  React.useEffect(() => {
    if (!checkoutOpen) return;
    const onKey = e => { if (e.key === "Escape") cartStore.closeCheckout(); };
    document.addEventListener("keydown", onKey);
    const ov = document.body.style.overflow; document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = ov; };
  }, [checkoutOpen]);

  if (!checkoutOpen) return null;

  const fmt = n => _fmtCOP(n, lang);
  const today = new Date();
  const slots = ["08:00", "09:00", "10:00", "11:00", "12:00", "14:00", "15:00", "16:00", "17:00", "18:00"];
  const months = (t.booking && t.booking.months) || ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
  const dows = (t.booking && t.booking.days) || ["Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"];

  const firstDay = new Date(calMonth.getFullYear(), calMonth.getMonth(), 1);
  const lastDay = new Date(calMonth.getFullYear(), calMonth.getMonth() + 1, 0);
  const cells = [];
  for (let i = 0; i < firstDay.getDay(); i++) cells.push(null);
  for (let d = 1; d <= lastDay.getDate(); d++) cells.push(d);
  const isPast = d => d && new Date(calMonth.getFullYear(), calMonth.getMonth(), d) < new Date(today.getFullYear(), today.getMonth(), today.getDate());
  const isToday = d => d && new Date(calMonth.getFullYear(), calMonth.getMonth(), d).toDateString() === today.toDateString();
  const isSel = d => date && d && date.getDate() === d && date.getMonth() === calMonth.getMonth() && date.getFullYear() === calMonth.getFullYear();
  const pick = d => { if (!d || isPast(d)) return; setDate(new Date(calMonth.getFullYear(), calMonth.getMonth(), d)); };
  const dateLabel = date ? `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}` : "";

  const buildWa = (snap, total) => {
    const lines = snap.map((it, i) => `${i + 1}. ${it.name[lang]}${it.qty > 1 ? ` x${it.qty}` : ""} — ${fmt(it.price * it.qty)}`).join("\n");
    const msg = lang === "es"
      ? `Hola Luxury Academy! Quiero agendar mi reserva:\n\n${lines}\n\n📅 Fecha: ${dateLabel}\n⏰ Hora: ${time}\n👤 Nombre: ${form.name}\n📱 WhatsApp: ${form.phone}${form.notes ? `\n💬 Notas: ${form.notes}` : ""}\n\n💵 Total: ${fmt(total)}`
      : `Hello Luxury Academy! I'd like to book:\n\n${lines}\n\n📅 Date: ${dateLabel}\n⏰ Time: ${time}\n👤 Name: ${form.name}\n📱 WhatsApp: ${form.phone}${form.notes ? `\n💬 Notes: ${form.notes}` : ""}\n\n💵 Total: ${fmt(total)}`;
    return `https://wa.me/573332716890?text=${encodeURIComponent(msg)}`;
  };

  const addToCalendar = (snap, total) => {
    const pad = n => String(n).padStart(2, "0");
    const stamp = d => `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}T${pad(d.getHours())}${pad(d.getMinutes())}00`;
    const [hh, mm] = time.split(":").map(Number);
    const start = new Date(date.getFullYear(), date.getMonth(), date.getDate(), hh, mm);
    let mins = 0;
    snap.forEach(it => {
      const dt = it.duration ? it.duration[lang] : "";
      const h = (dt.match(/(\d+)\s*h/) || [])[1]; const m = (dt.match(/(\d+)\s*m/) || [])[1];
      mins += ((h ? +h * 60 : 0) + (m ? +m : 0) || 60) * it.qty;
    });
    if (!mins) mins = 60;
    const end = new Date(start.getTime() + mins * 60000);
    const esc = s => String(s || "").replace(/([\\,;])/g, "\\$1").replace(/\n/g, "\\n");
    const summary = lang === "es" ? "Cita · Luxury Academy" : "Appointment · Luxury Academy";
    const desc = snap.map(it => `${it.name[lang]}${it.qty > 1 ? ` x${it.qty}` : ""}`).join(", ") + `\\n${lang === "es" ? "Total" : "Total"}: ${fmt(total)}` + (form.name ? `\\n${form.name}` : "");
    const ics = ["BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//Luxury Academy Ibague//ES", "CALSCALE:GREGORIAN", "BEGIN:VEVENT",
      "UID:" + Math.random().toString(36).slice(2) + "@luxury-academy", "DTSTAMP:" + stamp(new Date()),
      "DTSTART:" + stamp(start), "DTEND:" + stamp(end), "SUMMARY:" + esc(summary), "DESCRIPTION:" + esc(desc),
      "LOCATION:" + esc("Cr 8A #57-52 Urb. Rincón de Piedra Pintada, Ibagué"), "END:VEVENT", "END:VCALENDAR"].join("\r\n");
    const url = URL.createObjectURL(new Blob([ics], { type: "text/calendar;charset=utf-8" }));
    const a = document.createElement("a"); a.href = url; a.download = "cita-luxury-academy.ics";
    document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000);
  };

  const confirm = async () => {
    const snap = items.map(i => ({ ...i }));
    const total = subtotal;
    setSubmitting(true); setError(null);
    try {
      const ds = _dstr(date);
      for (const it of snap) {
        for (let k = 0; k < it.qty; k++) {
          await lxApi.createBooking({ serviceId: it.id, date: ds, timeSlot: time, name: form.name, phone: form.phone, notes: form.notes, lang });
        }
      }
      window.open(buildWa(snap, total), "_blank");
      setDone({ snap, total });
      cartStore.clear();
    } catch (e) {
      setError(lang === "es" ? "No se pudo guardar la cita. Intenta de nuevo." : "Could not save the appointment. Please try again.");
    } finally {
      setSubmitting(false);
    }
  };

  const close = () => cartStore.closeCheckout();

  return (
    <div className="modal-back checkout-back" onClick={e => e.target === e.currentTarget && close()}>
      <div className="checkout-modal" role="dialog" aria-modal="true">
        <button className="cart-x checkout-x" onClick={close} aria-label={lang === "es" ? "Cerrar" : "Close"}><Icon.Close size={18} /></button>

        {done ? (
          <div className="checkout-success">
            <div className="checkout-success-ic">✅</div>
            <h3>{lang === "es" ? "¡Reserva registrada!" : "Booking confirmed!"}</h3>
            <p>{lang === "es"
              ? "Guardamos tu reserva y abrimos WhatsApp para confirmar los detalles con el equipo."
              : "We saved your booking and opened WhatsApp to confirm the details with the team."}</p>
            <div className="checkout-success-list">
              {done.snap.map(it => (
                <div key={it.id}><span>{it.name[lang]}{it.qty > 1 ? ` ×${it.qty}` : ""}</span><span>{fmt(it.price * it.qty)}</span></div>
              ))}
              <div className="cs-total"><span>{lang === "es" ? "Total" : "Total"}</span><span>{fmt(done.total)}</span></div>
            </div>
            <div className="checkout-actions">
              <button className="btn btn-primary" onClick={() => addToCalendar(done.snap, done.total)}>
                <Icon.Calendar size={16} /> {lang === "es" ? "Añadir al calendario" : "Add to calendar"}
              </button>
              <button className="btn btn-gold" onClick={close}>{lang === "es" ? "Listo" : "Done"}</button>
            </div>
          </div>
        ) : (
          <>
            <div className="checkout-head">
              <div className="eyebrow"><span className="dot"></span>{lang === "es" ? "Finaliza tu reserva" : "Complete your booking"}</div>
              <h3>{lang === "es" ? "Agenda tu cita" : "Schedule your appointment"}</h3>
            </div>

            <div className="checkout-body">
              {/* Order summary */}
              <div className="checkout-summary">
                {items.map(it => (
                  <div key={it.id} className="cs-row">
                    <span className="cs-name">{it.name[lang]}{it.qty > 1 ? ` ×${it.qty}` : ""}</span>
                    <span className="cs-price">{fmt(it.price * it.qty)}</span>
                  </div>
                ))}
                <div className="cs-row cs-grand"><span>{lang === "es" ? "Total" : "Total"}</span><span>{fmt(subtotal)}</span></div>
              </div>

              {/* Calendar */}
              <div className="cal">
                <div className="cal-head">
                  <h4>{months[calMonth.getMonth()]} {calMonth.getFullYear()}</h4>
                  <div className="cal-nav">
                    <button onClick={() => setCalMonth(m => new Date(m.getFullYear(), m.getMonth() - 1, 1))} aria-label="◀"><Icon.ChevronLeft size={14} /></button>
                    <button onClick={() => setCalMonth(m => new Date(m.getFullYear(), m.getMonth() + 1, 1))} aria-label="▶"><Icon.ChevronRight size={14} /></button>
                  </div>
                </div>
                <div className="cal-grid">
                  {dows.map((d, i) => <div key={i} className="cal-dow">{d}</div>)}
                  {cells.map((d, i) => (
                    <button key={i} className={`cal-day ${isPast(d) ? "muted" : ""} ${isToday(d) ? "today" : ""} ${d && !isPast(d) ? "has-slots" : ""} ${isSel(d) ? "on" : ""}`} onClick={() => pick(d)}>{d}</button>
                  ))}
                </div>
                {date && (
                  <div>
                    <p style={{ fontSize: 13, color: "var(--c-ink-mute)", margin: "16px 0 10px" }}>{lang === "es" ? "Elige una hora" : "Pick a time"}</p>
                    {loadingSlots ? (
                      <div style={{ fontSize: 13, color: "var(--c-ink-mute)", padding: "12px 0" }}>{lang === "es" ? "Verificando disponibilidad…" : "Checking availability…"}</div>
                    ) : (
                      <div className="time-slots">
                        {slots.map(s => (
                          <button key={s} className={`slot ${booked.includes(s) ? "taken" : ""} ${time === s ? "on" : ""}`}
                            onClick={() => !booked.includes(s) && setTime(s)}>{s}</button>
                        ))}
                      </div>
                    )}
                  </div>
                )}
              </div>

              {/* Form */}
              <div className="checkout-form">
                <div className="form-group">
                  <label>{lang === "es" ? "Nombre completo" : "Full name"}</label>
                  <div className="input-wrap"><Icon.User size={16} /><input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="María García" /></div>
                </div>
                <div className="form-group">
                  <label>WhatsApp</label>
                  <div className="input-wrap"><Icon.Phone size={16} /><input value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} placeholder="316 000 0000" /></div>
                </div>
                <div className="form-group">
                  <label>{lang === "es" ? "Notas (opcional)" : "Notes (optional)"}</label>
                  <textarea value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} rows={2}
                    placeholder={lang === "es" ? "Alguna preferencia o comentario…" : "Any preference or comment…"}
                    style={{ width: "100%", padding: "12px 14px", borderRadius: "var(--radius-sm)", border: "1.5px solid var(--c-line)", background: "var(--c-mist)", fontSize: 14, resize: "vertical" }} />
                </div>
                {error && <div className="checkout-error">{error}</div>}
              </div>
            </div>

            <div className="checkout-foot">
              <button className="btn btn-ghost" onClick={() => cartStore.openDrawer()} disabled={submitting}>{lang === "es" ? "Volver" : "Back"}</button>
              <button className="btn btn-gold" style={{ flex: 1, justifyContent: "center" }}
                onClick={confirm} disabled={submitting || !date || !time || !form.name || !form.phone}>
                {submitting ? (lang === "es" ? "Guardando…" : "Saving…") : <><Icon.Whatsapp size={16} /> {lang === "es" ? "Confirmar reserva" : "Confirm booking"}</>}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
window.CartCheckout = CartCheckout;
