/* ============================================================
   ADMIN · CUSTOMERS — loyalty CRM.
   Reads PPDB.customers (created when a guest opts in after a
   reservation). Tiers: New Guest → VIP Guest → Gold → Platinum.
   Adjust tier/points, contact, see each guest's reservations.
   ============================================================ */
const LOYALTY_TIERS = [
  ["New Guest", "#9aa0a6", 0],
  ["VIP Guest", "#FF6B5B", 100],
  ["Gold", "#CBA35C", 300],
  ["Platinum", "#E9E4DA", 700],
];
function tierMeta(name) { return LOYALTY_TIERS.find((x) => x[0] === name) || LOYALTY_TIERS[0]; }
function suggestedTier(points) {
  let t = LOYALTY_TIERS[0][0];
  for (const [name, , min] of LOYALTY_TIERS) if ((points || 0) >= min) t = name;
  return t;
}

function useCustomers() {
  const [list, setList] = useState(() => window.PPDB.customers.all());
  useEffect(() => {
    const f = () => setList(window.PPDB.customers.all());
    window.addEventListener("pp:customers", f);
    return () => window.removeEventListener("pp:customers", f);
  }, []);
  return list;
}

function CustomersModule() {
  const t = useT(); const { lang } = useLang();
  const list = useCustomers();
  const [q, setQ] = useState("");
  const [filter, setFilter] = useState("all");
  const [openId, setOpenId] = useState(null);

  // reservation count per phone (last 10 digits)
  const resByPhone = (() => {
    const m = {}; (window.PPDB.reservations.all() || []).forEach((r) => { const k = String(r.phone || "").replace(/\D/g, "").slice(-10); if (k) m[k] = (m[k] || 0) + 1; }); return m;
  })();
  const resCount = (c) => resByPhone[String(c.phone || "").replace(/\D/g, "").slice(-10)] || 0;

  const counts = {
    all: list.length,
    vip: list.filter((c) => c.loyaltyTier && c.loyaltyTier !== "New Guest").length,
    marketing: list.filter((c) => c.marketingConsent).length,
  };
  const FILTERS = [["all", t("All", "Todos")], ...LOYALTY_TIERS.map(([n]) => [n, n])];

  const filtered = list.filter((c) => {
    const okF = filter === "all" || (c.loyaltyTier || "New Guest") === filter;
    const okQ = !q || JSON.stringify(c).toLowerCase().includes(q.toLowerCase());
    return okF && okQ;
  });

  const update = (id, patch) => window.PPDB.customers.update(id, patch);
  const addPoints = (c, n) => { const pts = Math.max(0, (c.loyaltyPoints || 0) + n); update(c.id, { loyaltyPoints: pts }); };
  const phoneDigits = (p) => String(p || "").replace(/\D/g, "");
  const fmt = (iso) => { try { return new Date(iso).toLocaleDateString(lang === "es" ? "es" : "en", { month: "short", day: "numeric", year: "numeric" }); } catch (e) { return ""; } };
  const pushToToast = (c) => {
    if (!(window.PPToast && window.PPToast.configured())) return window.toast(t("Connect Toast to sync loyalty (Admin → Toast).", "Conecta Toast para sincronizar lealtad (Admin → Toast)."), "error");
    window.PPToast.loyalty.upsertGuest(c).then(() => window.toast(t("Synced to Toast loyalty.", "Sincronizado con lealtad de Toast."))).catch((e) => window.toast("Toast: " + e.message, "error"));
  };

  return (
    <div>
      {/* stats */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-5">
        {[["users", counts.all, t("Customers", "Clientes"), "#9333EA"], ["crown", counts.vip, t("VIP+", "VIP+"), "#FF6B5B"], ["mail", counts.marketing, t("Opted in", "Suscritos"), "#5FBFA8"], ["star", list.reduce((s, c) => s + (c.loyaltyPoints || 0), 0), t("Total points", "Puntos totales"), "#CBA35C"]].map(([ic, n, l, c], i) => (
          <div key={i} className="rounded-2xl border border-white/10 bg-card p-4"><Icon name={ic} className="w-5 h-5 mb-2" style={{ color: c }} /><div className="text-2xl font-black leading-none">{n}</div><div className="label text-white/45 text-[9px] mt-1">{l}</div></div>
        ))}
      </div>

      {/* filters */}
      <div className="flex flex-wrap items-center gap-2 mb-5">
        {FILTERS.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}</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…", "Buscar…")} 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-40 sm:w-52" />
        </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="users" className="w-8 h-8 mx-auto mb-3 text-white/25" />
          {list.length === 0
            ? t("No customers yet. Guests who create a loyalty account after reserving appear here.", "Aún no hay clientes. Los invitados que crean una cuenta de lealtad tras reservar aparecen aquí.")
            : t("No customers match your filter.", "Ningún cliente coincide con el filtro.")}
        </div>
      ) : (
        <div className="space-y-2.5">
          {filtered.map((c) => {
            const tm = tierMeta(c.loyaltyTier || "New Guest"); const ph = phoneDigits(c.phone);
            const open = openId === c.id; const sugg = suggestedTier(c.loyaltyPoints);
            return (
              <div key={c.id} className="rounded-2xl border border-white/10 bg-card p-4">
                <div className="flex items-start gap-3.5">
                  <div className="w-11 h-11 rounded-xl flex items-center justify-center shrink-0 font-extrabold text-sm" style={{ background: tm[1] + "1f", border: "1px solid " + tm[1] + "55", color: tm[1] }}>{(c.fullName || "?").slice(0, 1).toUpperCase()}</div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap">
                      <span className="font-bold text-sm truncate">{c.fullName}</span>
                      <span className="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider" style={{ background: tm[1] + "1f", color: tm[1] }}>{tm[0]}</span>
                      {c.marketingConsent && <Icon name="mail-check" className="w-3.5 h-3.5 text-[#5FBFA8]" />}
                    </div>
                    <div className="text-white/50 text-[12px] mt-0.5 flex items-center gap-x-3 gap-y-0.5 flex-wrap">
                      <span className="inline-flex items-center gap-1"><Icon name="star" className="w-3 h-3 text-gold" />{c.loyaltyPoints || 0} {t("pts", "pts")}</span>
                      <span className="inline-flex items-center gap-1"><Icon name="calendar-check" className="w-3 h-3" />{resCount(c)} {t("reservations", "reservas")}</span>
                      <span>{t("Joined", "Desde")} {fmt(c.at)}</span>
                    </div>
                    <div className="text-white/40 text-[11px] mt-0.5 truncate">{c.phone}{c.email ? " · " + c.email : ""}</div>
                  </div>
                  <button onClick={() => setOpenId(open ? null : c.id)} className="px-3 py-1.5 rounded-full border border-white/15 text-white/60 text-[10px] font-bold uppercase tracking-wider hover:text-white shrink-0">{open ? t("Close", "Cerrar") : t("Manage", "Gestionar")}</button>
                </div>

                <div className="flex flex-wrap items-center gap-1.5 mt-3 pt-3 border-t border-white/8">
                  {ph && <a href={"https://wa.me/" + ph.replace(/^1?/, "1")} 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>}
                  {ph && <a href={"tel:+" + ph.replace(/^1?/, "1")} 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 inline-flex items-center gap-1.5"><Icon name="phone" className="w-3 h-3" />{t("Call", "Llamar")}</a>}
                  {c.email && <a href={"mailto:" + c.email} 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 inline-flex items-center gap-1.5"><Icon name="mail" className="w-3 h-3" />Email</a>}
                  <button onClick={() => { if (confirm(t("Delete this customer?", "¿Borrar este cliente?"))) window.PPDB.customers.remove(c.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>

                {/* manage drawer */}
                {open && (
                  <div className="mt-3 pt-3 border-t border-white/8 fade-view space-y-3">
                    <div>
                      <div className="label text-white/45 text-[10px] mb-2">{t("Loyalty tier", "Nivel de lealtad")}{sugg !== (c.loyaltyTier || "New Guest") ? <span className="text-gold-soft normal-case"> · {t("suggested", "sugerido")}: {sugg}</span> : null}</div>
                      <div className="flex flex-wrap gap-1.5">
                        {LOYALTY_TIERS.map(([name, color]) => (
                          <button key={name} onClick={() => update(c.id, { loyaltyTier: name })} className={"px-3 py-1.5 rounded-full text-[10px] font-bold uppercase tracking-wider transition-all " + ((c.loyaltyTier || "New Guest") === name ? "text-black" : "border border-white/15 text-white/60 hover:text-white")} style={(c.loyaltyTier || "New Guest") === name ? { background: color } : {}}>{name}</button>
                        ))}
                      </div>
                    </div>
                    <div>
                      <div className="label text-white/45 text-[10px] mb-2">{t("Points", "Puntos")}</div>
                      <div className="flex items-center gap-2">
                        {[-50, -10, 10, 50, 100].map((n) => <button key={n} onClick={() => addPoints(c, n)} className="px-3 py-1.5 rounded-full border border-white/15 text-white/70 text-[11px] font-bold hover:bg-white/5">{n > 0 ? "+" + n : n}</button>)}
                        <span className="text-white/55 text-[12px] ml-1">= {c.loyaltyPoints || 0}</span>
                      </div>
                    </div>
                    <div className="flex flex-wrap items-center gap-2">
                      <button onClick={() => update(c.id, { marketingConsent: !c.marketingConsent })} 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 inline-flex items-center gap-1.5"><Icon name="mail" className="w-3 h-3" />{c.marketingConsent ? t("Opted in ✓", "Suscrito ✓") : t("Mark opted-in", "Marcar suscrito")}</button>
                      <button onClick={() => pushToToast(c)} 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 inline-flex items-center gap-1.5"><Icon name="credit-card" className="w-3 h-3" />{t("Sync to Toast", "Sincronizar a Toast")}</button>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { CustomersModule, useCustomers, LOYALTY_TIERS });
