/* ============================================================
   ADMIN · RESERVATIONS — today's book, sources, seating, fees
   Uses window.PP.RES_TODAY. Shares ChargeButton/CardOnFile (admin.jsx).
   ============================================================ */
function ReservationsModule() {
  const t = useT(); const { lang } = useLang();
  const [rows, setRows] = useState(() => window.PP.RES_TODAY.map((r) => ({ ...r, fee: 0 })));
  const [filter, setFilter] = useState("all");
  const [feeFor, setFeeFor] = useState(null);
  const [amount, setAmount] = useState(100);

  const srcMeta = {
    direct:     { l: t("Direct", "Directa"), ic: "globe", c: "#5FBFA8" },
    promoter:   { l: t("Promoter", "Promotor"), ic: "megaphone", c: "#FF6B5B" },
    sevenrooms: { l: "SevenRooms", ic: "calendar", c: "#9333EA" },
  };
  const stMeta = {
    confirmed: { l: t("Confirmed", "Confirmada"), c: "#5FBFA8" },
    seated:    { l: t("Seated", "Sentada"), c: "#CBA35C" },
    "no-show": { l: t("No-show", "No-show"), c: "#ef4444" },
    cancelled: { l: t("Cancelled", "Cancelada"), c: "#6b6b72" },
  };
  const filters = [["all", t("All", "Todas")], ["confirmed", t("Confirmed", "Confirmadas")], ["seated", t("Seated", "Sentadas")], ["no-show", t("No-show", "No-show")], ["cancelled", t("Cancelled", "Canceladas")]];
  const list = rows.filter((r) => filter === "all" || r.status === filter);
  const totals = {
    covers: rows.filter((r) => r.status !== "cancelled").reduce((s, r) => s + r.party, 0),
    mins: rows.filter((r) => r.status !== "cancelled").reduce((s, r) => s + r.min, 0),
    deposits: rows.reduce((s, r) => s + r.deposit, 0),
    noshow: rows.filter((r) => r.status === "no-show").length,
  };
  const seat = (code) => setRows((rs) => rs.map((r) => r.code === code ? { ...r, status: "seated" } : r));

  return (
    <div>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-5">
        {[["calendar-check", rows.filter((r) => r.status !== "cancelled").length, t("Bookings today", "Reservas hoy"), "#FF6B5B"], ["users", totals.covers, t("Total covers", "Personas"), "#9333EA"], ["dollar-sign", "$" + (totals.mins / 1000).toFixed(1) + "K", t("Minimum spend", "Mínimo total"), "#CBA35C"], ["alert-triangle", totals.noshow, t("No-shows", "No-shows"), "#ef4444"]].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>

      <div className="flex gap-2 overflow-x-auto mb-4">{filters.map(([id, lbl]) => <button key={id} onClick={() => setFilter(id)} className={"shrink-0 px-4 py-2 rounded-xl 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}</button>)}</div>

      <div className="space-y-2.5">
        {list.map((r) => {
          const sm = stMeta[r.status]; const src = srcMeta[r.source]; const cancelled = r.status === "cancelled";
          return (
            <div key={r.code} className={"flex items-center gap-4 p-4 rounded-2xl border border-white/10 bg-card " + (cancelled ? "opacity-55" : "")}>
              <div className="text-center shrink-0 w-14"><div className="serif text-base text-white leading-none">{r.time.replace(" ", "")}</div></div>
              <div className="w-12 h-12 rounded-xl bg-coral/12 border border-coral/30 flex items-center justify-center font-extrabold text-coral shrink-0 text-xs">{r.table.replace("VIP ", "V")}</div>
              <div className="flex-1 min-w-0">
                <div className="font-bold text-sm truncate">{r.name}</div>
                <div className="text-white/45 text-xs flex items-center gap-2 flex-wrap"><span>{r.code} · {r.party} {t("guests", "pers")}</span><span className="inline-flex items-center gap-1" style={{ color: src.c }}><Icon name={src.ic} className="w-3 h-3" />{src.l}{r.promoter ? " · " + r.promoter : ""}</span></div>
              </div>
              <div className="text-right shrink-0 w-16 hidden sm:block"><div className="serif text-base text-gold-soft">${r.min}</div><div className="text-white/35 text-[10px]">{t("min", "mín")}</div></div>
              <Chip color={sm.c}>{sm.l}</Chip>
              {!cancelled && r.status !== "seated" && r.status !== "no-show" && <button onClick={() => seat(r.code)} className="px-3 py-2 rounded-full bg-coral/15 border border-coral/40 text-coral text-[11px] font-bold uppercase tracking-wider hover:bg-coral hover:text-white transition-all w-20">{t("Seat", "Sentar")}</button>}
              {r.status === "no-show" && (r.fee > 0
                ? <span className="text-green-400 text-xs font-bold flex items-center gap-1 w-20 justify-center"><Icon name="check" className="w-3.5 h-3.5" />${r.fee}</span>
                : <button onClick={() => { setFeeFor(r.code); setAmount(150); }} className="px-3 py-2 rounded-full border border-white/20 text-white text-[11px] font-bold uppercase tracking-wider hover:bg-coral hover:border-coral transition-all w-20">{t("Fee", "Tarifa")}</button>)}
              {(r.status === "seated") && <span className="w-20 text-center text-white/35 text-[11px]">{t("on floor", "en piso")}</span>}
              {cancelled && <span className="w-20 text-center text-white/30 text-[11px]">—</span>}
            </div>
          );
        })}
      </div>

      {feeFor && (() => { const r = rows.find((x) => x.code === feeFor); return (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-6 bg-black/70 backdrop-blur-sm fade-view" onClick={() => setFeeFor(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("No-show fee", "Tarifa no-show")}</h3><button onClick={() => setFeeFor(null)}><Icon name="x" className="w-5 h-5 text-white/50" /></button></div>
            <p className="text-white/55 text-sm mb-4">{r.name} · {t("Table", "Mesa")} {r.table} · {r.party} {t("guests", "personas")}</p>
            <div className="flex items-center gap-2 mb-4">{[100, 150, 250, 500].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>
            {r.card ? <div className="mb-4"><CardOnFile /></div> : <div className="mb-4 rounded-xl border border-coral/30 bg-coral/5 p-3 flex items-center gap-2 text-coral text-xs"><Icon name="alert-triangle" className="w-4 h-4 shrink-0" />{t("No card on file for this booking.", "Sin tarjeta en archivo para esta reserva.")}</div>}
            <ChargeButton amount={amount} label={t("Charge fee", "Cobrar tarifa")} onDone={() => { setRows((rs) => rs.map((x) => x.code === feeFor ? { ...x, fee: amount } : x)); setTimeout(() => setFeeFor(null), 900); }} />
            <p className="text-white/40 text-[11px] text-center mt-3">{t("Charged per the digitally-accepted cancellation policy.", "Se cobra según la política de cancelación aceptada digitalmente.")}</p>
          </div>
        </div>
      ); })()}
    </div>
  );
}

Object.assign(window, { ReservationsModule });
