/* ============================================================
   ADMIN · INVITATIONS — real, admin-issued invitations.
   Each invite gets a unique door code (PP-XXXXXX), persists in
   PPDB, can be sent by WhatsApp, and is verifiable in Door/Scan.
   ============================================================ */
function useInvites() {
  const [list, setList] = useState(() => window.PPDB.invites.all());
  useEffect(() => {
    const f = () => setList(window.PPDB.invites.all());
    window.addEventListener("pp:invites", f);
    return () => window.removeEventListener("pp:invites", f);
  }, []);
  return list;
}

function InvitesModule() {
  const t = useT(); const { lang } = useLang();
  const list = useInvites();
  const today = new Date().toISOString().slice(0, 10);
  const [form, setForm] = useState({ name: "", phone: "", date: today, party: 2, type: "guestlist", note: "" });
  const [justMade, setJustMade] = useState(null);
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const TYPES = {
    guestlist: { l: t("Guestlist", "Guestlist"), c: "#5FBFA8", ic: "list" },
    vip: { l: t("VIP / Table", "VIP / Mesa"), c: "#CBA35C", ic: "crown" },
    comp: { l: t("Comp / Guest of house", "Cortesía"), c: "#9333EA", ic: "gift" },
  };
  const ST = {
    active: { l: t("Active", "Activa"), c: "#5FBFA8" },
    in: { l: t("Checked in", "Adentro"), c: "#CBA35C" },
    cancelled: { l: t("Cancelled", "Cancelada"), c: "#777" },
  };

  const create = (e) => {
    e.preventDefault();
    if (!form.name.trim()) return;
    const inv = window.PPDB.invites.add({
      name: form.name.trim(), phone: form.phone.replace(/[^\d+]/g, ""),
      date: form.date, party: Math.max(1, Number(form.party) || 1),
      type: form.type, note: form.note.trim(),
    });
    setJustMade(inv);
    setForm({ name: "", phone: "", date: form.date, party: 2, type: form.type, note: "" });
    if (window.PP && window.PP.track) window.PP.track("Lead", { content_name: "admin_invite" });
  };

  const waText = (inv) => {
    const d = new Date(inv.date + "T20:00:00");
    const ds = d.toLocaleDateString(lang === "es" ? "es" : "en", { weekday: "long", month: "short", day: "numeric" });
    return lang === "es"
      ? `🩷 PINK PONY CLUB — Invitación\n\n${inv.name}, estás en la lista para ${ds}.\n\n🎟 Código de puerta: ${inv.code}\n👥 ${inv.party} persona(s)\n📍 7971 NW 33rd St, Doral, FL 33122\n\nPresenta este código en la entrada. 21+ con ID válido.`
      : `🩷 PINK PONY CLUB — Invitation\n\n${inv.name}, you're on the list for ${ds}.\n\n🎟 Door code: ${inv.code}\n👥 ${inv.party} guest(s)\n📍 7971 NW 33rd St, Doral, FL 33122\n\nShow this code at the door. 21+ with valid ID.`;
  };
  const waSend = (inv) => {
    const base = inv.phone ? "https://wa.me/" + inv.phone.replace(/^\+/, "") : "https://wa.me/";
    window.open(base + "?text=" + encodeURIComponent(waText(inv)), "_blank");
  };
  const copyCode = (inv) => { try { navigator.clipboard.writeText(inv.code); } catch (e) {} };

  const active = list.filter((x) => x.status === "active");
  const inside = list.filter((x) => x.status === "in");
  const heads = inside.reduce((s, x) => s + (x.party || 1), 0);

  return (
    <div>
      {/* stats */}
      <div className="grid grid-cols-3 gap-3 mb-6">
        {[[active.length, t("Active invites", "Invitaciones activas"), "#5FBFA8"], [inside.length, t("Checked in", "Adentro"), "#CBA35C"], [heads, t("Guests inside", "Personas adentro"), "#FF6B5B"]].map(([n, l, c], i) => (
          <div key={i} className="rounded-2xl border border-white/10 bg-card p-4 text-center"><div className="serif text-3xl" style={{ color: c }}>{n}</div><div className="label text-white/45 text-[9px] mt-1">{l}</div></div>
        ))}
      </div>

      <div className="grid lg:grid-cols-12 gap-6 items-start">
        {/* create form */}
        <div className="lg:col-span-5">
          <form onSubmit={create} className="rounded-2xl border border-white/12 bg-card p-5 space-y-3.5">
            <div className="label text-coral text-[10px]">{t("New invitation", "Nueva invitación")}</div>
            <input value={form.name} onChange={(e) => set("name", e.target.value)} placeholder={t("Guest name *", "Nombre del invitado *")} required className="w-full bg-ink border border-white/12 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-coral placeholder:text-white/35" />
            <input value={form.phone} onChange={(e) => set("phone", e.target.value)} placeholder={t("WhatsApp (optional, e.g. +1786…)", "WhatsApp (opcional, ej. +1786…)")} className="w-full bg-ink border border-white/12 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-coral placeholder:text-white/35" />
            <div className="grid grid-cols-2 gap-3">
              <div><label className="label text-white/45 text-[9px] block mb-1.5">{t("Night", "Noche")}</label><input type="date" value={form.date} min={today} onChange={(e) => set("date", e.target.value)} className="w-full bg-ink border border-white/12 rounded-xl px-3 py-3 text-sm text-white focus:outline-none focus:border-coral" style={{ colorScheme: "dark" }} /></div>
              <div><label className="label text-white/45 text-[9px] block mb-1.5">{t("Guests", "Personas")}</label><input type="number" min="1" max="40" value={form.party} onChange={(e) => set("party", e.target.value)} className="w-full bg-ink border border-white/12 rounded-xl px-3 py-3 text-sm text-white focus:outline-none focus:border-coral" /></div>
            </div>
            <div className="flex gap-2">
              {Object.entries(TYPES).map(([id, ty]) => (
                <button type="button" key={id} onClick={() => set("type", id)} className={"flex-1 px-2 py-2.5 rounded-xl text-[10px] font-bold uppercase tracking-wider border transition-all " + (form.type === id ? "text-white" : "text-white/45 border-white/12 hover:text-white")} style={form.type === id ? { background: ty.c + "22", borderColor: ty.c } : {}}>{ty.l}</button>
              ))}
            </div>
            <input value={form.note} onChange={(e) => set("note", e.target.value)} placeholder={t("Note (optional)", "Nota (opcional)")} className="w-full bg-ink border border-white/12 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-coral placeholder:text-white/35" />
            <button 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="user-plus" className="w-4 h-4" />{t("Create invitation", "Crear invitación")}</button>
          </form>

          {justMade && (
            <div className="mt-4 rounded-2xl border border-green-400/40 bg-green-400/10 p-5 text-center fade-view">
              <div className="label text-green-400 text-[10px] mb-2">{t("Invitation created", "Invitación creada")}</div>
              <div className="font-mono text-2xl tracking-[0.2em] text-white mb-1">{justMade.code}</div>
              <div className="text-white/55 text-xs mb-4">{justMade.name} · {justMade.party} {t("guests", "personas")}</div>
              <div className="flex gap-2 justify-center">
                <button onClick={() => waSend(justMade)} className="inline-flex items-center gap-2 px-5 py-2.5 rounded-full bg-[#25D366] text-black text-[11px] font-bold uppercase tracking-wider"><Icon name="message-circle" className="w-4 h-4" />{t("Send by WhatsApp", "Enviar por WhatsApp")}</button>
                <button onClick={() => copyCode(justMade)} className="inline-flex items-center gap-2 px-4 py-2.5 rounded-full border border-white/20 text-white/80 text-[11px] font-bold uppercase tracking-wider hover:bg-white/5"><Icon name="copy" className="w-4 h-4" />{t("Copy", "Copiar")}</button>
              </div>
            </div>
          )}
        </div>

        {/* list */}
        <div className="lg:col-span-7">
          {list.length === 0 ? (
            <div className="rounded-2xl border border-dashed border-white/15 p-10 text-center text-white/45 text-sm">
              <Icon name="mail" className="w-8 h-8 mx-auto mb-3 text-white/25" />
              {t("No invitations yet. Every invitation you create here is real — it gets a unique door code your team verifies at Door / Scan.", "Aún no hay invitaciones. Cada invitación que crees aquí es real — recibe un código único que tu equipo verifica en Puerta / Escáner.")}
            </div>
          ) : (
            <div className="space-y-2 max-h-[560px] overflow-y-auto pr-1">
              {list.map((inv) => {
                const ty = TYPES[inv.type] || TYPES.guestlist;
                const st = ST[inv.status] || ST.active;
                return (
                  <div key={inv.id} className={"rounded-xl border border-white/10 bg-card p-3.5 " + (inv.status === "cancelled" ? "opacity-50" : "")}>
                    <div className="flex items-center gap-3">
                      <div className="w-9 h-9 rounded-lg flex items-center justify-center shrink-0" style={{ background: ty.c + "1f", border: "1px solid " + ty.c + "55" }}><Icon name={ty.ic} className="w-4 h-4" style={{ color: ty.c }} /></div>
                      <div className="flex-1 min-w-0">
                        <div className="font-bold text-sm truncate">{inv.name} <span className="text-white/35 font-normal">×{inv.party}</span></div>
                        <div className="text-white/45 text-[11px] flex flex-wrap items-center gap-x-2"><span className="font-mono text-gold-soft">{inv.code}</span><span>·</span><span>{inv.date}</span>{inv.note && <><span>·</span><span className="truncate">{inv.note}</span></>}</div>
                      </div>
                      <Chip color={st.c}>{st.l}</Chip>
                    </div>
                    <div className="flex gap-1.5 mt-2.5 pl-12">
                      <button onClick={() => waSend(inv)} className="px-3 py-1.5 rounded-full border border-white/12 text-white/65 text-[10px] font-bold uppercase tracking-wider hover:text-white hover:bg-white/5 inline-flex items-center gap-1.5"><Icon name="message-circle" className="w-3 h-3" />WhatsApp</button>
                      <button onClick={() => copyCode(inv)} className="px-3 py-1.5 rounded-full border border-white/12 text-white/65 text-[10px] font-bold uppercase tracking-wider hover:text-white hover:bg-white/5 inline-flex items-center gap-1.5"><Icon name="copy" className="w-3 h-3" />{t("Copy", "Copiar")}</button>
                      {inv.status === "active" && <button onClick={() => window.PPDB.invites.update(inv.id, { status: "cancelled" })} className="px-3 py-1.5 rounded-full border border-white/12 text-white/45 text-[10px] font-bold uppercase tracking-wider hover:text-coral hover:border-coral/40">{t("Cancel", "Cancelar")}</button>}
                      {inv.status === "cancelled" && <>
                        <button onClick={() => window.PPDB.invites.update(inv.id, { status: "active" })} className="px-3 py-1.5 rounded-full border border-white/12 text-white/45 text-[10px] font-bold uppercase tracking-wider hover:text-green-400 hover:border-green-400/40">{t("Reactivate", "Reactivar")}</button>
                        <button onClick={() => window.PPDB.invites.remove(inv.id)} className="px-3 py-1.5 rounded-full border border-white/12 text-white/45 text-[10px] font-bold uppercase tracking-wider hover:text-coral hover:border-coral/40"><Icon name="trash-2" className="w-3 h-3" /></button>
                      </>}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { InvitesModule, useInvites });
