/* ============================================================
   ADMIN · LEADS — every captured form/CTA (reservations, casting,
   newsletter, venue, experiences, store) lands here, even if the
   guest never hit send in WhatsApp. Synced via PPDB.leads.
   ============================================================ */
function useLeads() {
  const [list, setList] = useState(() => window.PPDB.leads.all());
  useEffect(() => {
    const f = () => setList(window.PPDB.leads.all());
    window.addEventListener("pp:leads", f);
    return () => window.removeEventListener("pp:leads", f);
  }, []);
  return list;
}
function leadField(lead, keys) {
  const f = (lead.fields || []).find(([k]) => keys.some((kw) => String(k).toLowerCase().includes(kw)));
  return f ? String(f[1]) : "";
}
function leadKind(title) {
  const s = String(title || "").toLowerCase();
  if (s.includes("casting")) return { l: { en: "Casting", es: "Casting" }, c: "#FF2E88", ic: "sparkles" };
  if (s.includes("reserv")) return { l: { en: "Reservation", es: "Reserva" }, c: "#FF6B5B", ic: "calendar-check" };
  if (s.includes("newsletter") || s.includes("boletín")) return { l: { en: "Newsletter", es: "Boletín" }, c: "#5FBFA8", ic: "mail" };
  if (s.includes("event") || s.includes("venue") || s.includes("private")) return { l: { en: "Private event", es: "Evento privado" }, c: "#CBA35C", ic: "building" };
  if (s.includes("bottle") || s.includes("store") || s.includes("order") || s.includes("merch")) return { l: { en: "Order", es: "Pedido" }, c: "#9333EA", ic: "shopping-bag" };
  return { l: { en: "Inquiry", es: "Consulta" }, c: "#888", ic: "message-circle" };
}

function LeadsModule() {
  const t = useT(); const { lang } = useLang();
  const list = useLeads();
  const [q, setQ] = useState("");
  const [filter, setFilter] = useState("all");
  const [open, setOpen] = useState(null);

  const ST = {
    new: { l: t("New", "Nuevo"), c: "#FF6B5B" },
    contacted: { l: t("Contacted", "Contactado"), c: "#CBA35C" },
    closed: { l: t("Closed", "Cerrado"), c: "#5FBFA8" },
  };
  const filtered = list.filter((l) =>
    (filter === "all" || (l.status || "new") === filter) &&
    (!q || JSON.stringify(l).toLowerCase().includes(q.toLowerCase()))
  );
  const counts = { all: list.length, new: list.filter((l) => (l.status || "new") === "new").length, contacted: list.filter((l) => l.status === "contacted").length, closed: list.filter((l) => l.status === "closed").length };
  const fmt = (iso) => { try { return new Date(iso).toLocaleString(lang === "es" ? "es" : "en", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }); } catch (e) { return ""; } };
  const phoneOf = (l) => leadField(l, ["phone", "teléfono", "telefono", "móvil", "movil", "mobile", "whatsapp"]).replace(/[^\d+]/g, "");
  const nameOf = (l) => leadField(l, ["name", "nombre", "legal"]) || "—";

  return (
    <div>
      {/* stats / filters */}
      <div className="flex flex-wrap items-center gap-2 mb-5">
        {[["all", t("All", "Todos")], ["new", ST.new.l], ["contacted", ST.contacted.l], ["closed", ST.closed.l]].map(([id, lbl]) => (
          <button key={id} onClick={() => setFilter(id)} className={"px-4 py-2 rounded-full text-[11px] font-bold uppercase tracking-wider transition-all " + (filter === id ? "bg-coral text-white" : "bg-card border border-white/12 text-white/60 hover:text-white")}>{lbl} <span className="opacity-60">· {counts[id]}</span></button>
        ))}
        <div className="relative ml-auto">
          <Icon name="search" className="w-4 h-4 text-white/35 absolute left-3 top-1/2 -translate-y-1/2" />
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder={t("Search leads…", "Buscar leads…")} className="bg-ink border border-white/12 rounded-full pl-9 pr-4 py-2 text-sm text-white focus:outline-none focus:border-coral placeholder:text-white/35 w-44 sm:w-56" />
        </div>
      </div>

      {filtered.length === 0 ? (
        <div className="rounded-2xl border border-dashed border-white/15 p-10 text-center text-white/45 text-sm">
          <Icon name="inbox" className="w-8 h-8 mx-auto mb-3 text-white/25" />
          {list.length === 0
            ? t("No leads yet. Every reservation, casting application, newsletter signup and inquiry from the website will appear here automatically.", "Aún no hay leads. Cada reserva, aplicación de casting, registro al boletín y consulta del sitio aparecerá aquí automáticamente.")
            : t("No leads match your filter.", "Ningún lead coincide con el filtro.")}
        </div>
      ) : (
        <div className="space-y-2">
          {filtered.map((l) => {
            const k = leadKind(l.title); const st = ST[l.status || "new"]; const phone = phoneOf(l); const isOpen = open === l.id;
            return (
              <div key={l.id} className="rounded-xl border border-white/10 bg-card overflow-hidden">
                <button onClick={() => setOpen(isOpen ? null : l.id)} className="w-full flex items-center gap-3 p-3.5 text-left">
                  <div className="w-9 h-9 rounded-lg flex items-center justify-center shrink-0" style={{ background: k.c + "1f", border: "1px solid " + k.c + "55" }}><Icon name={k.ic} className="w-4 h-4" style={{ color: k.c }} /></div>
                  <div className="flex-1 min-w-0">
                    <div className="font-bold text-sm truncate">{nameOf(l)} <span className="text-white/40 font-normal">· {L(k.l, lang)}</span></div>
                    <div className="text-white/45 text-[11px]">{fmt(l.at)}{phone ? " · " + phone : ""}</div>
                  </div>
                  <Chip color={st.c}>{st.l}</Chip>
                  <Icon name={isOpen ? "chevron-up" : "chevron-down"} className="w-4 h-4 text-white/30 shrink-0" />
                </button>
                {isOpen && (
                  <div className="px-3.5 pb-3.5 border-t border-white/8 pt-3 fade-view">
                    <div className="grid sm:grid-cols-2 gap-x-5 gap-y-1.5 mb-3">
                      {(l.fields || []).map(([key, val], i) => (
                        <div key={i} className="text-[13px] flex gap-2"><span className="text-white/40 shrink-0">{key}:</span><span className="text-white/85 break-words">{val}</span></div>
                      ))}
                    </div>
                    <div className="flex flex-wrap gap-1.5">
                      {phone && <a href={"https://wa.me/" + phone.replace(/^\+/, "")} target="_blank" rel="noopener" className="px-3 py-1.5 rounded-full bg-[#25D366] text-black text-[10px] font-bold uppercase tracking-wider inline-flex items-center gap-1.5"><Icon name="message-circle" className="w-3 h-3" />WhatsApp</a>}
                      {phone && <a href={"tel:" + phone} className="px-3 py-1.5 rounded-full border border-white/15 text-white/70 text-[10px] font-bold uppercase tracking-wider inline-flex items-center gap-1.5 hover:bg-white/5"><Icon name="phone" className="w-3 h-3" />{t("Call", "Llamar")}</a>}
                      {(l.status || "new") !== "contacted" && <button onClick={() => window.PPDB.leads.update(l.id, { status: "contacted" })} className="px-3 py-1.5 rounded-full border border-white/15 text-white/70 text-[10px] font-bold uppercase tracking-wider hover:bg-white/5">{t("Mark contacted", "Marcar contactado")}</button>}
                      {(l.status || "new") !== "closed" && <button onClick={() => window.PPDB.leads.update(l.id, { status: "closed" })} className="px-3 py-1.5 rounded-full border border-white/15 text-white/70 text-[10px] font-bold uppercase tracking-wider hover:bg-white/5">{t("Close", "Cerrar")}</button>}
                      <button onClick={() => { if (confirm(t("Delete this lead?", "¿Borrar este lead?"))) window.PPDB.leads.remove(l.id); }} className="px-3 py-1.5 rounded-full border border-white/15 text-white/45 text-[10px] font-bold uppercase tracking-wider hover:text-coral hover:border-coral/40 ml-auto"><Icon name="trash-2" className="w-3 h-3" /></button>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { LeadsModule, useLeads });
