/* ============================================================
   ADMIN · CASH CONTROL — drawer reconciliation, tip pool, deposit
   ============================================================ */
function CashControlModule() {
  const t = useT(); const { lang } = useLang();
  const { CASH_DRAWERS, TIP_POOL } = window.PP;
  const [drawers, setDrawers] = useState(() => CASH_DRAWERS.map((d) => ({ ...d })));
  const [countFor, setCountFor] = useState(null);
  const [countVal, setCountVal] = useState("");

  const expected = (d) => d.start + d.cashSales - d.paidOut;
  const variance = (d) => d.status === "counted" ? d.counted - expected(d) : null;

  const totalCash = drawers.reduce((s, d) => s + d.cashSales, 0);
  const totalCard = drawers.reduce((s, d) => s + d.cardSales, 0);
  const depositExpected = drawers.reduce((s, d) => s + expected(d), 0);
  const tipTotal = TIP_POOL.cardTips + TIP_POOL.cashTips;

  const doCount = () => {
    const v = parseFloat(countVal); if (isNaN(v)) return;
    setDrawers((ds) => ds.map((d) => d.id === countFor ? { ...d, status: "counted", counted: v } : d));
    setCountFor(null); setCountVal("");
  };
  const countedCount = drawers.filter((d) => d.status === "counted").length;

  return (
    <div>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-5">
        {[["banknote", "$" + (totalCash / 1000).toFixed(1) + "K", t("Cash sales", "Ventas efectivo"), "#5FBFA8"], ["credit-card", "$" + (totalCard / 1000).toFixed(1) + "K", t("Card sales", "Ventas tarjeta"), "#9333EA"], ["coins", "$" + (tipTotal / 1000).toFixed(1) + "K", t("Tip pool", "Pool propinas"), "#CBA35C"], ["vault", "$" + (depositExpected / 1000).toFixed(1) + "K", t("Deposit expected", "Depósito esperado"), "#FF6B5B"]].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>

      <div className="grid lg:grid-cols-2 gap-5">
        {/* DRAWERS */}
        <div>
          <div className="flex items-center justify-between mb-3"><h3 className="text-sm font-black uppercase tracking-wide flex items-center gap-2"><Icon name="calculator" className="w-4 h-4 text-coral" />{t("Drawer reconciliation", "Cuadre de cajas")}</h3><span className="text-white/40 text-xs">{countedCount}/{drawers.length} {t("counted", "contadas")}</span></div>
          <div className="space-y-2.5">
            {drawers.map((d) => {
              const v = variance(d);
              return (
                <div key={d.id} className="rounded-2xl border border-white/10 bg-card p-4">
                  <div className="flex items-center justify-between mb-3">
                    <div><div className="font-bold text-sm">{d.name}</div><div className="text-white/45 text-xs">{L(d.station, lang)}</div></div>
                    {d.status === "counted"
                      ? <Chip color={Math.abs(v) <= 5 ? "#5FBFA8" : "#ef4444"}>{v === 0 ? t("Balanced", "Cuadrada") : (v > 0 ? "+" : "") + "$" + v}</Chip>
                      : <Chip color="#CBA35C">{t("Open", "Abierta")}</Chip>}
                  </div>
                  <div className="grid grid-cols-4 gap-2 mb-3 text-center">
                    {[[t("Start", "Inicio"), d.start], [t("Cash", "Efectivo"), d.cashSales], [t("Paid-out", "Salidas"), -d.paidOut], [t("Expected", "Esperado"), expected(d)]].map(([l, val], i) => (
                      <div key={i}><div className={"serif text-base " + (i === 3 ? "text-gold-soft" : "text-white")}>{val < 0 ? "-$" + Math.abs(val) : "$" + val}</div><div className="label text-white/40 text-[8px] mt-0.5">{l}</div></div>
                    ))}
                  </div>
                  {d.status === "counted"
                    ? <div className="flex items-center justify-between rounded-xl bg-ink border border-white/10 px-3 py-2 text-sm"><span className="text-white/55">{t("Counted", "Contado")}</span><span className="serif text-lg text-white">${d.counted}</span></div>
                    : <button onClick={() => { setCountFor(d.id); setCountVal(String(expected(d))); }} className="w-full py-2.5 rounded-full bg-coral/15 border border-coral/40 text-coral text-[11px] font-bold uppercase tracking-wider hover:bg-coral hover:text-white transition-all">{t("Count drawer", "Contar caja")}</button>}
                </div>
              );
            })}
          </div>
        </div>

        {/* TIP POOL + DEPOSIT */}
        <div className="space-y-5">
          <div className="rounded-2xl border border-white/10 bg-card p-5">
            <h3 className="text-sm font-black uppercase tracking-wide mb-4 flex items-center gap-2"><Icon name="coins" className="w-4 h-4 text-gold" />{t("Tip pool distribution", "Distribución de propinas")}</h3>
            <div className="flex gap-3 mb-4">
              <div className="flex-1 rounded-xl border border-white/10 bg-ink p-3 text-center"><div className="serif text-xl text-gold-soft">${TIP_POOL.cardTips.toLocaleString()}</div><div className="label text-white/40 text-[9px] mt-1">{t("Card tips", "Propinas tarjeta")}</div></div>
              <div className="flex-1 rounded-xl border border-white/10 bg-ink p-3 text-center"><div className="serif text-xl text-gold-soft">${TIP_POOL.cashTips.toLocaleString()}</div><div className="label text-white/40 text-[9px] mt-1">{t("Cash tips", "Propinas efectivo")}</div></div>
            </div>
            <div className="space-y-2.5">
              {TIP_POOL.splits.map((sp, i) => { const amt = Math.round(tipTotal * sp.pct / 100); return (
                <div key={i} className="flex items-center gap-3">
                  <div className="w-24 shrink-0 text-sm font-semibold">{L(sp.role, lang)}</div>
                  <div className="flex-1 h-2 rounded-full bg-white/10 overflow-hidden"><div className="h-full rounded-full bg-gradient-to-r from-gold to-gold-soft" style={{ width: sp.pct + "%" }}></div></div>
                  <div className="text-right shrink-0 w-24"><span className="serif text-base text-gold-soft">${amt.toLocaleString()}</span><span className="text-white/35 text-[10px] ml-1">/{sp.heads}</span></div>
                </div>
              ); })}
            </div>
            <div className="flex items-center justify-between mt-4 pt-3 border-t border-white/10"><span className="text-sm font-bold uppercase">{t("Total tip out", "Total a repartir")}</span><span className="serif text-2xl text-gold-soft">${tipTotal.toLocaleString()}</span></div>
          </div>

          <div className="rounded-2xl border border-coral/30 bg-coral/5 p-5">
            <div className="flex items-center justify-between mb-1"><span className="label text-white/55 text-[10px]">{t("Cash to deposit (safe)", "Efectivo a depositar (caja fuerte)")}</span></div>
            <div className="serif text-4xl text-coral mb-4">${depositExpected.toLocaleString()}</div>
            <ChargeButton amount={(depositExpected / 1000).toFixed(1) + "K"} label={t("Close night & deposit", "Cerrar noche y depositar")} />
            <p className="text-white/40 text-[11px] text-center mt-3">{t("Locks all drawers and files the nightly cash report.", "Bloquea todas las cajas y registra el reporte de efectivo de la noche.")}</p>
          </div>
        </div>
      </div>

      {/* count modal */}
      {countFor && (() => { const d = drawers.find((x) => x.id === countFor); return (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-6 bg-black/70 backdrop-blur-sm fade-view" onClick={() => setCountFor(null)}>
          <div className="w-full max-w-sm rounded-3xl border border-white/12 bg-ink p-6" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-4"><h3 className="text-xl font-black uppercase">{t("Count drawer", "Contar caja")}</h3><button onClick={() => setCountFor(null)}><Icon name="x" className="w-5 h-5 text-white/50" /></button></div>
            <p className="text-white/55 text-sm mb-1">{d.name} · {L(d.station, lang)}</p>
            <p className="text-white/40 text-xs mb-4">{t("Expected", "Esperado")}: <b className="text-gold-soft">${expected(d)}</b></p>
            <label className="label text-white/45 text-[10px] block mb-1.5">{t("Counted cash in drawer", "Efectivo contado en caja")}</label>
            <div className="relative mb-4"><span className="absolute left-4 top-1/2 -translate-y-1/2 text-white/40 text-lg">$</span><input autoFocus type="number" value={countVal} onChange={(e) => setCountVal(e.target.value)} className="w-full bg-card border border-white/12 rounded-xl pl-9 pr-3 py-3 text-2xl font-bold text-white focus:outline-none focus:border-coral" /></div>
            <button onClick={doCount} className="gbtn w-full py-3.5 rounded-full bg-coral hover:bg-coral-deep text-white text-[12px] font-bold uppercase tracking-[0.14em] flex items-center justify-center gap-2"><Icon name="check" className="w-4 h-4" />{t("Save count", "Guardar conteo")}</button>
          </div>
        </div>
      ); })()}
    </div>
  );
}

Object.assign(window, { CashControlModule });
