/* ============================================================
   ADMIN · CRM — contacts, accounts, loyalty, memberships
   ============================================================ */
function loyaltyOf(points, tiers) {
  let cur = tiers[0];
  for (const tr of tiers) if (points >= tr.min) cur = tr;
  return cur;
}

function CRMModule() {
  const t = useT(); const { lang } = useLang();
  const { CRM_CONTACTS, LOYALTY_TIERS, TIERS } = window.PP;
  const [q, setQ] = useState("");
  const [filter, setFilter] = useState("all");
  const [sel, setSel] = useState(null);

  const filters = [["all", t("All", "Todos")], ["vip", t("VIP", "VIP")], ["active", t("Active", "Activos")], ["lead", t("Leads", "Leads")], ["lapsed", t("Lapsed", "Inactivos")]];
  const list = CRM_CONTACTS.filter((c) =>
    (filter === "all" || c.status === filter) &&
    (q === "" || c.name.toLowerCase().includes(q.toLowerCase()) || c.handle.toLowerCase().includes(q.toLowerCase()))
  );
  const statusColor = { vip: "#FF6B5B", active: "#5FBFA8", lead: "#CBA35C", lapsed: "#6b6b72" };
  const tierName = (id) => ({ free: "Guest", member: "Member", vip: "VIP", black: "Black" }[id] || id);

  const totals = {
    contacts: CRM_CONTACTS.length,
    vip: CRM_CONTACTS.filter((c) => c.tier === "vip" || c.tier === "black").length,
    spend: CRM_CONTACTS.reduce((s, c) => s + c.spend, 0),
    points: CRM_CONTACTS.reduce((s, c) => s + c.points, 0),
  };

  return (
    <div>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-5">
        {[["users", totals.contacts, t("Contacts", "Contactos")], ["crown", totals.vip, t("VIP / Black", "VIP / Black")], ["dollar-sign", "$" + (totals.spend / 1000).toFixed(0) + "K", t("Lifetime spend", "Gasto histórico")], ["star", (totals.points / 1000).toFixed(1) + "K", t("Loyalty points", "Puntos lealtad")]].map(([ic, n, l], i) => (
          <div key={i} className="rounded-2xl border border-white/10 bg-card p-4"><Icon name={ic} className="w-5 h-5 text-coral mb-2" /><div className="text-2xl font-black leading-none">{n}</div><div className="label text-white/45 text-[9px] mt-1">{l}</div></div>
        ))}
      </div>

      {/* loyalty program ladder */}
      <div className="rounded-2xl border border-white/10 bg-card p-5 mb-5">
        <div className="flex items-center justify-between mb-4"><h3 className="text-sm font-black uppercase tracking-wide flex items-center gap-2"><Icon name="award" className="w-4 h-4 text-gold" />{t("Loyalty Program", "Programa de Lealtad")}</h3><span className="text-white/40 text-xs">{t("Points = $1 spent", "Puntos = $1 gastado")}</span></div>
        <div className="grid sm:grid-cols-4 gap-3">
          {LOYALTY_TIERS.map((tr) => (
            <div key={tr.name} className="rounded-xl border border-white/10 bg-ink p-4">
              <div className="flex items-center gap-2 mb-1"><span className="w-2.5 h-2.5 rounded-full" style={{ background: tr.color }}></span><span className="font-bold text-sm">{tr.name}</span></div>
              <div className="text-white/40 text-[11px] mb-2">{tr.min.toLocaleString()}+ {t("pts", "pts")}</div>
              <div className="text-white/65 text-xs leading-snug">{L(tr.perk, lang)}</div>
            </div>
          ))}
        </div>
      </div>

      {/* search + filters */}
      <div className="flex flex-col sm:flex-row gap-3 mb-4">
        <div className="relative flex-1"><Icon name="search" className="w-4 h-4 text-white/40 absolute left-3.5 top-1/2 -translate-y-1/2" /><input value={q} onChange={(e) => setQ(e.target.value)} placeholder={t("Search name or @handle…", "Buscar nombre o @handle…")} className="w-full bg-card border border-white/12 rounded-xl pl-10 pr-3 py-3 text-sm text-white focus:outline-none focus:border-coral placeholder:text-white/35" /></div>
        <div className="flex gap-2 overflow-x-auto">{filters.map(([id, lbl]) => <button key={id} onClick={() => setFilter(id)} className={"shrink-0 px-4 py-2 rounded-xl 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>
      </div>

      {/* contact list */}
      <div className="space-y-2">
        {list.map((c) => {
          const lt = loyaltyOf(c.points, LOYALTY_TIERS);
          return (
            <button key={c.id} onClick={() => setSel(c)} className="w-full flex items-center gap-4 p-4 rounded-2xl border border-white/10 bg-card text-left hover:border-coral/40 transition-all">
              <div className="w-11 h-11 rounded-full flex items-center justify-center font-black text-sm shrink-0" style={{ background: statusColor[c.status] + "22", color: statusColor[c.status], border: "1px solid " + statusColor[c.status] + "55" }}>{c.name.split(" ").map((x) => x[0]).slice(0, 2).join("")}</div>
              <div className="flex-1 min-w-0"><div className="font-bold text-sm truncate">{c.name}</div><div className="text-white/45 text-xs truncate">{c.handle} · {c.visits} {t("visits", "visitas")}</div></div>
              <div className="hidden sm:flex items-center gap-2"><span className="w-2 h-2 rounded-full" style={{ background: lt.color }}></span><span className="text-xs text-white/60 w-12">{lt.name}</span></div>
              <Chip color={c.tier === "free" ? "#6b6b72" : c.tier === "black" ? "#E9E4DA" : c.tier === "vip" ? "#FF6B5B" : "#CBA35C"}>{tierName(c.tier)}</Chip>
              <div className="text-right shrink-0 w-20 hidden md:block"><div className="serif text-lg text-gold-soft">${(c.spend / 1000).toFixed(1)}K</div><div className="text-white/35 text-[10px]">{L(c.last, lang)}</div></div>
              <Icon name="chevron-right" className="w-5 h-5 text-white/30 shrink-0" />
            </button>
          );
        })}
        {list.length === 0 && <div className="text-center text-white/40 py-10 text-sm">{t("No contacts match.", "Ningún contacto coincide.")}</div>}
      </div>

      {/* detail drawer */}
      {sel && <CRMDetail c={sel} onClose={() => setSel(null)} />}
    </div>
  );
}

function CRMDetail({ c, onClose }) {
  const t = useT(); const { lang } = useLang();
  const { LOYALTY_TIERS } = window.PP;
  const lt = loyaltyOf(c.points, LOYALTY_TIERS);
  const next = LOYALTY_TIERS.find((x) => x.min > c.points);
  const pct = next ? Math.round(((c.points - lt.min) / (next.min - lt.min)) * 100) : 100;
  const tierName = (id) => ({ free: "Guest", member: "Member", vip: "VIP", black: "Black" }[id] || id);

  return (
    <div className="fixed inset-0 z-50 flex justify-end fade-view" onClick={onClose}>
      <div className="absolute inset-0 bg-black/70 backdrop-blur-sm"></div>
      <div className="relative w-full max-w-md bg-ink border-l border-white/12 h-full overflow-y-auto" onClick={(e) => e.stopPropagation()}>
        <div className="p-6">
          <div className="flex items-center justify-between mb-6"><div className="label text-coral text-[10px]">{t("Contact profile", "Perfil de contacto")}</div><button onClick={onClose}><Icon name="x" className="w-6 h-6 text-white/55" /></button></div>
          <div className="flex items-center gap-4 mb-6">
            <div className="w-16 h-16 rounded-full bg-gradient-to-br from-coral to-grape flex items-center justify-center font-black text-xl shrink-0">{c.name.split(" ").map((x) => x[0]).slice(0, 2).join("")}</div>
            <div><h2 className="text-2xl font-black uppercase leading-none">{c.name}</h2><div className="text-white/45 text-sm mt-1">{c.handle}</div></div>
          </div>
          <div className="flex flex-wrap gap-2 mb-6">
            <Chip color={c.tier === "free" ? "#6b6b72" : c.tier === "black" ? "#E9E4DA" : c.tier === "vip" ? "#FF6B5B" : "#CBA35C"}>{tierName(c.tier)} {t("Member", "Miembro")}</Chip>
            <Chip color={lt.color}>{lt.name} {t("loyalty", "lealtad")}</Chip>
          </div>

          {/* loyalty progress */}
          <div className="rounded-2xl border border-white/10 bg-card p-5 mb-4">
            <div className="flex items-center justify-between mb-2"><span className="label text-white/45 text-[10px]">{t("Loyalty points", "Puntos de lealtad")}</span><span className="serif text-2xl text-gold-soft">{c.points.toLocaleString()}</span></div>
            <div className="h-2 rounded-full bg-white/10 overflow-hidden mb-2"><div className="h-full rounded-full" style={{ width: pct + "%", background: lt.color }}></div></div>
            <div className="text-white/45 text-[11px]">{next ? <>{(next.min - c.points).toLocaleString()} {t("pts to", "pts para")} {next.name}</> : t("Top tier reached", "Nivel máximo alcanzado")}</div>
          </div>

          <div className="grid grid-cols-2 gap-3 mb-4">
            <div className="rounded-xl border border-white/10 bg-card p-4"><div className="serif text-2xl text-white">{c.visits}</div><div className="label text-white/45 text-[9px] mt-1">{t("Visits", "Visitas")}</div></div>
            <div className="rounded-xl border border-white/10 bg-card p-4"><div className="serif text-2xl text-gold-soft">${c.spend.toLocaleString()}</div><div className="label text-white/45 text-[9px] mt-1">{t("Lifetime spend", "Gasto total")}</div></div>
          </div>

          <div className="rounded-2xl border border-white/10 bg-card p-5 mb-4 space-y-3">
            {[["phone", c.phone], ["mail", c.email], ["gift", t("Birthday", "Cumpleaños") + " · " + c.bday], ["calendar", t("Last visit", "Última visita") + " · " + L(c.last, lang)]].map(([ic, v], i) => (
              <div key={i} className="flex items-center gap-3 text-sm"><Icon name={ic} className="w-4 h-4 text-gold shrink-0" /><span className="text-white/75">{v}</span></div>
            ))}
            <div className="flex items-center gap-3 text-sm"><Icon name="credit-card" className="w-4 h-4 text-gold shrink-0" />{c.card ? <span className="text-white/75 flex items-center gap-2">•••• {c.card} <Icon name="shield-check" className="w-4 h-4 text-green-400" /></span> : <span className="text-white/45">{t("No card on file", "Sin tarjeta en archivo")}</span>}</div>
          </div>

          <div className="rounded-2xl border border-white/10 bg-card p-5 mb-5">
            <div className="label text-white/45 text-[10px] mb-2">{t("Host notes", "Notas del host")}</div>
            <p className="text-white/75 text-sm leading-relaxed">{L(c.note, lang)}</p>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <button className="gbtn py-3 rounded-full bg-coral hover:bg-coral-deep text-white text-[11px] font-bold uppercase tracking-wider flex items-center justify-center gap-2"><Icon name="calendar-plus" className="w-4 h-4" />{t("New reservation", "Nueva reserva")}</button>
            <button className="py-3 rounded-full border border-white/15 text-white/80 text-[11px] font-bold uppercase tracking-wider hover:bg-white/5 flex items-center justify-center gap-2"><Icon name="message-circle" className="w-4 h-4" />{t("Message", "Mensaje")}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CRMModule, CRMDetail, loyaltyOf });
