/* ============================================================
   WORKER — personal tip-split view (points × hours model)
   Each worker sees THEIR share of tonight's pool + the full split.
   ============================================================ */
function WorkerTipsApp() {
  const t = useT(); const { lang } = useLang();
  const TS = window.PP.TIP_SPLIT;
  const [seg, setSeg] = useState("tonight");
  const [confirmed, setConfirmed] = useState(false);

  const pool = TS.cardTips + TS.cashTips;
  const weighted = TS.crew.map((c) => ({ ...c, w: +(c.pts * c.hours).toFixed(2) }));
  const totalW = weighted.reduce((s, c) => s + c.w, 0);
  const shareOf = (w) => Math.round(pool * w / totalW);
  const me = weighted.find((c) => c.me) || weighted[0];
  const mine = shareOf(me.w);
  const minePct = (me.w / totalW * 100);
  const myCard = Math.round(TS.cardTips * me.w / totalW);
  const myCash = mine - myCard;
  const maxW = Math.max(...weighted.map((c) => c.w));

  return (
    <React.Fragment>
      <StatusBar />
      {/* header */}
      <div className="px-5 pt-1 pb-3 shrink-0 flex items-center justify-between">
        <div>
          <div className="label text-coral text-[9px] mb-0.5">{t("My tips", "Mis propinas")}</div>
          <div className="text-[14px] font-black uppercase leading-none">{me.name}</div>
        </div>
        <Chip color={TS.deptColor[me.dept]}>{L(me.role, lang)}</Chip>
      </div>

      <div className="px-5 pb-3 shrink-0">
        <Seg options={[["tonight", t("Tonight", "Esta noche")], ["history", t("History", "Historial")]]} value={seg} onChange={setSeg} />
      </div>

      <AppScroll className="px-5">
        {seg === "tonight" && (
          <div className="space-y-3.5">
            {/* hero — your cut */}
            <div className="rounded-2xl border border-white/10 p-5 relative overflow-hidden" style={{ background: "linear-gradient(140deg, rgba(255,107,91,.22), rgba(201,146,154,.12) 50%, rgba(11,11,12,.5))" }}>
              <div className="absolute -right-8 -top-8 w-32 h-32 rounded-full" style={{ background: "#FF6B5B", filter: "blur(60px)", opacity: 0.25 }}></div>
              <div className="relative">
                <div className="flex items-center justify-between mb-1.5">
                  <span className="label text-white/60 text-[9px]">{t("Your cut tonight", "Tu parte hoy")}</span>
                  <span className="flex items-center gap-1.5 px-2 py-1 rounded-full text-[8px] font-bold uppercase tracking-wider" style={{ color: "#CBA35C", border: "1px solid rgba(203,163,92,.45)" }}><span className="w-1.5 h-1.5 rounded-full bg-gold pulse-dot"></span>{t("Pool open", "Pool abierto")}</span>
                </div>
                <div className="serif text-[48px] text-white leading-none mb-1.5">${mine.toLocaleString()}</div>
                <div className="text-white/55 text-[11px]">{L(TS.date, lang)} · {TS.night}</div>
              </div>
            </div>

            {/* how it's calculated */}
            <div className="rounded-2xl border border-white/10 bg-white/[.03] p-4">
              <div className="label text-white/45 text-[9px] mb-3">{t("How yours is calculated", "Cómo se calcula la tuya")}</div>
              <div className="flex items-center justify-between text-[11.5px] mb-2"><span className="text-white/60">{t("Role points", "Puntos de rol")}</span><span className="font-bold">{me.pts.toFixed(1)} <span className="text-white/40 font-normal">({L(me.role, lang)})</span></span></div>
              <div className="flex items-center justify-between text-[11.5px] mb-2"><span className="text-white/60">{t("Hours worked", "Horas trabajadas")}</span><span className="font-bold">{me.hours.toFixed(1)} h</span></div>
              <div className="flex items-center justify-between text-[11.5px] mb-3 pb-3 border-b border-white/8"><span className="text-white/60">{t("Your share units", "Tus unidades")}</span><span className="font-bold text-coral">{me.w.toFixed(1)} <span className="text-white/40 font-normal">/ {totalW.toFixed(1)}</span></span></div>
              <div className="flex items-center justify-between"><span className="text-[11.5px] text-white/60">{t("= Share of pool", "= % del pool")}</span><span className="serif text-[20px] text-gold-soft">{minePct.toFixed(1)}%</span></div>
            </div>

            {/* card vs cash */}
            <div className="grid grid-cols-2 gap-2.5">
              <div className="rounded-2xl border border-white/10 bg-white/[.03] p-3.5"><Icon name="credit-card" className="w-4 h-4 text-grape mb-2" /><div className="serif text-[20px] text-white">${myCard.toLocaleString()}</div><div className="label text-white/45 text-[8px] mt-1">{t("Digital share", "Parte digital")}</div></div>
              <div className="rounded-2xl border border-white/10 bg-white/[.03] p-3.5"><Icon name="banknote" className="w-4 h-4" style={{ color: "#5FBFA8" }} /><div className="serif text-[20px] text-white mt-2">${myCash.toLocaleString()}</div><div className="label text-white/45 text-[8px] mt-1">{t("Cash share", "Parte efectivo")}</div></div>
            </div>

            {/* full split */}
            <div>
              <div className="flex items-center justify-between mb-2 px-1">
                <span className="label text-white/45 text-[9px]">{t("Tonight's split", "Reparto de hoy")}</span>
                <span className="text-white/40 text-[10px]">{t("Pool", "Pool")} <b className="text-gold-soft">${pool.toLocaleString()}</b></span>
              </div>
              <div className="space-y-1.5">
                {weighted.map((c) => {
                  const amt = shareOf(c.w);
                  return (
                    <div key={c.id} className={"rounded-xl border px-3 py-2.5 " + (c.me ? "border-coral/50 bg-coral/[.08]" : "border-white/10 bg-white/[.02]")}>
                      <div className="flex items-center gap-2.5 mb-1.5">
                        <span className="w-1.5 h-1.5 rounded-full shrink-0" style={{ background: TS.deptColor[c.dept] }}></span>
                        <div className="flex-1 min-w-0"><span className="text-[12px] font-bold">{c.name.split(" ")[0]}</span> <span className="text-white/40 text-[10px]">· {L(c.role, lang)}</span></div>
                        {c.me && <span className="text-[8px] font-black uppercase tracking-wider text-coral">{t("You", "Tú")}</span>}
                        <span className="serif text-[14px] shrink-0" style={{ color: c.me ? "#FF6B5B" : "#E8C8C6" }}>${amt.toLocaleString()}</span>
                      </div>
                      <div className="h-1 rounded-full bg-white/8 overflow-hidden"><div className="h-full rounded-full" style={{ width: (c.w / maxW * 100) + "%", background: c.me ? "linear-gradient(90deg,#FF6B5B,#E8725A)" : TS.deptColor[c.dept] + "99" }}></div></div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* payout */}
            <div className="rounded-2xl border border-white/10 bg-white/[.03] p-4">
              <div className="flex items-center gap-3 mb-3">
                <div className="w-9 h-6 rounded bg-gradient-to-br from-coral to-grape shrink-0"></div>
                <div className="flex-1"><div className="text-[12px] font-semibold">{t("Payout to", "Pago a")} •••• {me.card}</div><div className="text-white/40 text-[10px]">{t("Digital share auto-deposits at close", "La parte digital se deposita al cierre")}</div></div>
              </div>
              <div className="flex items-center gap-2 rounded-xl bg-gold/5 border border-gold/20 px-3 py-2 mb-3 text-[10.5px] text-white/65"><Icon name="banknote" className="w-3.5 h-3.5 text-gold-soft shrink-0" />{t("Cash share collected from the manager at check-out.", "La parte en efectivo se entrega con el manager al salir.")}</div>
              <button onClick={() => setConfirmed(true)} disabled={confirmed} className={"w-full py-3 rounded-full text-[11px] font-bold uppercase tracking-wider flex items-center justify-center gap-2 transition-all " + (confirmed ? "bg-green-500/90 text-white" : "gbtn bg-coral hover:bg-coral-deep text-white")}>
                <Icon name={confirmed ? "check" : "thumbs-up"} className="w-4 h-4" />{confirmed ? t("Confirmed", "Confirmado") : t("Confirm I received it", "Confirmar que recibí")}
              </button>
            </div>
            <p className="text-white/35 text-[10px] text-center px-2 leading-snug">{t("Split = pool × (role points × hours) ÷ total. Updated live as tips come in.", "Reparto = pool × (puntos de rol × horas) ÷ total. Se actualiza en vivo.")}</p>
          </div>
        )}

        {seg === "history" && (
          <div className="space-y-2.5">
            <div className="rounded-2xl border border-white/10 p-4 mb-1" style={{ background: "linear-gradient(135deg, rgba(201,146,154,.15), rgba(11,11,12,.4))" }}>
              <div className="label text-gold-soft text-[9px] mb-1.5">{t("Last 7 nights", "Últimas 7 noches")}</div>
              <div className="serif text-[36px] text-white leading-none">${TS.history.reduce((s, h) => s + h.amt, mine).toLocaleString()}</div>
              <div className="text-white/50 text-[11px] mt-1">{t("Total tips earned", "Total de propinas")}</div>
            </div>
            {[{ date: TS.date, amt: mine, hours: me.hours, live: true }, ...TS.history].map((h, i) => (
              <div key={i} className="flex items-center gap-3 rounded-xl border border-white/10 bg-white/[.03] px-4 py-3">
                <div className="w-9 h-9 rounded-xl bg-white/[.05] flex items-center justify-center shrink-0"><Icon name="coins" className="w-4 h-4 text-gold-soft" /></div>
                <div className="flex-1 min-w-0"><div className="text-[12.5px] font-bold">{L(h.date, lang)}</div><div className="text-white/45 text-[10px]">{h.hours.toFixed(1)} h · {L(me.role, lang)}</div></div>
                {h.live && <Chip color="#CBA35C">{t("Live", "En vivo")}</Chip>}
                <div className="serif text-[16px] text-gold-soft">${h.amt.toLocaleString()}</div>
              </div>
            ))}
          </div>
        )}
      </AppScroll>
    </React.Fragment>
  );
}

Object.assign(window, { WorkerTipsApp });
