// Screen 10: Stats Tab — my stats / leaderboard / operations
const { useState: useStateST } = React;

function StatsTab({ user, mode = "full" }) {
  const items = mode === "my" ? ["MY STATS"] : ["MY STATS", "LEADERBOARD", "OPERATIONS"];
  const [sub, setSub] = useStateST(items[0]);

  return (
    <div className="flex-1 flex flex-col">
      <div className="px-8 pt-5 pb-3 border-b border-zinc-800 flex gap-1">
        {items.map((i) => {
          const isActive = i === sub;
          return (
            <button key={i} onClick={() => setSub(i)}
              className={`h-10 px-5 rounded-lg font-display text-[15px] tracking-wider transition ${
                isActive ? "bg-zinc-100 text-zinc-950" : "text-zinc-400 hover:bg-zinc-900 hover:text-zinc-200"
              }`}>
              {i}
            </button>
          );
        })}
      </div>
      {sub === "MY STATS" && <MyStats user={user} />}
      {sub === "LEADERBOARD" && <Leaderboard user={user} />}
      {sub === "OPERATIONS" && <Operations />}
    </div>
  );
}

function MyStats({ user }) {
  const stats = window.MY_STATS["Cole Mirovsky"]; // demo data
  const w = stats.week;
  const max = Math.max(w.KITTING, w.ASSY, w.SHIPPING, w.RECEIVING);
  const earnedIds = window.BADGES_EARNED[user.name] || window.BADGES_EARNED["Cole Mirovsky"];
  const total = w.KITTING + w.ASSY + w.SHIPPING + w.RECEIVING;
  const [view, setView] = useStateST("WEEK");

  return (
    <div className="flex-1 px-8 py-6 overflow-y-auto">
      <div className="max-w-[1100px] mx-auto space-y-6">
        {/* Profile */}
        <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-6 flex items-center gap-5">
          <window.Avatar user={user} size={80} />
          <div className="flex-1">
            <div className="font-display text-[44px] leading-none tracking-tight">{user.name}</div>
            <div className="flex items-center gap-3 mt-2">
              <window.RoleBadge role={user.role} />
              <span className="text-zinc-400 text-[14px]">{user.shift} shift · Member since {user.since}</span>
            </div>
          </div>
          <div className="flex gap-1 bg-zinc-950 border border-zinc-800 rounded-lg p-1">
            {["WEEK", "ALL TIME"].map((v) => (
              <button key={v} onClick={() => setView(v)}
                className={`h-10 px-4 rounded-md text-[13px] font-display tracking-wider transition ${
                  view === v ? "bg-zinc-100 text-zinc-950" : "text-zinc-400 hover:text-zinc-200"
                }`}>
                {v}
              </button>
            ))}
          </div>
        </div>

        {/* Session bars */}
        <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-6">
          <div className="flex items-center justify-between mb-5">
            <div className="font-display text-[24px] tracking-wider text-zinc-300">SESSIONS · {view}</div>
            <div className="font-display text-[28px] tabular-nums">
              {view === "WEEK" ? total : "142"} <span className="text-[15px] text-zinc-500 font-sans tracking-normal normal-case">total</span>
            </div>
          </div>
          <div className="space-y-3">
            <Bar label="KITTING" value={w.KITTING} max={max} avg={`${w.kitAvg} min avg`} color="bg-sky-500" />
            <Bar label="ASSEMBLY" value={w.ASSY} max={max} avg={`${w.assyAvg} min avg`} color="bg-violet-500" />
            <Bar label="SHIPPING" value={w.SHIPPING} max={max} avg={`${w.shipAvg} min avg`} color="bg-orange-500" />
            <Bar label="RECEIVING" value={w.RECEIVING} max={max} avg={`${w.recAvg} min avg`} color="bg-teal-500" />
          </div>
        </div>

        {/* Order contribution + streak */}
        <div className="grid grid-cols-2 gap-4">
          <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-6">
            <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Order contribution</div>
            <div className="font-display text-[44px] tabular-nums leading-none mt-2">{stats.ordersFulfilled}</div>
            <div className="text-[14px] text-zinc-400 mt-1">orders you helped fulfill this week</div>
            <div className="grid grid-cols-3 gap-3 mt-5 pt-5 border-t border-zinc-800">
              <MiniStat label="Your avg O→S" value={`${stats.orderToShip}d`} />
              <MiniStat label="Team avg" value={`${stats.teamOrderToShip}d`} />
              <MiniStat label="Your best" value={`${stats.bestOrderToShip}d`} color="text-emerald-400" />
            </div>
          </div>
          <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-6">
            <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Streak</div>
            <div className="font-display text-[44px] leading-none mt-2 flex items-center gap-3">
              <span className="text-[44px]">🔥</span>
              <span className="text-amber-400 tabular-nums">{stats.streak}</span>
              <span className="text-[18px] text-zinc-400 font-sans tracking-normal normal-case font-normal">sessions, no shortages</span>
            </div>
            <div className="text-[14px] text-zinc-400 mt-4">
              Personal best: <span className="text-zinc-200 tabular-nums">{stats.bestStreak}</span> sessions
            </div>
          </div>
        </div>

        {/* Badges */}
        <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-6">
          <div className="font-display text-[24px] tracking-wider text-zinc-300 mb-4">BADGES · {earnedIds.length} / {window.ALL_BADGES.length}</div>
          <div className="grid grid-cols-4 gap-3">
            {window.ALL_BADGES.map((b) => {
              const earned = earnedIds.includes(b.id);
              return (
                <div key={b.id}
                  className={`rounded-xl border p-4 ${earned ? "bg-zinc-800/50 border-zinc-700" : "bg-zinc-950 border-zinc-800 opacity-50"}`}>
                  <div className={`text-[44px] ${earned ? "" : "grayscale"}`}>{b.icon}</div>
                  <div className={`font-display text-[18px] tracking-wider mt-1 ${earned ? "text-zinc-100" : "text-zinc-600"}`}>{b.name}</div>
                  <div className="text-[12px] text-zinc-500 mt-1 leading-tight">{b.desc}</div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

function Bar({ label, value, max, avg, color }) {
  return (
    <div className="grid grid-cols-[100px_1fr_140px] items-center gap-4">
      <div className="font-display text-[15px] tracking-wider text-zinc-400">{label}</div>
      <div className="h-9 bg-zinc-950 border border-zinc-800 rounded-lg overflow-hidden flex items-center px-2">
        <div className={`h-5 rounded ${color} transition-all`} style={{ width: `${(value / max) * 100}%` }} />
        <div className="ml-auto font-display text-[20px] tabular-nums pr-2">{value}</div>
      </div>
      <div className="text-[13px] text-zinc-500 text-right">{avg}</div>
    </div>
  );
}

function MiniStat({ label, value, color = "text-zinc-100" }) {
  return (
    <div>
      <div className="text-[10px] uppercase tracking-wider text-zinc-500">{label}</div>
      <div className={`font-display text-[24px] tabular-nums leading-none mt-1 ${color}`}>{value}</div>
    </div>
  );
}

function Leaderboard({ user }) {
  const medals = ["🥇", "🥈", "🥉"];
  return (
    <div className="flex-1 px-8 py-6 overflow-y-auto">
      <div className="max-w-[1100px] mx-auto space-y-6">
        <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-6">
          <div className="flex items-center justify-between mb-5">
            <div className="font-display text-[28px] tracking-wider text-zinc-300">WEEK OF MAY 19</div>
            <button className="h-10 px-4 rounded-lg bg-zinc-800 border border-zinc-700 text-[13px] font-display tracking-wider text-zinc-300 hover:bg-zinc-700">
              SORT: SESSIONS ▾
            </button>
          </div>
          <div className="space-y-2">
            {window.LEADERBOARD.map((p, i) => {
              const isMe = p.name === user.name;
              return (
                <div key={p.name}
                  className={`grid grid-cols-[60px_1fr_120px_140px_140px_1fr] items-center gap-3 px-4 py-3 rounded-lg border ${
                    isMe ? "border-l-[4px] border-zinc-800" : "border-transparent"
                  } ${isMe ? "bg-zinc-800/40" : "bg-zinc-950/40"}`}
                  style={isMe ? { borderLeftColor: window.GPS_RED } : {}}>
                  <div className="font-display text-[28px] tabular-nums">{medals[i] || (i+1)}</div>
                  <div className="font-display text-[22px] tracking-tight">{p.name}{isMe && <span className="ml-2 text-[12px] text-zinc-500 font-sans tracking-normal normal-case">(you)</span>}</div>
                  <div className="font-display text-[26px] tabular-nums">{p.sessions}<span className="text-[13px] text-zinc-500 ml-1 font-sans tracking-normal normal-case">sess</span></div>
                  <div className="font-display text-[20px] tabular-nums text-zinc-300">{p.avgKitMin} min</div>
                  <div className="font-display text-[20px] tabular-nums">
                    <span className={p.onTimeRate === 100 ? "text-emerald-400" : p.onTimeRate >= 95 ? "text-zinc-100" : "text-amber-400"}>{p.onTimeRate}%</span>
                    <span className="text-[12px] text-zinc-500 ml-1 font-sans tracking-normal normal-case">on time</span>
                  </div>
                  <div className="text-[24px] text-right">{p.badges.join(" ")}</div>
                </div>
              );
            })}
          </div>
        </div>

        <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-6">
          <div className="font-display text-[24px] tracking-wider text-zinc-300 mb-5">ALL TIME · TOP 5</div>
          <div className="space-y-1">
            {window.LEADERBOARD_ALLTIME.map((p, i) => (
              <div key={p.name} className="grid grid-cols-[40px_1fr_120px_120px_120px] items-center px-3 py-2 text-[14px]">
                <div className="font-display text-[18px] text-zinc-400">{i+1}</div>
                <div className="font-display text-[18px] tracking-tight">{p.name}</div>
                <div className="tabular-nums">{p.sessions} sessions</div>
                <div className="tabular-nums text-zinc-400">{p.avgKitMin} min</div>
                <div className="tabular-nums text-zinc-400">{p.onTimeRate}% on time</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function Operations() {
  const [tab, setTab] = useStateST("TODAY");
  return (
    <div className="flex-1 px-8 py-6 overflow-y-auto">
      <div className="max-w-[1100px] mx-auto space-y-6">
        <div className="flex gap-1 bg-zinc-900 border border-zinc-800 rounded-lg p-1 w-fit">
          {["TODAY", "THIS WEEK", "TRENDS"].map((t) => (
            <button key={t} onClick={() => setTab(t)}
              className={`h-10 px-5 rounded-md font-display text-[14px] tracking-wider transition ${
                tab === t ? "bg-zinc-100 text-zinc-950" : "text-zinc-400 hover:text-zinc-200"
              }`}>
              {t}
            </button>
          ))}
        </div>

        {tab === "TODAY" && (
          <div className="grid grid-cols-2 gap-4">
            <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-5">
              <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Live sessions</div>
              <div className="flex items-center gap-3 mt-3">
                <span className="h-3 w-3 rounded-full bg-emerald-500" style={{ animation: "pulse 1.5s infinite" }} />
                <div className="font-display text-[36px] tabular-nums leading-none">3 active</div>
              </div>
              <div className="text-[13px] text-zinc-400 mt-3 space-y-1">
                <div>Cole Mirovsky · WO-24193 ASSY · step 2 of 5</div>
                <div>Priya Anand · WO-24196 KITTING · step 7 of 11</div>
                <div>Markus Rumswinkel · WO-24187 SHIPPING · 3 labels printed</div>
              </div>
            </div>
            <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-5">
              <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Completed today</div>
              <div className="font-display text-[36px] tabular-nums leading-none mt-3">11</div>
              <div className="grid grid-cols-4 gap-2 mt-4 text-[12px]">
                <div className="bg-sky-500/10 border border-sky-500/30 rounded px-2 py-1 text-center text-sky-300">KIT 5</div>
                <div className="bg-violet-500/10 border border-violet-500/30 rounded px-2 py-1 text-center text-violet-300">ASSY 2</div>
                <div className="bg-orange-500/10 border border-orange-500/30 rounded px-2 py-1 text-center text-orange-300">SHIP 3</div>
                <div className="bg-teal-500/10 border border-teal-500/30 rounded px-2 py-1 text-center text-teal-300">REC 1</div>
              </div>
            </div>
            <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-5 col-span-2">
              <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Active shortages</div>
              <div className="mt-3 space-y-2">
                <div className="flex items-center gap-3 px-3 py-2 rounded-lg bg-red-500/10 border border-red-500/30 text-[14px]">
                  <span className="text-red-300">⚠</span>
                  <span className="font-mono text-red-100">GPS-CN-TMAP-3B</span>
                  <span className="text-zinc-300">T-Connector MAP (3-pin Bosch)</span>
                  <span className="ml-auto text-zinc-400">14 in stock · 12 reserved</span>
                </div>
                <div className="flex items-center gap-3 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30 text-[14px]">
                  <span className="text-amber-300">!</span>
                  <span className="font-mono text-amber-100">GPS-PKG-OC-S</span>
                  <span className="text-zinc-300">Outer Carton — Small</span>
                  <span className="ml-auto text-zinc-400">72 in stock · 6 days left</span>
                </div>
              </div>
            </div>
          </div>
        )}

        {tab === "THIS WEEK" && (
          <div className="grid grid-cols-2 gap-4">
            <StatCard label="Order → Ship" value="1.7d" sub="avg · best 0.3d · worst 4.1d" />
            <StatCard label="On-time rate" value="96%" sub="46 / 48 orders" color="text-emerald-400" />
            <StatCard label="Sessions" value="48" sub="44 complete · 3 paused · 1 abandoned" />
            <StatCard label="Label costs" value="$284.10" sub="UPS Ground $192 · USPS $42 · DHL $50" />
          </div>
        )}

        {tab === "TRENDS" && (
          <div className="space-y-4">
            <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-5">
              <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500 mb-3">Burn rate</div>
              <div className="grid grid-cols-[2fr_1fr_1fr_1fr] text-[12px] uppercase tracking-wider text-zinc-500 px-2 pb-2 border-b border-zinc-800">
                <div>SKU</div><div className="text-right">Units / day</div><div className="text-right">Days left</div><div>Status</div>
              </div>
              <div className="divide-y divide-zinc-800/60">
                {window.INVENTORY.slice(0, 6).map((it) => (
                  <div key={it.sku} className="grid grid-cols-[2fr_1fr_1fr_1fr] items-center px-2 py-2 text-[13px]">
                    <div className="font-mono text-zinc-300">{it.sku}</div>
                    <div className="text-right tabular-nums">{(it.qty / (it.daysLeft || 30)).toFixed(1)}</div>
                    <div className="text-right tabular-nums">{it.daysLeft != null ? `${it.daysLeft}d` : "—"}</div>
                    <div>
                      <span className={`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider border ${INV_STATUS_REF[it.status]?.color || ""}`}>
                        {INV_STATUS_REF[it.status]?.label}
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
            <div className="grid grid-cols-3 gap-3">
              <StatCard label="Kitted, ready to ship" value="$18.4k" />
              <StatCard label="In queue" value="$42.1k" />
              <StatCard label="Blocked by shortage" value="$6.8k" color="text-red-400" />
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

const INV_STATUS_REF = {
  OK: { label: "OK", color: "text-emerald-300 bg-emerald-500/10 border-emerald-500/30" },
  WATCH: { label: "WATCH", color: "text-amber-300 bg-amber-500/10 border-amber-500/30" },
  ORDER_NOW: { label: "ORDER", color: "text-red-300 bg-red-500/15 border-red-500/40" },
  CRITICAL: { label: "CRITICAL", color: "text-red-300 bg-red-500/15 border-red-500/40" },
};

function StatCard({ label, value, sub, color = "text-zinc-100" }) {
  return (
    <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-5">
      <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">{label}</div>
      <div className={`font-display text-[44px] tabular-nums leading-none mt-2 ${color}`}>{value}</div>
      {sub && <div className="text-[13px] text-zinc-400 mt-2">{sub}</div>}
    </div>
  );
}

window.StatsTab = StatsTab;
