/* ============================================================
   ADMIN · RESERVATIONS — the real reservation book.
   Reads PPDB.reservations (saved by the public reserve flow).
   Lifecycle: pending → accepted → payment-sent → paid →
   confirmed → completed / cancelled / no-show.
   Contact by WhatsApp/Call, request a Toast deposit, advance status.
   ============================================================ */
function useReservations() {
  const [list, setList] = useState(() => window.PPDB.reservations.all());
  useEffect(() => {
    const f = () => setList(window.PPDB.reservations.all());
    window.addEventListener("pp:reservations", f);
    return () => window.removeEventListener("pp:reservations", f);
  }, []);
  return list;
}

function ReservationsModule() {
  const t = useT(); const { lang } = useLang();
  const list = useReservations();
  const [q, setQ] = useState("");
  const [filter, setFilter] = useState("active");
  const [depFor, setDepFor] = useState(null);
  const [amount, setAmount] = useState(100);
  const [busy, setBusy] = useState(false);

  const ST = {
    pending:        { l: t("Pending", "Pendiente"), c: "#E8A33C" },
    accepted:       { l: t("Accepted", "Aceptada"), c: "#9333EA" },
    "payment-sent": { l: t("Deposit requested", "Depósito solicitado"), c: "#FF6B5B" },
    paid:           { l: t("Paid", "Pagada"), c: "#5FBFA8" },
    confirmed:      { l: t("Confirmed", "Confirmada"), c: "#5FBFA8" },
    completed:      { l: t("Completed", "Completada"), c: "#6b6b72" },
    cancelled:      { l: t("Cancelled", "Cancelada"), c: "#ef4444" },
    "no-show":      { l: t("No-show", "No-show"), c: "#ef4444" },
  };
  const stOf = (r) => ST[r.status] || ST.pending;
  const isActive = (r) => ["pending", "accepted", "payment-sent", "paid"].includes(r.status || "pending");

  const counts = {
    active: list.filter(isActive).length,
    pending: list.filter((r) => (r.status || "pending") === "pending").length,
    confirmed: list.filter((r) => ["paid", "confirmed"].includes(r.status)).length,
    all: list.length,
  };
  const FILTERS = [["active", t("Active", "Activas")], ["pending", t("Pending", "Pendientes")], ["confirmed", t("Confirmed", "Confirmadas")], ["all", t("All", "Todas")]];

  const filtered = list.filter((r) => {
    const okF = filter === "all" ? true : filter === "active" ? isActive(r) : filter === "confirmed" ? ["paid", "confirmed"].includes(r.status) : (r.status || "pending") === filter;
    const okQ = !q || JSON.stringify(r).toLowerCase().includes(q.toLowerCase());
    return okF && okQ;
  });

  const update = (id, patch) => window.PPDB.reservations.update(id, patch);
  const phoneDigits = (p) => String(p || "").replace(/\D/g, "");
  const fmtDate = (d) => { try { return new Date(d + "T12:00:00").toLocaleDateString(lang === "es" ? "es" : "en", { weekday: "short", month: "short", day: "numeric" }); } catch (e) { return d; } };
  const toastReady = () => !!(window.PPToast && window.PPToast.configured());

  // request a Toast deposit for a reservation
  const sendDeposit = (r) => {
    if (!toastReady()) {
      window.toast(t("Connect Toast first (Admin → Settings → Toast) to take deposits.", "Conecta Toast primero (Admin → Ajustes → Toast) para cobrar depósitos."), "error");
      // still let staff mark it as requested so the lifecycle isn't blocked
      update(r.id, { status: "payment-sent", paymentStatus: "requested" });
      setDepFor(null);
      return;
    }
    setBusy(true);
    window.PPToast.payments.createLink({
      amount: amount,
      reference: r.code,
      customer: { name: r.fullName, phone: r.phone, email: r.email },
    }).then((res) => {
      update(r.id, {
        status: "payment-sent", paymentStatus: "requested",
        depositAmount: amount, paymentLink: res.url || "", toastOrderGuid: res.orderGuid || "",
      });
      if (res.url) {
        window.toast(t("Toast deposit link created.", "Link de depósito Toast creado."));
      } else {
        window.toast(t("Deposit order created in Toast — collect at POS.", "Orden de depósito creada en Toast — cobrar en POS."));
      }
      setDepFor(null);
    }).catch((e) => {
      window.toast(t("Toast error: ", "Error de Toast: ") + e.message, "error");
    }).then(() => setBusy(false));
  };

  const waGuest = (r) => {
    const msg = t("Hi " + r.fullName + ", this is Pink Pony Club about your reservation " + r.code + " for " + fmtDate(r.date) + " at " + r.time + ".", "Hola " + r.fullName + ", somos Pink Pony Club sobre tu reserva " + r.code + " para el " + fmtDate(r.date) + " a las " + r.time + ".");
    try { window.open("https://wa.me/" + phoneDigits(r.phone).replace(/^1?/, "1") + "?text=" + encodeURIComponent(msg), "_blank", "noopener"); } catch (e) {}
  };

  return (
    <div>
      {/* stats */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-5">
        {[["bell", counts.pending, t("Pending", "Pendientes"), "#E8A33C"], ["calendar-check", counts.active, t("Active", "Activas"), "#FF6B5B"], ["circle-check-big", counts.confirmed, t("Confirmed", "Confirmadas"), "#5FBFA8"], ["list", counts.all, t("Total", "Total"), "#9333EA"]].map(([ic, n, l, c], i) => (
          <div key={i} className="rounded-2xl border border-white/10 bg-card p-4"><Icon name={ic} className="w-5 h-5 mb-2" style={{ color: c }} /><div className="text-2xl font-black leading-none">{n}</div><div className="label text-white/45 text-[9px] mt-1">{l}</div></div>
        ))}
      </div>

      {/* filters + search */}
      <div className="flex flex-wrap items-center gap-2 mb-5">
        {FILTERS.map(([id, lbl]) => (
          <button key={id} onClick={() => setFilter(id)} className={"px-4 py-2 rounded-full text-[11px] font-bold uppercase tracking-wider transition-all " + (filter === id ? "bg-coral text-white" : "bg-card border border-white/12 text-white/60 hover:text-white")}>{lbl}{counts[id] != null ? <span className="opacity-60"> · {counts[id]}</span> : null}</button>
        ))}
        <div className="relative ml-auto">
          <Icon name="search" className="w-4 h-4 text-white/35 absolute left-3 top-1/2 -translate-y-1/2" />
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder={t("Search…", "Buscar…")} className="bg-ink border border-white/12 rounded-full pl-9 pr-4 py-2 text-sm text-white focus:outline-none focus:border-coral placeholder:text-white/35 w-40 sm:w-52" />
        </div>
      </div>

      {/* toast connection hint */}
      {!toastReady() && (
        <div className="rounded-xl border border-gold/25 bg-gold/5 p-3 mb-4 flex items-center gap-2.5 text-[12px] text-gold-soft">
          <Icon name="credit-card" className="w-4 h-4 shrink-0" />
          {t("Toast isn't connected yet — deposits are tracked manually until you set it up.", "Toast aún no está conectado — los depósitos se registran manualmente hasta configurarlo.")}
        </div>
      )}

      {filtered.length === 0 ? (
        <div className="rounded-2xl border border-dashed border-white/15 p-10 text-center text-white/45 text-sm">
          <Icon name="calendar-check" className="w-8 h-8 mx-auto mb-3 text-white/25" />
          {list.length === 0
            ? t("No reservations yet. Requests from the website appear here automatically.", "Aún no hay reservas. Las solicitudes del sitio aparecen aquí automáticamente.")
            : t("No reservations match your filter.", "Ninguna reserva coincide con el filtro.")}
        </div>
      ) : (
        <div className="space-y-2.5">
          {filtered.map((r) => {
            const st = stOf(r); const ph = phoneDigits(r.phone); const status = r.status || "pending";
            return (
              <div key={r.id} className="rounded-2xl border border-white/10 bg-card p-4">
                <div className="flex items-start gap-3.5">
                  <div className="text-center shrink-0 w-16">
                    <div className="serif text-base text-white leading-none">{(r.time || "").replace(" ", "")}</div>
                    <div className="text-white/40 text-[10px] mt-1">{fmtDate(r.date)}</div>
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap">
                      <span className="font-bold text-sm truncate">{r.fullName}</span>
                      <span className="text-white/35 text-[11px]">{r.code}</span>
                    </div>
                    <div className="text-white/50 text-[12px] mt-0.5 flex items-center gap-x-3 gap-y-0.5 flex-wrap">
                      <span className="inline-flex items-center gap-1"><Icon name="users" className="w-3 h-3" />{r.guests}</span>
                      {r.experienceType && <span className="inline-flex items-center gap-1"><Icon name="sparkles" className="w-3 h-3" />{r.experienceType}</span>}
                      <span className="inline-flex items-center gap-1"><Icon name="map-pin" className="w-3 h-3" />{r.tableId || t("Host assigns", "Host asigna")}</span>
                      {r.depositAmount ? <span className="inline-flex items-center gap-1 text-coral"><Icon name="credit-card" className="w-3 h-3" />${r.depositAmount}</span> : null}
                    </div>
                    {r.notes ? <div className="text-white/40 text-[11px] mt-1 italic truncate">"{r.notes}"</div> : null}
                  </div>
                  <Chip color={st.c}>{st.l}</Chip>
                </div>

                {/* actions */}
                <div className="flex flex-wrap items-center gap-1.5 mt-3 pt-3 border-t border-white/8">
                  {ph && <a href={"https://wa.me/" + ph.replace(/^1?/, "1")} target="_blank" rel="noopener" onClick={(e) => { e.preventDefault(); waGuest(r); }} className="px-3 py-1.5 rounded-full bg-[#25D366] text-black text-[10px] font-bold uppercase tracking-wider inline-flex items-center gap-1.5"><Icon name="message-circle" className="w-3 h-3" />WhatsApp</a>}
                  {ph && <a href={"tel:+" + ph.replace(/^1?/, "1")} className="px-3 py-1.5 rounded-full border border-white/15 text-white/70 text-[10px] font-bold uppercase tracking-wider hover:bg-white/5 inline-flex items-center gap-1.5"><Icon name="phone" className="w-3 h-3" />{t("Call", "Llamar")}</a>}

                  {status === "pending" && <button onClick={() => update(r.id, { status: "accepted" })} className="px-3 py-1.5 rounded-full bg-coral/15 border border-coral/40 text-coral text-[10px] font-bold uppercase tracking-wider hover:bg-coral hover:text-white transition-all">{t("Accept", "Aceptar")}</button>}
                  {(status === "accepted" || status === "pending") && <button onClick={() => { setDepFor(r.id); setAmount(r.depositAmount || 100); }} className="px-3 py-1.5 rounded-full border border-coral/40 text-coral text-[10px] font-bold uppercase tracking-wider hover:bg-coral hover:text-white transition-all inline-flex items-center gap-1.5"><Icon name="credit-card" className="w-3 h-3" />{t("Deposit", "Depósito")}</button>}
                  {r.paymentLink && <a href={r.paymentLink} target="_blank" rel="noopener" className="px-3 py-1.5 rounded-full border border-white/15 text-white/70 text-[10px] font-bold uppercase tracking-wider hover:bg-white/5 inline-flex items-center gap-1.5"><Icon name="external-link" className="w-3 h-3" />{t("Pay link", "Link pago")}</a>}
                  {status === "payment-sent" && <button onClick={() => update(r.id, { status: "paid", paymentStatus: "paid" })} className="px-3 py-1.5 rounded-full bg-[#5FBFA8]/15 border border-[#5FBFA8]/40 text-[#5FBFA8] text-[10px] font-bold uppercase tracking-wider hover:bg-[#5FBFA8] hover:text-black transition-all">{t("Mark paid", "Marcar pagada")}</button>}
                  {(status === "accepted" || status === "paid") && <button onClick={() => update(r.id, { status: "confirmed" })} className="px-3 py-1.5 rounded-full bg-[#5FBFA8]/15 border border-[#5FBFA8]/40 text-[#5FBFA8] text-[10px] font-bold uppercase tracking-wider hover:bg-[#5FBFA8] hover:text-black transition-all">{t("Confirm", "Confirmar")}</button>}
                  {status === "confirmed" && <button onClick={() => update(r.id, { status: "completed" })} className="px-3 py-1.5 rounded-full border border-white/15 text-white/70 text-[10px] font-bold uppercase tracking-wider hover:bg-white/5">{t("Complete", "Completar")}</button>}

                  {isActive(r) && <button onClick={() => update(r.id, { status: "no-show" })} className="px-3 py-1.5 rounded-full border border-white/15 text-white/45 text-[10px] font-bold uppercase tracking-wider hover:text-coral hover:border-coral/40">{t("No-show", "No-show")}</button>}
                  {status !== "cancelled" && <button onClick={() => { if (confirm(t("Cancel this reservation?", "¿Cancelar esta reserva?"))) update(r.id, { status: "cancelled" }); }} className="px-3 py-1.5 rounded-full border border-white/15 text-white/45 text-[10px] font-bold uppercase tracking-wider hover:text-coral hover:border-coral/40">{t("Cancel", "Cancelar")}</button>}
                  <button onClick={() => { if (confirm(t("Delete this reservation permanently?", "¿Borrar esta reserva permanentemente?"))) window.PPDB.reservations.remove(r.id); }} className="px-3 py-1.5 rounded-full border border-white/15 text-white/45 text-[10px] font-bold uppercase tracking-wider hover:text-coral hover:border-coral/40 ml-auto"><Icon name="trash-2" className="w-3 h-3" /></button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* deposit modal */}
      {depFor && (() => { const r = list.find((x) => x.id === depFor); if (!r) return null; return (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-6 bg-black/70 backdrop-blur-sm fade-view" onClick={() => !busy && setDepFor(null)}>
          <div className="w-full max-w-sm rounded-3xl border border-white/12 bg-ink p-6" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-4"><h3 className="text-xl font-black uppercase">{t("Request deposit", "Solicitar depósito")}</h3><button onClick={() => !busy && setDepFor(null)}><Icon name="x" className="w-5 h-5 text-white/50" /></button></div>
            <p className="text-white/55 text-sm mb-4">{r.fullName} · {r.code} · {fmtDate(r.date)} {r.time}</p>
            <div className="flex items-center gap-2 mb-4">{[50, 100, 150, 250].map((a) => <button key={a} onClick={() => setAmount(a)} className={"flex-1 py-2.5 rounded-xl text-sm font-bold transition-all " + (amount === a ? "bg-coral text-white" : "bg-card border border-white/12 text-white/60")}>${a}</button>)}</div>
            <div className="rounded-xl border border-white/12 bg-card p-3 mb-4 flex items-center gap-2 text-[12px] text-white/55">
              <Icon name={toastReady() ? "credit-card" : "alert-triangle"} className="w-4 h-4 shrink-0" style={{ color: toastReady() ? "#5FBFA8" : "#E8A33C" }} />
              {toastReady() ? t("Creates a Toast deposit order for this reservation.", "Crea una orden de depósito en Toast para esta reserva.") : t("Toast not connected — this just marks the deposit as requested.", "Toast no conectado — solo marca el depósito como solicitado.")}
            </div>
            <button disabled={busy} onClick={() => sendDeposit(r)} className={"gbtn w-full py-3.5 rounded-full text-[12px] font-bold uppercase tracking-[0.14em] flex items-center justify-center gap-2 " + (busy ? "bg-white/10 text-white/40" : "bg-coral hover:bg-coral-deep text-white")}>{busy ? t("Working…", "Procesando…") : <>{t("Request", "Solicitar")} ${amount} {t("deposit", "depósito")}</>}</button>
          </div>
        </div>
      ); })()}
    </div>
  );
}

Object.assign(window, { ReservationsModule, useReservations });
