/* ============================================================
   ADMIN · EMPLOYEES — roster, hiring pipeline, schedule, tips, payroll
   ============================================================ */
function StaffModule() {
  const t = useT(); const { lang } = useLang();
  const { STAFF, APPLICANTS, HIRING_STAGES, PAYROLL } = window.PP;
  const [tab, setTab] = useState("roster");
  const [staff, setStaff] = useState([...STAFF]);

  const toggleClock = (id) => setStaff((arr) => arr.map((s) => s.id === id ? { ...s, clocked: !s.clocked, in: s.clocked ? "—" : new Date().toLocaleTimeString(lang === "es" ? "es" : "en", { hour: "numeric", minute: "2-digit" }) } : s));
  const clockedIn = staff.filter((s) => s.clocked).length;
  const tipPool = staff.reduce((s, x) => s + x.tips, 0);
  const deptColor = { Bar: "#FF6B5B", Floor: "#CBA35C", Security: "#9333EA", Kitchen: "#5FBFA8" };

  return (
    <div>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-5">
        {[["user-check", clockedIn + "/" + staff.length, t("Clocked in", "Fichados")], ["coins", "$" + tipPool, t("Tip pool tonight", "Pool de propinas")], ["briefcase", APPLICANTS.length, t("Open applicants", "Aplicantes")], ["wallet", "$" + (PAYROLL.net / 1000).toFixed(1) + "K", t("Payroll due", "Nómina a pagar")]].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>

      <div className="flex gap-2 border-b border-white/10 mb-6 overflow-x-auto">
        {[["roster", t("Roster & Clock", "Roster y Reloj"), "users"], ["hiring", t("Hiring", "Contratación"), "user-plus"], ["schedule", t("Schedule", "Horario"), "calendar"], ["payroll", t("Payroll & Tips", "Nómina y Propinas"), "wallet"]].map(([id, lbl, ic]) => (
          <button key={id} onClick={() => setTab(id)} className={"shrink-0 inline-flex items-center gap-2 px-4 py-3 text-[12px] font-bold uppercase tracking-[0.1em] border-b-2 -mb-px transition-all " + (tab === id ? "border-coral text-white" : "border-transparent text-white/50 hover:text-white")}><Icon name={ic} className="w-4 h-4" />{lbl}</button>
        ))}
      </div>

      {tab === "roster" && (
        <div className="space-y-2">
          {staff.map((s) => (
            <div key={s.id} className="flex items-center gap-4 p-4 rounded-2xl border border-white/10 bg-card">
              <div className="w-2.5 h-2.5 rounded-full shrink-0" style={{ background: s.clocked ? "#5FBFA8" : "#6b6b72" }}></div>
              <div className="flex-1 min-w-0"><div className="font-bold text-sm truncate">{s.name}</div><div className="text-white/45 text-xs">{L(s.role, lang)}</div></div>
              <Chip color={deptColor[s.dept]}>{s.dept}</Chip>
              <div className="hidden sm:block text-right w-20"><div className="text-sm font-bold text-white/80">${s.hourly}/hr</div><div className="text-white/35 text-[10px]">{s.week}h {t("this wk", "esta sem")}</div></div>
              <button onClick={() => toggleClock(s.id)} className={"px-4 py-2 rounded-full text-[11px] font-bold uppercase tracking-wider transition-all w-28 " + (s.clocked ? "bg-green-500/15 border border-green-500/40 text-green-400 hover:bg-green-500/25" : "bg-coral/15 border border-coral/40 text-coral hover:bg-coral hover:text-white")}>{s.clocked ? <>{t("In", "Dentro")} · {s.in}</> : t("Clock in", "Fichar")}</button>
            </div>
          ))}
        </div>
      )}

      {tab === "hiring" && (
        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-3">
          {HIRING_STAGES.map((st) => {
            const apps = APPLICANTS.filter((a) => a.stage === st.id);
            return (
              <div key={st.id} className="rounded-2xl border border-white/10 bg-card p-4">
                <div className="flex items-center justify-between mb-3"><span className="label text-white/55 text-[10px]">{L(st.label, lang)}</span><span className="w-6 h-6 rounded-full bg-white/8 text-white/70 text-[11px] font-bold flex items-center justify-center">{apps.length}</span></div>
                <div className="space-y-2">
                  {apps.map((a) => (
                    <div key={a.id} className="rounded-xl border border-white/10 bg-ink p-3">
                      <div className="font-bold text-sm">{a.name}</div>
                      <div className="text-white/45 text-xs mb-2">{L(a.role, lang)}</div>
                      <div className="flex items-center justify-between"><div className="flex gap-0.5">{[1, 2, 3, 4, 5].map((n) => <Icon key={n} name="star" className="w-3 h-3" style={{ color: n <= a.rating ? "#CBA35C" : "rgba(255,255,255,.18)", fill: n <= a.rating ? "#CBA35C" : "none" }} />)}</div><span className="text-white/35 text-[10px]">{L(a.applied, lang)}</span></div>
                    </div>
                  ))}
                  {apps.length === 0 && <div className="text-white/30 text-xs text-center py-3">—</div>}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {tab === "schedule" && <StaffSchedule staff={staff} />}

      {tab === "payroll" && (
        <div>
          <div className="rounded-2xl border border-coral/30 bg-coral/5 p-6 mb-5 flex flex-col sm:flex-row items-center justify-between gap-4">
            <div><div className="label text-coral text-[10px] mb-1">{t("Pay period", "Periodo de pago")}</div><div className="text-xl font-black uppercase">{L(PAYROLL.period, lang)}</div></div>
            <div className="grid grid-cols-2 sm:flex gap-5 text-center">
              {[[t("Gross wages", "Salarios"), PAYROLL.gross], [t("Tips", "Propinas"), PAYROLL.tips], [t("Taxes", "Impuestos"), PAYROLL.taxes], [t("Net payout", "Pago neto"), PAYROLL.net]].map(([l, v], i) => (
                <div key={i}><div className={"serif text-2xl " + (i === 3 ? "text-green-400" : "text-gold-soft")}>${(v / 1000).toFixed(1)}K</div><div className="label text-white/45 text-[9px] mt-1">{l}</div></div>
              ))}
            </div>
          </div>
          <div className="rounded-2xl border border-white/10 bg-card overflow-hidden mb-5">
            <div className="grid grid-cols-5 gap-2 px-5 py-3 border-b border-white/10 label text-white/40 text-[9px]"><span>{t("Department", "Departamento")}</span><span className="text-center">{t("Staff", "Staff")}</span><span className="text-center">{t("Hours", "Horas")}</span><span className="text-right">{t("Wages", "Salarios")}</span><span className="text-right">{t("Tips", "Propinas")}</span></div>
            {PAYROLL.runs.map((r) => (
              <div key={r.dept} className="grid grid-cols-5 gap-2 px-5 py-3.5 border-b border-white/5 text-sm items-center"><span className="font-bold">{r.dept}</span><span className="text-center text-white/60">{r.staff}</span><span className="text-center text-white/60">{r.hours}</span><span className="text-right text-gold-soft serif text-base">${r.wages.toLocaleString()}</span><span className="text-right text-gold-soft serif text-base">${r.tips.toLocaleString()}</span></div>
            ))}
          </div>
          <ChargeButton amount={(PAYROLL.net / 1000).toFixed(1) + "K"} label={t("Run payroll", "Procesar nómina")} className="max-w-sm mx-auto" />
        </div>
      )}
    </div>
  );
}

function StaffSchedule({ staff }) {
  const t = useT();
  const days = [t("Mon", "Lun"), t("Tue", "Mar"), t("Wed", "Mié"), t("Thu", "Jue"), t("Fri", "Vie"), t("Sat", "Sáb"), t("Sun", "Dom")];
  // deterministic shift pattern per staff
  const shift = (i, d) => {
    const seed = (i * 7 + d * 3) % 10;
    if (seed < 4) return null;
    return seed < 7 ? "8P–3A" : "9P–5A";
  };
  return (
    <div className="rounded-2xl border border-white/10 bg-card overflow-x-auto">
      <table className="w-full text-sm" style={{ minWidth: 640 }}>
        <thead><tr className="border-b border-white/10"><th className="text-left label text-white/40 text-[9px] px-5 py-3 sticky left-0 bg-card">{t("Employee", "Empleado")}</th>{days.map((d) => <th key={d} className="label text-white/40 text-[9px] py-3 px-2">{d}</th>)}</tr></thead>
        <tbody>
          {staff.map((s, i) => (
            <tr key={s.id} className="border-b border-white/5">
              <td className="px-5 py-3 sticky left-0 bg-card"><div className="font-bold text-sm whitespace-nowrap">{s.name}</div><div className="text-white/40 text-[11px]">{s.dept}</div></td>
              {days.map((d, di) => { const sh = shift(i, di); return (
                <td key={di} className="py-3 px-2 text-center">{sh ? <span className="inline-block px-2 py-1 rounded-md bg-coral/15 border border-coral/30 text-coral text-[10px] font-bold whitespace-nowrap">{sh}</span> : <span className="text-white/15">—</span>}</td>
              ); })}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

Object.assign(window, { StaffModule, StaffSchedule });
