/* ============================================================
   ADMIN · FLOOR PLAN — live visual table map + reservation status
   Reuses window.PP.TABLES (real Pink Pony layout) + RES_TODAY.
   ============================================================ */
function FloorPlanModule() {
  const t = useT(); const { lang } = useLang();
  const { TABLES, ZONES, RES_TODAY, tablePrice } = window.PP;
  const [floor, setFloor] = useState("main");
  const [sel, setSel] = useState(null);

  // reservation lookup (ignore cancelled)
  const resByTable = {};
  RES_TODAY.forEach((r) => { if (r.status !== "cancelled") resByTable[r.table] = r; });

  // effective status per table
  const effStatus = (tb) => {
    if (tb.status === "closed") return "closed";
    const r = resByTable[tb.id];
    if (r) return r.status === "seated" ? "seated" : r.status === "no-show" ? "noshow" : "reserved";
    return tb.status === "held" ? "held" : tb.status === "booked" ? "reserved" : "open";
  };
  const META = {
    open:     { c: "#5FBFA8", l: t("Open", "Libre") },
    reserved: { c: "#CBA35C", l: t("Reserved", "Reservada") },
    seated:   { c: "#FF6B5B", l: t("Seated", "Sentada") },
    held:     { c: "#9333EA", l: t("Held", "En espera") },
    noshow:   { c: "#ef4444", l: t("No-show", "No-show") },
    closed:   { c: "#3a3a40", l: t("Closed", "Cerrada") },
  };

  const onFloor = TABLES.filter((tb) => tb.floor === floor);
  const all = TABLES.filter((tb) => tb.status !== "closed");
  const counts = {
    seated: all.filter((tb) => effStatus(tb) === "seated").length,
    reserved: all.filter((tb) => effStatus(tb) === "reserved").length,
    open: all.filter((tb) => effStatus(tb) === "open").length,
  };
  const projMin = RES_TODAY.filter((r) => r.status !== "cancelled").reduce((s, r) => s + r.min, 0);

  return (
    <div>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-5">
        {[["armchair", counts.seated, t("Seated now", "Sentadas ahora"), "#FF6B5B"], ["calendar-check", counts.reserved, t("Reserved", "Reservadas"), "#CBA35C"], ["circle", counts.open, t("Open tables", "Mesas libres"), "#5FBFA8"], ["dollar-sign", "$" + (projMin / 1000).toFixed(1) + "K", t("Booked minimums", "Mínimos reservados"), "#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>

      <div className="grid lg:grid-cols-[1fr_320px] gap-5">
        {/* MAP */}
        <div className="rounded-2xl border border-white/10 bg-card p-4">
          <div className="flex items-center justify-between mb-3">
            <div className="flex gap-2">
              {[["main", t("Main Floor", "Planta Principal")], ["second", t("2nd Floor", "2do Piso")]].map(([id, lbl]) => (
                <button key={id} onClick={() => { setFloor(id); setSel(null); }} className={"px-4 py-2 rounded-full text-[11px] font-bold uppercase tracking-wider transition-all " + (floor === id ? "bg-coral text-white" : "bg-white/5 border border-white/10 text-white/55 hover:text-white")}>{lbl}</button>
              ))}
            </div>
            <div className="hidden sm:flex flex-wrap gap-2.5">
              {["open", "reserved", "seated", "held"].map((k) => <span key={k} className="inline-flex items-center gap-1.5 text-[10px] text-white/55"><span className="w-2.5 h-2.5 rounded-full" style={{ background: META[k].c }}></span>{META[k].l}</span>)}
            </div>
          </div>
          <div className="relative w-full rounded-xl overflow-hidden border border-white/10" style={{ height: 560, background: "repeating-linear-gradient(0deg,#0d0d10,#0d0d10 1px,transparent 1px,transparent 28px),repeating-linear-gradient(90deg,#0d0d10,#0d0d10 1px,transparent 1px,transparent 28px),#0a0a0c" }}>
            {/* stage marker (main floor) */}
            {floor === "main" && <div className="absolute left-1/2 -translate-x-1/2 px-4 py-1.5 rounded-b-xl bg-gradient-to-b from-coral/30 to-transparent border-x border-b border-coral/30 text-coral text-[9px] font-bold uppercase tracking-[0.2em]" style={{ top: 0 }}>{t("Main Stage", "Tarima")}</div>}
            {onFloor.map((tb) => {
              const st = effStatus(tb); const m = META[st]; const isVip = tb.zone === "vip" || tb.zone === "stage";
              const size = tb.seats >= 8 ? 50 : tb.seats >= 6 ? 44 : 38;
              return (
                <button key={tb.id} onClick={() => tb.status !== "closed" && setSel(tb)} disabled={tb.status === "closed"}
                  className="absolute -translate-x-1/2 -translate-y-1/2 flex items-center justify-center font-black transition-all hover:z-10 hover:scale-110"
                  style={{ left: tb.x + "%", top: tb.y + "%", width: size, height: size, borderRadius: tb.shape === "diamond" ? 8 : isVip ? 12 : 999, transform: `translate(-50%,-50%) rotate(${tb.shape === "diamond" ? 45 : 0}deg)`, background: st === "open" ? "transparent" : m.c + "26", border: "2px solid " + m.c, color: m.c, cursor: tb.status === "closed" ? "not-allowed" : "pointer", boxShadow: st === "seated" || st === "live" ? "0 0 16px " + m.c + "88" : "none" }}>
                  <span style={{ transform: tb.shape === "diamond" ? "rotate(-45deg)" : "none", fontSize: tb.id.length > 3 ? 9 : 12 }}>{tb.id.replace("VIP ", "V").replace("stg", "S")}</span>
                </button>
              );
            })}
          </div>
        </div>

        {/* DETAIL PANEL */}
        <div>
          {sel ? <FloorTableCard tb={sel} res={resByTable[sel.id]} meta={META} eff={effStatus(sel)} onClose={() => setSel(null)} />
            : (
              <div className="rounded-2xl border border-white/10 bg-card p-6 text-center lg:sticky lg:top-28">
                <Icon name="mouse-pointer-click" className="w-8 h-8 text-white/25 mx-auto mb-3" />
                <p className="text-white/50 text-sm">{t("Tap any table on the map to see its reservation, party and minimum.", "Toca cualquier mesa en el mapa para ver su reserva, grupo y mínimo.")}</p>
                <div className="mt-5 pt-5 border-t border-white/10 space-y-2 text-left">
                  {ZONES.map((z) => (
                    <div key={z.id} className="flex items-center gap-2.5 text-sm"><span className="w-3 h-3 rounded" style={{ background: z.accent }}></span><span className="text-white/65">{L(z.name, lang)}</span></div>
                  ))}
                </div>
              </div>
            )}
        </div>
      </div>
    </div>
  );
}

function FloorTableCard({ tb, res, meta, eff, onClose }) {
  const t = useT(); const { lang } = useLang();
  const { ZONES, tablePrice } = window.PP;
  const zone = ZONES.find((z) => z.id === tb.zone);
  const m = meta[eff];
  const min = tablePrice(tb.zone, 5);
  return (
    <div className="rounded-2xl border border-white/12 bg-card p-6 lg:sticky lg:top-28 fade-view">
      <div className="flex items-start justify-between mb-4">
        <div>
          <div className="label text-white/45 text-[10px] mb-1">{L(zone.name, lang)}</div>
          <div className="text-3xl font-black uppercase leading-none">{t("Table", "Mesa")} {tb.id.replace("VIP ", "VIP ")}</div>
        </div>
        <button onClick={onClose}><Icon name="x" className="w-5 h-5 text-white/50" /></button>
      </div>
      <div className="flex items-center gap-2 mb-5"><Chip color={m.c}>{m.l}</Chip><span className="text-white/45 text-xs">{t("Seats", "Asientos")} {tb.seats} · {t("Min", "Mín")} ${min}+</span></div>

      {res ? (
        <div className="space-y-3">
          <div className="rounded-xl border border-white/10 bg-ink p-4">
            <div className="font-bold text-base">{res.name}</div>
            <div className="text-white/45 text-xs mt-0.5">{res.code} · {res.time} · {res.party} {t("guests", "personas")}</div>
            <div className="flex flex-wrap gap-2 mt-3">
              <span className="px-2.5 py-1 rounded-md bg-white/5 border border-white/10 text-white/70 text-[11px]">{t("Min", "Mín")} ${res.min}</span>
              <span className="px-2.5 py-1 rounded-md bg-white/5 border border-white/10 text-white/70 text-[11px]">{t("Deposit", "Depósito")} ${res.deposit}</span>
              {res.promoter && <span className="px-2.5 py-1 rounded-md bg-coral/10 border border-coral/25 text-coral text-[11px]">{res.promoter}</span>}
            </div>
          </div>
          <div className="grid grid-cols-2 gap-2">
            {eff !== "seated" && <button className="gbtn py-3 rounded-full bg-coral hover:bg-coral-deep text-white text-[11px] font-bold uppercase tracking-wider flex items-center justify-center gap-2"><Icon name="armchair" className="w-4 h-4" />{t("Seat", "Sentar")}</button>}
            <button className={"py-3 rounded-full border border-white/15 text-white/80 text-[11px] font-bold uppercase tracking-wider hover:bg-white/5 flex items-center justify-center gap-2 " + (eff === "seated" ? "col-span-2" : "")}><Icon name="phone" className="w-4 h-4" />{t("Call guest", "Llamar")}</button>
          </div>
        </div>
      ) : (
        <div className="space-y-3">
          <p className="text-white/50 text-sm text-center py-3">{t("No reservation on this table tonight.", "Sin reserva en esta mesa esta noche.")}</p>
          <button className="gbtn w-full py-3 rounded-full bg-coral hover:bg-coral-deep text-white text-[11px] font-bold uppercase tracking-wider flex items-center justify-center gap-2"><Icon name="calendar-plus" className="w-4 h-4" />{t("Book this table", "Reservar esta mesa")}</button>
          <button className="w-full py-3 rounded-full border border-white/15 text-white/80 text-[11px] font-bold uppercase tracking-wider hover:bg-white/5 flex items-center justify-center gap-2"><Icon name="user-plus" className="w-4 h-4" />{t("Walk-in seat", "Sentar walk-in")}</button>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { FloorPlanModule, FloorTableCard });
