/* ============================================================
   ADMIN · MENUS & DISCOUNTS — total control of the public menu.
   Every change persists (PPDB) and updates the live Menu page:
   hide/show items & whole categories, edit names & prices,
   add custom items, manage discounts, public QR & permissions.
   ============================================================ */
/* editable row — top-level component so inputs keep focus across renders */
function MenuRow({ img, name, desc, price, off, onName, onPrice, onToggle, onDelete }) {
  const t = useT();
  return (
    <div className={"flex flex-wrap sm:flex-nowrap items-center gap-3 sm:gap-4 px-4 sm:px-5 py-3.5 border-b border-white/5 transition-opacity " + (off ? "opacity-45" : "")}>
      <div className="w-10 h-10 rounded-lg overflow-hidden bg-ink shrink-0">{img ? <img src={window.PP.SRC(img, 80, 80)} alt="" className="w-full h-full object-cover" /> : <div className="w-full h-full flex items-center justify-center"><Icon name="image" className="w-4 h-4 text-white/20" /></div>}</div>
      <div className="flex-1 min-w-[140px]">
        <input value={name} onChange={(e) => onName(e.target.value)} className="w-full bg-transparent font-bold text-sm text-white focus:outline-none focus:bg-ink rounded px-1 -mx-1 border border-transparent focus:border-coral/50" />
        {desc && <div className="text-white/40 text-xs truncate">{desc}</div>}
      </div>
      <div className="flex items-center gap-1 shrink-0"><span className="serif text-gold-soft">$</span>
        <input type="number" min="0" value={price} onChange={(e) => onPrice(e.target.value)} className="w-16 bg-ink border border-white/12 rounded-lg px-2 py-1.5 text-sm text-gold-soft focus:outline-none focus:border-coral" />
      </div>
      <button onClick={onToggle} className={"relative w-11 h-6 rounded-full transition-colors shrink-0 " + (off ? "bg-white/12" : "bg-green-500")} title={off ? t("Hidden on public menu", "Oculto en el menú público") : t("Live on public menu", "Visible en el menú público")}>
        <span className={"absolute top-0.5 w-5 h-5 rounded-full bg-white transition-all " + (off ? "left-0.5" : "left-[22px]")}></span>
      </button>
      {onDelete && <button onClick={onDelete} className="shrink-0 text-white/35 hover:text-coral" title={t("Delete", "Borrar")}><Icon name="trash-2" className="w-4 h-4" /></button>}
    </div>
  );
}

function MenusModule() {
  const t = useT(); const { lang } = useLang();
  const { MENU, MENU_ADMIN, DISCOUNTS, ADMIN_ROLES } = window.PP;
  const [tab, setTab] = useState("menus");
  const [activeCat, setActiveCat] = useState("cocktails");
  const [ov, setOv] = useState(() => window.PPDB.menu.ov());
  const [adding, setAdding] = useState(false);
  const [draft, setDraft] = useState({ name: "", price: "", d: "" });
  const [disStates, setDisStates] = useState(() => window.PPDB.discounts.states());
  useEffect(() => {
    const f = () => setOv(window.PPDB.menu.ov());
    window.addEventListener("pp:menu", f);
    return () => window.removeEventListener("pp:menu", f);
  }, []);
  const patch = (fn) => window.PPDB.menu.patch(fn);
  const k = (i) => activeCat + ":" + i;
  const isOff = (i) => !!ov.hidden[k(i)];
  const catOff = !!ov.hiddenCats[activeCat];

  const items = MENU[activeCat] || [];
  const custom = ov.custom[activeCat] || [];
  const liveCount = items.filter((_, i) => !isOff(i)).length + custom.filter((c) => !c.hidden).length;

  const addItem = (e) => {
    e.preventDefault();
    if (!draft.name.trim() || !draft.price) return;
    patch((o) => { o.custom[activeCat] = (o.custom[activeCat] || []).concat([{ id: Date.now().toString(36), name: draft.name.trim(), price: Number(draft.price), d: draft.d.trim() }]); });
    setDraft({ name: "", price: "", d: "" }); setAdding(false);
  };

  return (
    <div>
      <div className="flex gap-2 border-b border-white/10 mb-6 overflow-x-auto">
        {[["menus", t("Digital Menus", "Menús Digitales"), "book-open"], ["discounts", t("Discounts", "Descuentos"), "percent"], ["qr", t("Public QR", "QR Público"), "qr-code"], ["roles", t("Permissions", "Permisos"), "shield"]].map(([id, lbl, ic]) => (
          <button key={id} onClick={() => setTab(id)} className={"shrink-0 inline-flex items-center gap-2 px-4 py-3 text-[12px] font-bold uppercase tracking-[0.1em] border-b-2 -mb-px transition-all " + (tab === id ? "border-coral text-white" : "border-transparent text-white/50 hover:text-white")}><Icon name={ic} className="w-4 h-4" />{lbl}</button>
        ))}
      </div>

      {tab === "menus" && (
        <div>
          <div className="rounded-2xl border border-gold/25 bg-gold/5 p-4 mb-5 flex items-center gap-3"><Icon name="zap" className="w-5 h-5 text-gold-soft shrink-0" /><p className="text-white/65 text-sm">{t("Everything here is live — changes apply to the public Menu page instantly on this device.", "Todo aquí es en vivo — los cambios se aplican al instante en la página pública del Menú en este dispositivo.")}</p></div>
          <div className="flex gap-2 mb-5 overflow-x-auto">
            {MENU_ADMIN.map((m) => (
              <button key={m.id} onClick={() => setActiveCat(m.id)} className={"shrink-0 inline-flex items-center gap-2 px-4 py-2.5 rounded-full text-[12px] font-bold uppercase tracking-wider transition-all " + (activeCat === m.id ? "bg-coral text-white" : "bg-card border border-white/12 text-white/60 hover:text-white") + (ov.hiddenCats[m.id] ? " line-through opacity-60" : "")}><Icon name={m.icon} className="w-4 h-4" />{L(m.label, lang)}</button>
            ))}
          </div>
          <div className="rounded-2xl border border-white/10 bg-card overflow-hidden">
            <div className="flex flex-wrap items-center justify-between gap-3 px-4 sm:px-5 py-3 border-b border-white/10">
              <span className="label text-white/45 text-[10px]">{items.length + custom.length} {t("items", "items")} · {catOff ? t("category hidden", "categoría oculta") : liveCount + " " + t("live", "activos")}</span>
              <div className="flex items-center gap-3">
                <label className="flex items-center gap-2 text-[11px] font-bold uppercase tracking-wider text-white/60">
                  {t("Category visible", "Categoría visible")}
                  <button onClick={() => patch((o) => { o.hiddenCats[activeCat] = !o.hiddenCats[activeCat]; })} className={"relative w-11 h-6 rounded-full transition-colors " + (catOff ? "bg-white/12" : "bg-green-500")}>
                    <span className={"absolute top-0.5 w-5 h-5 rounded-full bg-white transition-all " + (catOff ? "left-0.5" : "left-[22px]")}></span>
                  </button>
                </label>
                <button onClick={() => setAdding((a) => !a)} className="text-coral text-[11px] font-bold uppercase tracking-wider flex items-center gap-1.5"><Icon name={adding ? "x" : "plus"} className="w-3.5 h-3.5" />{adding ? t("Cancel", "Cancelar") : t("Add item", "Agregar item")}</button>
              </div>
            </div>
            {adding && (
              <form onSubmit={addItem} className="px-4 sm:px-5 py-4 border-b border-white/10 bg-ink/40 grid sm:grid-cols-[1fr_110px_auto] gap-3">
                <input value={draft.name} onChange={(e) => setDraft((d) => ({ ...d, name: e.target.value }))} placeholder={t("Item name *", "Nombre del item *")} required className="bg-ink border border-white/12 rounded-xl px-3 py-2.5 text-sm text-white focus:outline-none focus:border-coral placeholder:text-white/35" />
                <input type="number" min="0" value={draft.price} onChange={(e) => setDraft((d) => ({ ...d, price: e.target.value }))} placeholder={t("Price *", "Precio *")} required className="bg-ink border border-white/12 rounded-xl px-3 py-2.5 text-sm text-white focus:outline-none focus:border-coral placeholder:text-white/35" />
                <button className="px-5 py-2.5 rounded-xl bg-coral text-white text-[11px] font-bold uppercase tracking-wider">{t("Add", "Agregar")}</button>
                <input value={draft.d} onChange={(e) => setDraft((d) => ({ ...d, d: e.target.value }))} placeholder={t("Description (optional)", "Descripción (opcional)")} className="sm:col-span-3 bg-ink border border-white/12 rounded-xl px-3 py-2.5 text-sm text-white focus:outline-none focus:border-coral placeholder:text-white/35" />
              </form>
            )}
            {items.map((it, i) => (
              <MenuRow key={i}
                img={it.img} off={isOff(i)}
                name={ov.name[k(i)] || it.name}
                desc={(it.d || it.flavor) ? L(it.d || it.flavor, lang) : (it.cat || "")}
                price={ov.price[k(i)] != null && ov.price[k(i)] !== "" ? ov.price[k(i)] : it.price}
                onName={(v) => patch((o) => { if (v && v !== it.name) o.name[k(i)] = v; else delete o.name[k(i)]; })}
                onPrice={(v) => patch((o) => { if (v !== "" && Number(v) !== it.price) o.price[k(i)] = Number(v); else delete o.price[k(i)]; })}
                onToggle={() => patch((o) => { if (o.hidden[k(i)]) delete o.hidden[k(i)]; else o.hidden[k(i)] = true; })}
              />
            ))}
            {custom.map((c) => (
              <MenuRow key={c.id}
                img={null} off={!!c.hidden}
                name={c.name} desc={c.d || t("Custom item", "Item personalizado")} price={c.price}
                onName={(v) => patch((o) => { o.custom[activeCat] = o.custom[activeCat].map((x) => x.id === c.id ? { ...x, name: v } : x); })}
                onPrice={(v) => patch((o) => { o.custom[activeCat] = o.custom[activeCat].map((x) => x.id === c.id ? { ...x, price: Number(v) || 0 } : x); })}
                onToggle={() => patch((o) => { o.custom[activeCat] = o.custom[activeCat].map((x) => x.id === c.id ? { ...x, hidden: !x.hidden } : x); })}
                onDelete={() => patch((o) => { o.custom[activeCat] = o.custom[activeCat].filter((x) => x.id !== c.id); })}
              />
            ))}
          </div>
        </div>
      )}

      {tab === "discounts" && (
        <div className="space-y-2.5">
          {DISCOUNTS.map((d) => {
            const active = disStates[d.id] != null ? disStates[d.id] : d.active;
            return (
              <div key={d.id} className="flex items-center gap-4 p-4 rounded-2xl border border-white/10 bg-card">
                <div className="w-11 h-11 rounded-xl bg-coral/12 border border-coral/30 flex items-center justify-center shrink-0"><Icon name={d.kind === "bogo" ? "copy" : d.kind === "pct" ? "percent" : d.kind === "free" ? "gift" : "badge-dollar-sign"} className="w-5 h-5 text-coral" /></div>
                <div className="flex-1 min-w-0">
                  <div className="font-bold text-sm truncate">{L(d.desc, lang)}</div>
                  <div className="text-white/45 text-xs flex flex-wrap items-center gap-2 mt-0.5"><span className="font-mono text-gold-soft">{d.code}</span><span>·</span><span>{L(d.scope, lang)}</span><span>·</span><span>{L(d.days, lang)}</span></div>
                </div>
                <button onClick={() => { window.PPDB.discounts.toggle(d.id, !active); setDisStates(window.PPDB.discounts.states()); }} className={"relative w-11 h-6 rounded-full transition-colors shrink-0 " + (active ? "bg-green-500" : "bg-white/12")}>
                  <span className={"absolute top-0.5 w-5 h-5 rounded-full bg-white transition-all " + (active ? "left-[22px]" : "left-0.5")}></span>
                </button>
              </div>
            );
          })}
        </div>
      )}

      {tab === "qr" && (
        <div className="grid lg:grid-cols-2 gap-6 items-start">
          <div className="rounded-2xl border border-white/10 bg-card p-7 text-center">
            <div className="inline-block p-4 bg-white rounded-2xl mb-4"><FauxQR value="clubpinkpony.com/menu" size={180} /></div>
            <div className="font-mono text-coral tracking-widest text-sm mb-1">clubpinkpony.com/menu</div>
            <p className="text-white/45 text-xs mb-5">{t("Customers scan this at the table to browse all live menus on their phone.", "Los clientes escanean esto en la mesa para ver todos los menús activos en su teléfono.")}</p>
            <div className="flex gap-2 justify-center">
              <button className="inline-flex items-center gap-2 px-5 py-3 rounded-full bg-coral hover:bg-coral-deep text-white text-[11px] font-bold uppercase tracking-wider transition-all"><Icon name="download" className="w-4 h-4" />{t("Download", "Descargar")}</button>
              <button className="inline-flex items-center gap-2 px-5 py-3 rounded-full border border-white/15 text-white/80 text-[11px] font-bold uppercase tracking-wider hover:bg-white/5 transition-all"><Icon name="printer" className="w-4 h-4" />{t("Print table tents", "Imprimir mesas")}</button>
            </div>
          </div>
          <div className="space-y-3">
            <div className="label text-white/45 text-[10px]">{t("Per-menu QR codes", "Códigos QR por menú")}</div>
            {MENU_ADMIN.map((m) => (
              <div key={m.id} className="flex items-center gap-4 p-4 rounded-2xl border border-white/10 bg-card">
                <div className="p-1.5 bg-white rounded-lg shrink-0"><FauxQR value={"clubpinkpony.com/menu/" + m.id} size={48} /></div>
                <div className="flex-1 min-w-0"><div className="font-bold text-sm flex items-center gap-2"><Icon name={m.icon} className="w-4 h-4 text-coral" />{L(m.label, lang)}</div><div className="text-white/40 text-xs font-mono truncate">/menu/{m.id}</div></div>
                <button className="px-3 py-2 rounded-full border border-white/15 text-white/70 text-[11px] font-bold uppercase tracking-wider hover:bg-white/5 transition-all flex items-center gap-1.5"><Icon name="download" className="w-3.5 h-3.5" />{t("Get", "Obtener")}</button>
              </div>
            ))}
          </div>
        </div>
      )}

      {tab === "roles" && (
        <div>
          <div className="rounded-2xl border border-gold/25 bg-gold/5 p-4 mb-5 flex items-center gap-3"><Icon name="shield" className="w-5 h-5 text-gold-soft shrink-0" /><p className="text-white/65 text-sm">{t("Menus and discounts can only be edited by Owners and Managers. Assign portal access per role below.", "Los menús y descuentos solo los pueden editar Dueños y Gerentes. Asigna acceso al portal por rol abajo.")}</p></div>
          <div className="space-y-3">
            {ADMIN_ROLES.map((r) => (
              <div key={r.id} className="rounded-2xl border border-white/10 bg-card p-5">
                <div className="flex items-center justify-between mb-3"><div className="font-bold text-base">{L(r.name, lang)}</div><Chip color={r.perms.includes("all") ? "#FF6B5B" : "#5FBFA8"}>{r.perms.includes("all") ? t("Full access", "Acceso total") : r.perms.length + " " + t("modules", "módulos")}</Chip></div>
                <div className="flex flex-wrap gap-2">
                  {(r.perms.includes("all") ? ["tickets", "door", "res", "crm", "staff", "dancers", "menus", "discounts"] : r.perms).map((p) => (
                    <span key={p} className="px-2.5 py-1 rounded-md bg-white/5 border border-white/10 text-white/70 text-[11px] font-semibold capitalize">{p}</span>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { MenusModule });
