/* ============================================================
   ADMIN · TICKETERA — events, ticket types (paid/free/collab/comp),
   issue + QR, and the issued-ticket ledger.
   Shared helpers (FauxQR, ChargeButton, CardOnFile) come from admin.jsx.
   ============================================================ */
function Ticketera() {
  const t = useT(); const { lang } = useLang();
  const { ADMIN_EVENTS, TICKET_KINDS, ISSUED_TICKETS } = window.PP;
  const [evId, setEvId] = useState(ADMIN_EVENTS[0].id);
  const [tab, setTab] = useState("issue"); // issue | ledger | pos
  const ev = ADMIN_EVENTS.find((e) => e.id === evId);

  // issue state
  const [tierIdx, setTierIdx] = useState(0);
  const [qty, setQty] = useState(1);
  const [guest, setGuest] = useState("");
  const [issued, setIssued] = useState([...ISSUED_TICKETS]);
  const [receipt, setReceipt] = useState(null);
  const tier = ev.tiers[tierIdx];
  const total = (tier.price || 0) * qty;
  const isPaid = tier.kind === "paid" && total > 0;

  const totals = {
    sold: ev.tiers.reduce((s, x) => s + x.sold, 0),
    rev: ev.tiers.reduce((s, x) => s + x.sold * (x.price || 0), 0),
    free: ev.tiers.filter((x) => x.kind !== "paid").reduce((s, x) => s + x.sold, 0),
  };

  const doIssue = () => {
    const code = "PP-" + Math.random().toString(16).slice(2, 8).toUpperCase();
    setReceipt({ code, name: guest || t("Walk-up", "Walk-up"), qty, total, kind: tier.kind, tierName: L(tier.name, lang) });
    setIssued((arr) => [{ code, event: ev.name, kind: tier.kind, name: guest || t("Walk-up", "Walk-up"), qty, amt: total, when: t("just now", "ahora"), scanned: false }, ...arr]);
  };

  if (receipt) {
    const kc = TICKET_KINDS[receipt.kind].color;
    return (
      <div className="fade-view max-w-md mx-auto">
        <div className="rounded-3xl border border-white/12 bg-card p-7 text-center">
          <div className="w-14 h-14 rounded-full bg-green-500/15 border border-green-500 flex items-center justify-center mx-auto mb-4"><Icon name="check" className="w-7 h-7 text-green-400" /></div>
          <h3 className="text-2xl font-black uppercase mb-1">{receipt.total > 0 ? t("Ticket sold", "Ticket vendido") : t("Ticket issued", "Ticket emitido")}</h3>
          <p className="text-white/55 text-sm mb-1">{ev.name}</p>
          <div className="flex items-center justify-center gap-2 mb-5"><Chip color={kc}>{L(TICKET_KINDS[receipt.kind].label, lang)}</Chip><span className="text-white/55 text-sm">{receipt.qty}× {receipt.tierName}</span></div>
          <div className="flex flex-col items-center gap-3 mb-5"><FauxQR value={receipt.code} /><div className="font-mono text-coral tracking-widest text-sm">{receipt.code}</div><p className="text-white/45 text-xs">{receipt.total > 0 ? <>{t("Charged", "Cobrado")} <b className="text-gold-soft">${receipt.total}</b> · </> : null}{t("Scannable QR sent to phone & email.", "QR escaneable enviado al teléfono y correo.")}</p></div>
          <PrimaryBtn onClick={() => { setReceipt(null); setQty(1); setGuest(""); }} icon="plus">{t("Issue another", "Emitir otro")}</PrimaryBtn>
        </div>
      </div>
    );
  }

  return (
    <div>
      {/* event selector */}
      <div className="flex gap-2.5 overflow-x-auto mb-5 pb-1">
        {ADMIN_EVENTS.map((e) => (
          <button key={e.id} onClick={() => { setEvId(e.id); setTierIdx(0); }} className={"shrink-0 text-left px-4 py-3 rounded-2xl border transition-all min-w-[180px] " + (evId === e.id ? "border-coral bg-coral/10" : "border-white/12 bg-card hover:border-white/30")}>
            <div className="font-bold text-sm leading-tight">{e.name}</div>
            <div className="text-white/45 text-xs mt-0.5">{L(e.date, lang)}</div>
          </button>
        ))}
      </div>

      {/* event KPIs */}
      <div className="grid grid-cols-3 gap-3 mb-5">
        <div className="rounded-2xl border border-white/10 bg-card p-4"><div className="serif text-3xl text-gold-soft">{totals.sold}</div><div className="label text-white/45 text-[9px] mt-1">{t("Tickets out", "Tickets emitidos")} · {ev.cap}</div></div>
        <div className="rounded-2xl border border-white/10 bg-card p-4"><div className="serif text-3xl text-green-400">${(totals.rev / 1000).toFixed(1)}K</div><div className="label text-white/45 text-[9px] mt-1">{t("Ticket revenue", "Ingresos tickets")}</div></div>
        <div className="rounded-2xl border border-white/10 bg-card p-4"><div className="serif text-3xl text-coral">{totals.free}</div><div className="label text-white/45 text-[9px] mt-1">{t("Free / comp / collab", "Gratis / cortesía / collab")}</div></div>
      </div>

      {/* sub-tabs */}
      <div className="flex gap-2 border-b border-white/10 mb-6">
        {[["issue", t("Issue tickets", "Emitir tickets"), "ticket"], ["ledger", t("Issued ledger", "Registro emitidos"), "list"], ["pos", t("Other sales", "Otras ventas"), "shopping-bag"]].map(([id, lbl, ic]) => (
          <button key={id} onClick={() => setTab(id)} className={"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 === "issue" && (
        <div className="grid lg:grid-cols-12 gap-6">
          <div className="lg:col-span-7 space-y-2.5">
            {ev.tiers.map((tr, i) => {
              const kc = TICKET_KINDS[tr.kind].color;
              return (
                <button key={i} onClick={() => { setTierIdx(i); setQty(1); }} className={"w-full flex items-center gap-4 p-4 rounded-xl border text-left transition-all " + (tierIdx === i ? "border-coral bg-coral/10" : "border-white/12 bg-card hover:border-white/30")}>
                  <div className="w-1.5 h-10 rounded-full shrink-0" style={{ background: kc }}></div>
                  <div className="flex-1 min-w-0"><div className="font-bold text-sm">{L(tr.name, lang)}</div><div className="flex items-center gap-2 mt-1"><Chip color={kc}>{L(TICKET_KINDS[tr.kind].label, lang)}</Chip><span className="text-white/40 text-xs">{tr.sold} {t("issued", "emitidos")}</span></div></div>
                  <div className="serif text-2xl shrink-0" style={{ color: tr.price ? "var(--c-gold-soft)" : "#5FBFA8" }}>{tr.price ? "$" + tr.price : t("FREE", "GRATIS")}</div>
                </button>
              );
            })}
          </div>
          <div className="lg:col-span-5">
            <div className="rounded-2xl border border-white/12 bg-card p-6 lg:sticky lg:top-28">
              <div className="label text-white/45 text-[10px] mb-1">{t("Issuing", "Emitiendo")}</div>
              <div className="text-lg font-black uppercase leading-tight mb-1">{L(tier.name, lang)}</div>
              <Chip color={TICKET_KINDS[tier.kind].color} className="mb-4">{L(TICKET_KINDS[tier.kind].label, lang)}</Chip>
              <div className="mt-2 mb-4"><label className="label text-white/45 text-[10px] block mb-1.5">{t("Guest name (optional)", "Nombre del invitado (opcional)")}</label><input value={guest} onChange={(e) => setGuest(e.target.value)} placeholder={t("Walk-up", "Walk-up")} className="w-full 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" /></div>
              <div className="flex items-center justify-between mb-4"><span className="text-sm text-white/60">{t("Quantity", "Cantidad")}</span>
                <div className="flex items-center gap-3"><button onClick={() => setQty((q) => Math.max(1, q - 1))} className="w-8 h-8 rounded-lg bg-white/5 flex items-center justify-center"><Icon name="minus" className="w-4 h-4" /></button><span className="font-bold w-6 text-center">{qty}</span><button onClick={() => setQty((q) => q + 1)} className="w-8 h-8 rounded-lg bg-white/5 flex items-center justify-center"><Icon name="plus" className="w-4 h-4" /></button></div>
              </div>
              <div className="flex items-center justify-between py-3 border-t border-b border-white/10 mb-4"><span className="font-bold uppercase tracking-wide text-sm">{t("Total", "Total")}</span><span className="serif text-3xl" style={{ color: total ? "var(--c-gold-soft)" : "#5FBFA8" }}>{total ? "$" + total : t("No charge", "Sin cargo")}</span></div>
              {isPaid ? <><div className="mb-4"><CardOnFile /></div><ChargeButton amount={total} label={t("Charge & issue", "Cobrar y emitir")} onDone={doIssue} /></>
                : <button onClick={doIssue} className="gbtn w-full py-3.5 rounded-full bg-coral hover:bg-coral-deep text-white text-[12px] font-bold uppercase tracking-[0.14em] flex items-center justify-center gap-2"><Icon name="ticket" className="w-4 h-4" />{t("Issue ticket", "Emitir ticket")}</button>}
              <p className="text-white/40 text-[11px] text-center mt-3">{t("Generates a unique QR — scan at the door to prevent duplicates.", "Genera un QR único — se escanea en la puerta para evitar duplicados.")}</p>
            </div>
          </div>
        </div>
      )}

      {tab === "ledger" && (
        <div className="space-y-2">
          {issued.map((it, i) => {
            const kc = TICKET_KINDS[it.kind].color;
            return (
              <div key={it.code + i} className="flex items-center gap-3 p-3.5 rounded-xl border border-white/10 bg-card">
                <FauxQR value={it.code} size={42} />
                <div className="flex-1 min-w-0"><div className="font-bold text-sm truncate">{it.name}</div><div className="text-white/45 text-xs font-mono">{it.code} · {it.qty}×</div></div>
                <div className="hidden sm:block text-white/40 text-xs truncate max-w-[160px]">{it.event}</div>
                <Chip color={kc}>{L(window.PP.TICKET_KINDS[it.kind].label, lang)}</Chip>
                <div className="text-right shrink-0 w-16"><div className="serif text-lg text-gold-soft">{it.amt ? "$" + it.amt : "—"}</div><div className="text-white/35 text-[10px]">{it.when}</div></div>
                {it.scanned ? <span className="text-green-400 text-[11px] font-bold flex items-center gap-1 w-20 justify-end"><Icon name="check-circle" className="w-3.5 h-3.5" />{t("Scanned", "Escaneado")}</span>
                  : <span className="text-white/40 text-[11px] w-20 text-right">{t("Not in", "Sin entrar")}</span>}
              </div>
            );
          })}
        </div>
      )}

      {tab === "pos" && (
        <div>
          <div className="rounded-xl border border-gold/25 bg-gold/5 p-4 mb-5 flex items-center gap-3"><Icon name="info" className="w-5 h-5 text-gold-soft shrink-0" /><p className="text-white/65 text-sm">{t("Quick point-of-sale for merch, memberships and experience packages.", "Punto de venta rápido para merch, membresías y paquetes de experiencia.")}</p></div>
          <BoxOffice />
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Ticketera });
