/* ============================================================
   ADMIN · CAREERS — job applications from the Careers page.
   Reads PPDB.careers. Filter by position + status, contact by
   WhatsApp/Call, advance the hiring lifecycle.
   Statuses: new → reviewed → contacted → interview → accepted /
   rejected / archived.
   ============================================================ */
function useCareers() {
  const [list, setList] = useState(() => window.PPDB.careers.all());
  useEffect(() => {
    const f = () => setList(window.PPDB.careers.all());
    window.addEventListener("pp:careers", f);
    return () => window.removeEventListener("pp:careers", f);
  }, []);
  return list;
}

function CareersModule() {
  const t = useT(); const { lang } = useLang();
  const list = useCareers();
  const [q, setQ] = useState("");
  const [filter, setFilter] = useState("open");
  const [posFilter, setPosFilter] = useState("all");

  const ST = {
    new:       { l: t("New", "Nuevo"), c: "#FF6B5B" },
    reviewed:  { l: t("Reviewed", "Revisado"), c: "#CBA35C" },
    contacted: { l: t("Contacted", "Contactado"), c: "#9333EA" },
    interview: { l: t("Interview", "Entrevista"), c: "#5FBFA8" },
    accepted:  { l: t("Accepted", "Aceptado"), c: "#22c55e" },
    rejected:  { l: t("Rejected", "Rechazado"), c: "#ef4444" },
    archived:  { l: t("Archived", "Archivado"), c: "#6b6b72" },
  };
  const stOf = (c) => ST[c.status || "new"] || ST.new;
  const isOpen = (c) => !["rejected", "archived", "accepted"].includes(c.status);
  // ordered next-step buttons
  const FLOW = ["new", "reviewed", "contacted", "interview", "accepted"];

  const counts = {
    open: list.filter(isOpen).length,
    new: list.filter((c) => (c.status || "new") === "new").length,
    interview: list.filter((c) => c.status === "interview").length,
    all: list.length,
  };
  const FILTERS = [["open", t("Open", "Abiertas")], ["new", t("New", "Nuevas")], ["interview", t("Interview", "Entrevista")], ["all", t("All", "Todas")]];

  // position chips present in the data
  const positionsInData = [...new Set(list.map((c) => c.position).filter(Boolean))];
  const labelFor = (id) => (typeof window.positionLabel === "function" ? window.positionLabel(id, lang) : id);

  const filtered = list.filter((c) => {
    const okF = filter === "all" ? true : filter === "open" ? isOpen(c) : (c.status || "new") === filter;
    const okP = posFilter === "all" || c.position === posFilter;
    const okQ = !q || JSON.stringify(c).toLowerCase().includes(q.toLowerCase());
    return okF && okP && okQ;
  });

  const update = (id, patch) => window.PPDB.careers.update(id, patch);
  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", hour: "numeric", minute: "2-digit" }); } catch (e) { return ""; } };
  const empLabel = (e) => e === "part" ? t("Part-time", "Medio tiempo") : t("Full-time", "Tiempo completo");

  return (
    <div>
      {/* stats */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-5">
        {[["briefcase", counts.all, t("Total", "Total"), "#9333EA"], ["sparkle", counts.new, t("New", "Nuevas"), "#FF6B5B"], ["calendar-check", counts.interview, t("Interviews", "Entrevistas"), "#5FBFA8"], ["folder-open", counts.open, t("Open", "Abiertas"), "#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-3">
        {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}{counts[id] != null ? <span className="opacity-60"> · {counts[id]}</span> : null}</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>

      {/* position filter */}
      {positionsInData.length > 0 && (
        <div className="flex flex-wrap items-center gap-1.5 mb-5">
          <button onClick={() => setPosFilter("all")} className={"px-3 py-1.5 rounded-full text-[10px] font-bold uppercase tracking-wider transition-all " + (posFilter === "all" ? "bg-white/15 text-white" : "bg-card border border-white/10 text-white/50 hover:text-white")}>{t("All roles", "Todos")}</button>
          {positionsInData.map((p) => (
            <button key={p} onClick={() => setPosFilter(p)} className={"px-3 py-1.5 rounded-full text-[10px] font-bold uppercase tracking-wider transition-all " + (posFilter === p ? "bg-white/15 text-white" : "bg-card border border-white/10 text-white/50 hover:text-white")}>{labelFor(p)}</button>
          ))}
        </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="briefcase" className="w-8 h-8 mx-auto mb-3 text-white/25" />
          {list.length === 0
            ? t("No applications yet. Submissions from the Careers page appear here automatically.", "Aún no hay aplicaciones. Los envíos de la página de Empleos aparecen aquí automáticamente.")
            : t("No applications match your filter.", "Ninguna aplicación coincide con el filtro.")}
        </div>
      ) : (
        <div className="space-y-2.5">
          {filtered.map((c) => {
            const st = stOf(c); const ph = phoneDigits(c.phone); const status = c.status || "new";
            const idx = FLOW.indexOf(status); const nextStep = idx >= 0 && idx < FLOW.length - 1 ? FLOW[idx + 1] : null;
            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 bg-coral/12 border border-coral/30 flex items-center justify-center shrink-0 text-coral"><Icon name="user" className="w-5 h-5" /></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 bg-coral/12 text-coral text-[10px] font-bold uppercase tracking-wider">{labelFor(c.position)}</span>
                    </div>
                    <div className="text-white/50 text-[12px] mt-0.5 flex items-center gap-x-3 gap-y-0.5 flex-wrap">
                      <span>{fmt(c.at)}</span>
                      <span>{empLabel(c.employment)}</span>
                      {c.experience && <span>{c.experience === "entry" ? t("No experience", "Sin experiencia") : c.experience + " " + t("yrs", "años")}</span>}
                      {c.days && c.days.length ? <span className="uppercase">{c.days.join(" ")}</span> : null}
                    </div>
                    <div className="text-white/45 text-[11px] mt-0.5 truncate">{c.email}</div>
                    {c.message ? <div className="text-white/40 text-[11px] mt-1 italic line-clamp-2">"{c.message}"</div> : null}
                  </div>
                  <Chip color={st.c}>{st.l}</Chip>
                </div>

                {/* actions */}
                <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>}
                  {nextStep && <button onClick={() => update(c.id, { status: nextStep })} className="px-3 py-1.5 rounded-full bg-coral/15 border border-coral/40 text-coral text-[10px] font-bold uppercase tracking-wider hover:bg-coral hover:text-white transition-all">→ {ST[nextStep].l}</button>}
                  {status !== "rejected" && status !== "accepted" && <button onClick={() => update(c.id, { status: "rejected" })} 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">{t("Reject", "Rechazar")}</button>}
                  {status !== "archived" && <button onClick={() => update(c.id, { status: "archived" })} className="px-3 py-1.5 rounded-full border border-white/15 text-white/45 text-[10px] font-bold uppercase tracking-wider hover:text-white">{t("Archive", "Archivar")}</button>}
                  <button onClick={() => { if (confirm(t("Delete this application permanently?", "¿Borrar esta aplicación permanentemente?"))) window.PPDB.careers.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>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { CareersModule, useCareers });
