/* ============================================================
   ADMIN · EVENTS — add one-off events to the public calendar
   (special nights, live shows, watch parties) without touching code.
   Persists via PPDB.events (localStorage + Firestore). Appears on the
   Events calendar and Tonight banner automatically by date.
   ============================================================ */
function useAdminEvents() {
  const [list, setList] = useState(() => window.PPDB.events.all());
  useEffect(() => {
    const f = () => setList(window.PPDB.events.all());
    window.addEventListener("pp:events", f);
    return () => window.removeEventListener("pp:events", f);
  }, []);
  return list;
}

function EventsModule() {
  const t = useT(); const { lang } = useLang();
  const list = useAdminEvents();
  const today = new Date().toISOString().slice(0, 10);
  const blank = { title: "", iso: today, time: "10PM", type: "special", note: "" };
  const [form, setForm] = useState(blank);
  const [editId, setEditId] = useState(null);
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const TYPES = {
    special: { l: t("Special Event", "Evento Especial"), c: "#FF2E88", ic: "sparkles" },
    live: { l: t("Live Performance", "Show en Vivo"), c: "#FF6B5B", ic: "mic-vocal" },
    sport: { l: t("Watch Party", "Watch Party"), c: "#5FBFA8", ic: "trophy" },
  };

  const save = (e) => {
    e.preventDefault();
    if (!form.title.trim() || !form.iso) return;
    const data = { title: form.title.trim(), iso: form.iso, time: form.time.trim() || "10PM", type: form.type, note: form.note.trim() };
    if (editId) { window.PPDB.events.update(editId, data); setEditId(null); }
    else window.PPDB.events.add(data);
    setForm({ ...blank, iso: form.iso, type: form.type });
  };
  const edit = (ev) => { setEditId(ev.id); setForm({ title: ev.title, iso: ev.iso, time: ev.time || "10PM", type: ev.type || "special", note: ev.note || "" }); window.scrollTo({ top: 0, behavior: "smooth" }); };
  const fmt = (iso) => { try { return new Date(iso + "T12:00:00").toLocaleDateString(lang === "es" ? "es" : "en", { weekday: "short", month: "short", day: "numeric" }); } catch (e) { return iso; } };
  const upcoming = list.filter((e) => e.iso >= today);
  const past = list.filter((e) => e.iso < today);

  return (
    <div>
      <div className="rounded-2xl border border-gold/25 bg-gold/5 p-4 mb-6 flex items-center gap-3"><Icon name="calendar-plus" className="w-5 h-5 text-gold-soft shrink-0" /><p className="text-white/65 text-sm">{t("Events you add here show on the public Events calendar and the 'Tonight' banner automatically, on their date. The 7 weekly nights are always shown — this is for one-offs.", "Los eventos que agregues aquí aparecen en el calendario público y en el banner 'Hoy', en su fecha. Las 7 noches semanales siempre se muestran — esto es para eventos puntuales.")}</p></div>

      <div className="grid lg:grid-cols-12 gap-6 items-start">
        {/* form */}
        <div className="lg:col-span-5">
          <form onSubmit={save} className="rounded-2xl border border-white/12 bg-card p-5 space-y-3.5">
            <div className="label text-coral text-[10px]">{editId ? t("Edit event", "Editar evento") : t("New event", "Nuevo evento")}</div>
            <input value={form.title} onChange={(e) => set("title", e.target.value)} placeholder={t("Event name * (e.g. Bad Bunny Night)", "Nombre del evento * (ej. Noche de Bad Bunny)")} 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" />
            <div className="grid grid-cols-2 gap-3">
              <div><label className="label text-white/45 text-[9px] block mb-1.5">{t("Date", "Fecha")}</label><input type="date" value={form.iso} min={today} onChange={(e) => set("iso", 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("Time", "Hora")}</label><input value={form.time} onChange={(e) => set("time", e.target.value)} placeholder="10PM" 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 placeholder:text-white/35" /></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 inline-flex items-center justify-center gap-1.5 " + (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 } : {}}><Icon name={ty.ic} className="w-3.5 h-3.5" />{ty.l}</button>
              ))}
            </div>
            <input value={form.note} onChange={(e) => set("note", e.target.value)} placeholder={t("Note (optional) — DJ, special, etc.", "Nota (opcional) — DJ, especial, etc.")} 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="flex gap-2">
              <button className="gbtn flex-1 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={editId ? "check" : "plus"} className="w-4 h-4" />{editId ? t("Save changes", "Guardar cambios") : t("Add to calendar", "Agregar al calendario")}</button>
              {editId && <button type="button" onClick={() => { setEditId(null); setForm(blank); }} className="px-4 py-3.5 rounded-full border border-white/15 text-white/70 text-[12px] font-bold uppercase tracking-wider hover:bg-white/5">{t("Cancel", "Cancelar")}</button>}
            </div>
          </form>
        </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="calendar-days" className="w-8 h-8 mx-auto mb-3 text-white/25" />
              {t("No custom events yet. Add your first one — it'll appear on the public calendar instantly.", "Aún no hay eventos personalizados. Agrega el primero — aparecerá en el calendario público al instante.")}
            </div>
          ) : (
            <div className="space-y-4">
              {[[t("Upcoming", "Próximos"), upcoming], [t("Past", "Pasados"), past]].map(([label, arr]) => arr.length > 0 && (
                <div key={label}>
                  <div className="label text-white/40 text-[10px] mb-2">{label} · {arr.length}</div>
                  <div className="space-y-2">
                    {arr.map((ev) => {
                      const ty = TYPES[ev.type] || TYPES.special;
                      return (
                        <div key={ev.id} className={"flex items-center gap-3 rounded-xl border border-white/10 bg-card p-3.5 " + (ev.iso < today ? "opacity-50" : "")}>
                          <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">{ev.title}</div>
                            <div className="text-white/45 text-[11px] capitalize">{fmt(ev.iso)} · {ev.time}{ev.note ? " · " + ev.note : ""}</div>
                          </div>
                          <button onClick={() => edit(ev)} 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">{t("Edit", "Editar")}</button>
                          <button onClick={() => { if (confirm(t("Delete this event?", "¿Borrar este evento?"))) window.PPDB.events.remove(ev.id); }} className="text-white/35 hover:text-coral shrink-0"><Icon name="trash-2" className="w-4 h-4" /></button>
                        </div>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { EventsModule, useAdminEvents });
