const { useState: useStateA, useEffect: useEffectA, useRef: useRefA } = React;

// ── PIN Security ──────────────────────────────────────────────
const PIN_HASH   = "e68259a977d847c9ed26fc47c6855021c9a51eac28a63f9a0c012f7bbac0b556";
const MAX_ATTEMPTS = 3;
const LOCKOUT_MS   = 5 * 60 * 1000;

async function hashPin(pin) {
  const buf = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(pin));
  return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2,"0")).join("");
}
function getLockout() {
  try { return JSON.parse(localStorage.getItem("trix.lockout") || "null") || { attempts: 0, until: 0 }; }
  catch { return { attempts: 0, until: 0 }; }
}
function setLockout(d) { try { localStorage.setItem("trix.lockout", JSON.stringify(d)); } catch {} }
function clearLockout() { try { localStorage.removeItem("trix.lockout"); } catch {} }

function PinStep({ onSuccess }) {
  const [pin, setPin]         = useStateA("");
  const [error, setError]     = useStateA(false);
  const [errMsg, setErrMsg]   = useStateA("");
  const [locked, setLocked]   = useStateA(false);
  const [remaining, setRemaining] = useStateA(0);
  const timerRef = useRefA(null);

  useEffectA(() => {
    function tick() {
      const { until, attempts } = getLockout();
      const now = Date.now();
      if (until > now) {
        setLocked(true);
        setRemaining(Math.ceil((until - now) / 1000));
      } else if (locked) {
        setLocked(false);
        setRemaining(0);
        if (attempts >= MAX_ATTEMPTS) setLockout({ attempts: 0, until: 0 });
      }
    }
    tick();
    timerRef.current = setInterval(tick, 1000);
    return () => clearInterval(timerRef.current);
  }, [locked]);

  async function pressKey(k) {
    if (locked) return;
    if (k === "del") { setPin(p => p.slice(0,-1)); return; }
    if (pin.length >= 4) return;
    const next = pin + k;
    setPin(next);
    if (next.length === 4) {
      const h = await hashPin(next);
      if (h === PIN_HASH) {
        clearLockout();
        onSuccess();
      } else {
        setError(true);
        setTimeout(() => { setError(false); setPin(""); }, 500);
        const state = getLockout();
        const attempts = state.attempts + 1;
        if (attempts >= MAX_ATTEMPTS) {
          const until = Date.now() + LOCKOUT_MS;
          setLockout({ attempts, until });
          setLocked(true);
          setErrMsg("تم الإغلاق · حاول بعد ٥ دقائق");
        } else {
          setLockout({ attempts, until: 0 });
          setErrMsg(`محاولة خاطئة · تبقى ${MAX_ATTEMPTS - attempts} محاولة`);
        }
      }
    }
  }

  const mins = String(Math.floor(remaining / 60)).padStart(2,"0");
  const secs = String(remaining % 60).padStart(2,"0");

  return (
    <div className="admin-screen">
      <div className="pin-shell">
        <div style={{ fontFamily: "Rakkas", fontSize: 80, color: "var(--gold)", textShadow: "0 0 20px var(--gold)", lineHeight: 0.8, marginBottom: 8 }}>♠</div>
        <div className="pin-title">صالة الإدارة</div>
        <div className="pin-sub">أدخل الرمز السري · للحكم فقط</div>
        {locked ? (
          <div style={{ margin: "24px auto", textAlign: "center" }}>
            <div style={{ fontFamily: "Rakkas,serif", fontSize: 64, color: "var(--red)", lineHeight: 1, textShadow: "0 0 20px var(--red)" }}>☠</div>
            <div style={{ fontFamily: "Lalezar,serif", fontSize: 22, color: "var(--red)", marginTop: 10 }}>تم الإغلاق مؤقتاً</div>
            <div style={{ fontFamily: "Rakkas,serif", fontSize: 48, color: "var(--cream)", marginTop: 8, letterSpacing: 4 }}>{mins}:{secs}</div>
            <div style={{ fontFamily: "Cairo,sans-serif", fontSize: 12, color: "var(--cream)", opacity: 0.6, marginTop: 8, fontWeight: 700 }}>محاولات خاطئة كثيرة · انتظر</div>
          </div>
        ) : (
          <>
            <div className="pin-dots">
              {[0,1,2,3].map(i => (
                <div key={i} className={`pin-dot ${pin.length > i ? "filled" : ""} ${error ? "wrong" : ""}`}>{pin[i] ? "●" : ""}</div>
              ))}
            </div>
            {errMsg && <div style={{ fontFamily: "Lalezar,serif", fontSize: 15, color: "var(--red)", marginBottom: 12, textAlign: "center" }}>{errMsg}</div>}
            <div className="pin-pad">
              {[1,2,3,4,5,6,7,8,9].map(n => (
                <button key={n} className="pin-key" onClick={() => pressKey(String(n))}>{n}</button>
              ))}
              <button className="pin-key ghost" disabled></button>
              <button className="pin-key" onClick={() => pressKey("0")}>0</button>
              <button className="pin-key del" onClick={() => pressKey("del")}>حذف</button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

const PRESET_ICONS = ["♛","♠","♥","♦","♣","☠","⚡","🔥","👑","💀","😈","🎯","🃏","🎴","⚔️","🏆"];
const PRESET_COLORS = [
  { name: "ذهبي",    value: "#f5c542" },
  { name: "أحمر",    value: "#e63946" },
  { name: "سماوي",   value: "#22d3ee" },
  { name: "وردي",    value: "#ff4fa3" },
  { name: "ليموني",  value: "#d9f635" },
  { name: "بنفسجي", value: "#a78bfa" },
  { name: "برتقالي", value: "#ff8c42" },
  { name: "أخضر",   value: "#4ade80" },
  { name: "مرجاني",  value: "#fb7185" },
  { name: "أبيض",   value: "#f6efd9" },
];

function AdminPage({ onSaved }) {
  const [authed, setAuthed] = useStateA(false);
  const [tab, setTab]       = useStateA("match");

  // match state
  const [game, setGame]           = useStateA(null);
  const [teamA, setTeamA]         = useStateA([]);
  const [teamB, setTeamB]         = useStateA([]);
  const [active, setActive]       = useStateA("A");
  const [winner, setWinner]       = useStateA(null);
  const [matchStep, setMatchStep] = useStateA("game");
  const [saveError, setSaveError] = useStateA("");

  // badge state
  const [bIcon,   setBIcon]   = useStateA(PRESET_ICONS[0]);
  const [bColor,  setBColor]  = useStateA(PRESET_COLORS[0].value);
  const [bName,   setBName]   = useStateA("");
  const [bFlavor, setBFlavor] = useStateA("");
  const [bPlayer, setBPlayer] = useStateA(null);
  const [bError,  setBError]  = useStateA("");

  // player edit state
  const [editPlayer,  setEditPlayer]  = useStateA(null);
  const [editName,    setEditName]    = useStateA("");
  const [editNick,    setEditNick]    = useStateA("");
  const [editPalette, setEditPalette] = useStateA(0);
  const [pError,      setPError]      = useStateA("");

  // match delete state
  const [confirmDelete, setConfirmDelete] = useStateA(null);
  const [deleteError,   setDeleteError]   = useStateA("");

  if (!authed) return <PinStep onSuccess={() => setAuthed(true)} />;

  // ── Match ──
  function togglePlayer(p) {
    const inA = teamA.includes(p.id), inB = teamB.includes(p.id);
    if (inA) { setTeamA(teamA.filter(id => id !== p.id)); return; }
    if (inB) { setTeamB(teamB.filter(id => id !== p.id)); return; }
    if (active === "A" && teamA.length < 2) {
      const next = [...teamA, p.id];
      setTeamA(next);
      if (next.length === 2) setActive("B");
    } else if (active === "B" && teamB.length < 2) {
      setTeamB([...teamB, p.id]);
    }
  }

  function removeFrom(team, id) {
    if (team === "A") setTeamA(t => t.filter(x => x !== id));
    else setTeamB(t => t.filter(x => x !== id));
    setActive(team);
  }

  function resetMatch() {
    setGame(null); setTeamA([]); setTeamB([]);
    setWinner(null); setActive("A"); setMatchStep("game");
    setSaveError("");
  }

  function saveMatch(w) {
    setWinner(w);
    setMatchStep("saved");
    DB.saveMatch(game, teamA, teamB, w).catch(() => setSaveError("فشل الحفظ في الخادم"));
  }

  // ── Badges ──
  function addBadge() {
    setBError("");
    if (!bName.trim()) return setBError("اكتب اسم الشارة");
    if (!bPlayer)      return setBError("اختر لاعباً");
    const playerBadges = DB.badges.filter(b => b.playerIds.includes(bPlayer));
    if (playerBadges.length >= 2) return setBError("هذا اللاعب عنده شارتين بالفعل");
    const newBadge = { id: "b" + Date.now(), icon: bIcon, label: bName.trim(), color: bColor, flavor: bFlavor.trim() || "🃏", playerIds: [bPlayer] };
    setBName(""); setBFlavor(""); setBPlayer(null);
    DB.saveBadges([...DB.badges, newBadge]).catch(() => setBError("فشل الحفظ في الخادم"));
  }

  function removeBadge(badgeId, playerId) {
    const updated = DB.badges.map(b => {
      if (b.id !== badgeId) return b;
      const ids = b.playerIds.filter(id => id !== playerId);
      return ids.length ? { ...b, playerIds: ids } : null;
    }).filter(Boolean);
    DB.saveBadges(updated).catch(() => {});
  }

  // ── Players ──
  function startEdit(p) {
    setEditPlayer(p.id);
    setEditName(p.name);
    setEditNick(p.nick);
    setEditPalette(p.paletteIndex ?? DB.players.indexOf(p));
    setPError("");
  }

  function savePlayerEdit() {
    if (!editName.trim()) return setPError("اكتب الاسم");
    if (!editNick.trim()) return setPError("اكتب الحرف");
    const updated = DB.raw.players.map(p =>
      p.id === editPlayer
        ? { ...p, name: editName.trim(), nick: editNick.trim()[0], paletteIndex: editPalette }
        : p
    );
    setEditPlayer(null);
    DB.savePlayers(updated).catch(() => setPError("فشل الحفظ في الخادم"));
  }

  const players = DB.players;
  const badges  = DB.badges;

  return (
    <div className="admin-screen">
      {/* Tab switcher */}
      <div style={{ display: "flex", gap: 8, marginBottom: 18 }}>
        {[
          { id: "match",   label: "مباراة ♠" },
          { id: "badges",  label: "شارات ♛" },
          { id: "players", label: "لاعبون ♥" },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            flex: 1, padding: "12px 4px",
            fontFamily: "Lalezar, serif", fontSize: 18,
            border: "3px solid #000", borderRadius: 16,
            background: tab === t.id ? "var(--gold)" : "rgba(0,0,0,0.4)",
            color: tab === t.id ? "#000" : "var(--cream)",
            boxShadow: tab === t.id ? "4px 4px 0 #000" : "3px 3px 0 #000",
            cursor: "pointer",
          }}>{t.label}</button>
        ))}
      </div>

      {/* ── MATCH TAB ── */}
      {tab === "match" && <>
        {matchStep === "game" && <>
          <div className="admin-step-head">
            <span className="step-num">١</span>
            <span className="step-title">اختر اللعبة</span>
          </div>
          <div className="game-select">
            <button className="game-opt" style={{ background: "var(--gold)" }} onClick={() => { setGame("طرنيب"); setMatchStep("teams"); }}>
              <span className="suit-mask">♠</span>
              <div style={{ position: "relative" }}>
                <div className="gn">طرنيب</div>
                <div className="gd">ثنائي ضد ثنائي · حكم · نزال</div>
              </div>
            </button>
            <button className="game-opt" style={{ background: "var(--neon-mag)" }} onClick={() => { setGame("تركس"); setMatchStep("teams"); }}>
              <span className="suit-mask">♦</span>
              <div style={{ position: "relative" }}>
                <div className="gn">تركس</div>
                <div className="gd">خمس ممالك · بلا رحمة</div>
              </div>
            </button>
          </div>

          {/* Match history / delete */}
          <div style={{ marginTop: 24 }}>
            <div className="section-title" style={{ fontSize: 18, marginBottom: 10 }}>سجل المباريات · حذف</div>
            {deleteError && <div style={{ color: "var(--red)", fontFamily: "Lalezar,serif", fontSize: 15, marginBottom: 8, textAlign: "center" }}>{deleteError}</div>}
            {DB.matches.length === 0 && (
              <div style={{ textAlign: "center", opacity: 0.5, fontFamily: "Lalezar,serif", fontSize: 18, marginTop: 16 }}>لا توجد مباريات</div>
            )}
            {DB.matches.map(m => {
              const nameA = m.teamA.map(id => byId(id)?.name ?? "؟").join(" · ");
              const nameB = m.teamB.map(id => byId(id)?.name ?? "؟").join(" · ");
              const winnerLabel = m.winner === "A" ? nameA : nameB;
              const isConfirming = confirmDelete === m.id;
              return (
                <div key={m.id} style={{ background: "rgba(0,0,0,0.4)", border: "2.5px solid #000", borderRadius: 16, padding: "10px 14px", marginBottom: 10, boxShadow: "3px 3px 0 #000", display: "flex", alignItems: "center", gap: 10 }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: "flex", gap: 8, alignItems: "baseline", marginBottom: 3 }}>
                      <span style={{ fontFamily: "Lalezar,serif", fontSize: 15, color: "var(--gold)" }}>{m.game}</span>
                      <span style={{ fontSize: 11, color: "var(--cream)", opacity: 0.55, fontWeight: 700 }}>{arabicDateLabel(m.date)}</span>
                    </div>
                    <div style={{ fontSize: 13, fontWeight: 700, color: "var(--cream)", marginBottom: 2 }}>
                      <span style={{ color: "var(--neon-cyan)" }}>{nameA}</span>
                      <span style={{ opacity: 0.6 }}> ضد </span>
                      <span style={{ color: "var(--neon-mag)" }}>{nameB}</span>
                    </div>
                    <div style={{ fontSize: 12, color: "var(--gold)", fontWeight: 800 }}>فاز: {winnerLabel}</div>
                  </div>
                  {isConfirming ? (
                    <div style={{ display: "flex", gap: 6, flexShrink: 0 }}>
                      <button onClick={() => {
                        setConfirmDelete(null);
                        setDeleteError("");
                        DB.deleteMatch(m.id).catch(() => setDeleteError("فشل الحذف في الخادم"));
                      }} style={{ background: "var(--red)", color: "#fff", border: "2.5px solid #000", borderRadius: 10, padding: "6px 12px", fontFamily: "Lalezar,serif", fontSize: 15, cursor: "pointer", boxShadow: "2px 2px 0 #000" }}>تأكيد</button>
                      <button onClick={() => setConfirmDelete(null)} style={{ background: "#000", color: "var(--cream)", border: "2.5px solid #000", borderRadius: 10, padding: "6px 12px", fontFamily: "Lalezar,serif", fontSize: 15, cursor: "pointer", boxShadow: "2px 2px 0 #000" }}>إلغاء</button>
                    </div>
                  ) : (
                    <button onClick={() => { setConfirmDelete(m.id); setDeleteError(""); }} style={{ background: "rgba(220,38,38,0.2)", color: "var(--red)", border: "2.5px solid var(--red)", borderRadius: 10, padding: "6px 12px", fontFamily: "Lalezar,serif", fontSize: 15, cursor: "pointer", boxShadow: "2px 2px 0 #000", flexShrink: 0 }}>حذف</button>
                  )}
                </div>
              );
            })}
          </div>
        </>}

        {matchStep === "teams" && <>
          <div className="admin-step-head">
            <span className="step-num">٢</span>
            <span className="step-title">اختر الفريقين</span>
            <button className="back" onClick={() => setMatchStep("game")}>رجوع</button>
          </div>
          {["A","B"].map(team => {
            const arr   = team === "A" ? teamA : teamB;
            const label = team === "A" ? "الفريق الأزرق" : "الفريق الوردي";
            const color = team === "A" ? "var(--neon-cyan)" : "var(--neon-mag)";
            return (
              <div key={team} className={`team-panel ${team.toLowerCase()}`}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                  <span className="tname">{label}</span>
                  <button className="btn-secondary"
                    style={{ padding: "4px 10px", fontSize: 14, background: active === team ? "#000" : "transparent", color: active === team ? color : "#000", borderColor: "#000" }}
                    onClick={() => setActive(team)}>{active === team ? "الدور عليه" : "اختر"}</button>
                </div>
                {[0,1].map(i => {
                  const id = arr[i], p = id ? byId(id) : null;
                  return (
                    <div key={i} className={`team-slot ${p ? "filled" : ""}`}>
                      {p
                        ? <><Avatar player={p} size={40} showTag={false} /><span>{p.name}</span><button className="remove" onClick={() => removeFrom(team, id)}>×</button></>
                        : <span style={{ opacity: 0.6 }}>لاعب {i+1}…</span>
                      }
                    </div>
                  );
                })}
              </div>
            );
          })}

          <div className="section-title" style={{ fontSize: 18, marginTop: 14 }}>اللاعبون المتاحون</div>
          <div className="pick-grid">
            {players.map(p => {
              const inA = teamA.includes(p.id), inB = teamB.includes(p.id), picked = inA || inB;
              return (
                <div key={p.id} className={`pick-item ${picked ? "picked" : ""} ${inB ? "team-b" : ""}`}
                  style={{ background: p.palette.bg }} onClick={() => togglePlayer(p)}>
                  <Avatar player={p} size={44} showTag={false} />
                  <span className="nm">{p.name}</span>
                  {inA && <span className="team-tag">الأزرق</span>}
                  {inB && <span className="team-tag">الوردي</span>}
                </div>
              );
            })}
          </div>
          <button className="btn-primary" style={{ marginTop: 18 }}
            disabled={teamA.length !== 2 || teamB.length !== 2}
            onClick={() => setMatchStep("winner")}>متابعة ← الفائز</button>
        </>}

        {matchStep === "winner" && <>
          <div className="admin-step-head">
            <span className="step-num">٣</span>
            <span className="step-title">من كسبها؟</span>
            <button className="back" onClick={() => setMatchStep("teams")}>رجوع</button>
          </div>
          {saveError && <div style={{ color: "var(--red)", fontFamily: "Lalezar,serif", fontSize: 16, marginBottom: 10, textAlign: "center" }}>{saveError}</div>}
          <div className="winner-pick">
            {["A","B"].map(w => {
              const arr   = w === "A" ? teamA : teamB;
              const label = w === "A" ? "الأزرق" : "الوردي";
              const bg    = w === "A" ? "linear-gradient(135deg,#22d3ee,#0891b2)" : "linear-gradient(135deg,#ff4fa3,#c026d3)";
              return (
                <div key={w} className="winner-btn" style={{ background: bg }} onClick={() => saveMatch(w)}>
                  <div className="crown-hint">♛</div>
                  <div className="wtname">{label}</div>
                  <div className="wpl">{arr.map(id => byId(id)?.name).join(" · ")}</div>
                </div>
              );
            })}
          </div>
          <div style={{ marginTop: 22, background: "rgba(0,0,0,0.4)", border: "2.5px dashed rgba(255,255,255,0.2)", borderRadius: 16, padding: 14, fontSize: 13, color: "var(--cream)", fontWeight: 700, textAlign: "center" }}>
            لعبة <b style={{ color: "var(--gold)" }}>{game}</b> · ٢ ضد ٢ · اضغط الفريق الفائز
          </div>
        </>}

        {matchStep === "saved" && (() => {
          const winArr  = winner === "A" ? teamA : teamB;
          const winName = winner === "A" ? "الفريق الأزرق" : "الفريق الوردي";
          return (
            <>
              <Confetti fire={true} />
              <div className="saved-overlay">
                <div className="saved-card">
                  <div style={{ fontFamily: "Rakkas", fontSize: 90, lineHeight: 0.8, marginBottom: 6 }}>♛</div>
                  <div className="headline">تم التسجيل!</div>
                  <div className="sub">مبروك الفوز يا أبطال</div>
                  <div className="win-team">{winName}</div>
                  <div style={{ marginTop: 10, fontWeight: 800 }}>{winArr.map(id => byId(id)?.name).join(" · ")}</div>
                  <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
                    <button className="btn-primary" style={{ fontSize: 18, padding: 12 }} onClick={resetMatch}>مباراة جديدة</button>
                    <button className="btn-primary" style={{ fontSize: 18, padding: 12, background: "#000", color: "var(--gold)" }} onClick={() => { resetMatch(); onSaved?.(); }}>اللوحة</button>
                  </div>
                </div>
              </div>
            </>
          );
        })()}
      </>}

      {/* ── BADGES TAB ── */}
      {tab === "badges" && <>
        <div className="admin-step-head">
          <span className="step-num">♛</span>
          <span className="step-title">إدارة الشارات</span>
        </div>
        <div style={{ background: "rgba(0,0,0,0.45)", border: "3px solid #000", borderRadius: 20, padding: 16, marginBottom: 16, boxShadow: "5px 5px 0 #000" }}>
          <div className="section-title" style={{ fontSize: 18, marginBottom: 12 }}>شارة جديدة</div>

          <div style={{ marginBottom: 12 }}>
            <div style={{ fontFamily: "Lalezar,serif", fontSize: 15, color: "var(--cream)", marginBottom: 6 }}>الأيقونة</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
              {PRESET_ICONS.map(ic => (
                <button key={ic} onClick={() => setBIcon(ic)} style={{ width: 44, height: 44, fontSize: 22, border: "3px solid #000", borderRadius: 12, background: bIcon === ic ? "var(--gold)" : "rgba(255,255,255,0.1)", boxShadow: bIcon === ic ? "3px 3px 0 #000" : "none", cursor: "pointer" }}>{ic}</button>
              ))}
            </div>
          </div>

          <div style={{ marginBottom: 12 }}>
            <div style={{ fontFamily: "Lalezar,serif", fontSize: 15, color: "var(--cream)", marginBottom: 6 }}>اللون</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
              {PRESET_COLORS.map(c => (
                <button key={c.value} onClick={() => setBColor(c.value)} style={{ width: 44, height: 44, background: c.value, border: bColor === c.value ? "4px solid #fff" : "3px solid #000", borderRadius: 12, cursor: "pointer", boxShadow: bColor === c.value ? "0 0 0 3px #000" : "2px 2px 0 #000" }} title={c.name} />
              ))}
            </div>
          </div>

          <input className="field" placeholder="اسم الشارة" value={bName} onChange={e => setBName(e.target.value)} style={{ marginBottom: 10, display: "block" }} />
          <input className="field" placeholder="نص الشارة (مثل: ما بخسر)" value={bFlavor} onChange={e => setBFlavor(e.target.value)} style={{ marginBottom: 10, display: "block" }} />

          <div style={{ fontFamily: "Lalezar,serif", fontSize: 15, color: "var(--cream)", marginBottom: 6 }}>اختر اللاعب</div>
          <div className="pick-grid" style={{ marginBottom: 12 }}>
            {players.map(p => {
              const count = badges.filter(b => b.playerIds.includes(p.id)).length;
              const full  = count >= 2;
              return (
                <div key={p.id} className={`pick-item ${bPlayer === p.id ? "picked" : ""}`}
                  style={{ background: p.palette.bg, opacity: full ? 0.45 : 1, cursor: full ? "not-allowed" : "pointer" }}
                  onClick={() => !full && setBPlayer(p.id)}>
                  <Avatar player={p} size={44} showTag={false} />
                  <span className="nm">{p.name}</span>
                  {full && <span className="team-tag" style={{ background: "#000", color: "#fff" }}>ممتلئ</span>}
                </div>
              );
            })}
          </div>

          {bName.trim() && (
            <div style={{ marginBottom: 12, display: "flex", alignItems: "center", gap: 10, background: bColor, border: "3px solid #000", borderRadius: 14, padding: "10px 14px", boxShadow: "4px 4px 0 #000" }}>
              <span style={{ fontFamily: "Rakkas", fontSize: 28, background: "#000", color: bColor, width: 38, height: 38, borderRadius: 10, display: "grid", placeItems: "center" }}>{bIcon}</span>
              <div>
                <div style={{ fontFamily: "Lalezar", fontSize: 18, color: "#000", lineHeight: 1 }}>{bName}</div>
                <div style={{ fontSize: 11, fontWeight: 800, color: "rgba(0,0,0,0.7)" }}>{bFlavor || "..."}</div>
              </div>
            </div>
          )}

          {bError && <div style={{ color: "var(--red)", fontFamily: "Lalezar,serif", fontSize: 16, marginBottom: 8 }}>{bError}</div>}
          <button className="btn-primary" onClick={addBadge}>إضافة الشارة ✓</button>
        </div>

        <div className="section-title" style={{ fontSize: 18 }}>الشارات الحالية</div>
        {players.map(p => {
          const pb = badges.filter(b => b.playerIds.includes(p.id));
          if (!pb.length) return null;
          return (
            <div key={p.id} style={{ marginBottom: 12, background: "rgba(0,0,0,0.4)", border: "2.5px solid #000", borderRadius: 16, padding: 12, boxShadow: "3px 3px 0 #000" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                <Avatar player={p} size={36} showTag={false} />
                <span style={{ fontFamily: "Lalezar,serif", fontSize: 18, color: "var(--cream)" }}>{p.name}</span>
              </div>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                {pb.map(b => (
                  <div key={b.id} style={{ background: b.color, border: "2.5px solid #000", borderRadius: 12, padding: "6px 10px", display: "flex", alignItems: "center", gap: 6, boxShadow: "2px 2px 0 #000" }}>
                    <span style={{ fontSize: 18 }}>{b.icon}</span>
                    <span style={{ fontFamily: "Lalezar", fontSize: 15, color: "#000" }}>{b.label}</span>
                    <button onClick={() => removeBadge(b.id, p.id)} style={{ background: "#000", color: "#fff", border: "none", borderRadius: "50%", width: 22, height: 22, cursor: "pointer", fontFamily: "Lalezar", fontSize: 14, display: "grid", placeItems: "center" }}>×</button>
                  </div>
                ))}
              </div>
            </div>
          );
        })}
        {badges.filter(b => b.playerIds.length).length === 0 && (
          <div style={{ textAlign: "center", opacity: 0.5, fontFamily: "Lalezar,serif", fontSize: 18, marginTop: 20 }}>لا توجد شارات بعد</div>
        )}
      </>}

      {/* ── PLAYERS TAB ── */}
      {tab === "players" && <>
        <div className="admin-step-head">
          <span className="step-num">♥</span>
          <span className="step-title">إدارة اللاعبين</span>
        </div>
        {players.map(p => (
          <div key={p.id} style={{ background: "rgba(0,0,0,0.4)", border: "2.5px solid #000", borderRadius: 18, padding: 14, marginBottom: 12, boxShadow: "4px 4px 0 #000" }}>
            {editPlayer === p.id ? (
              <div>
                <div style={{ display: "flex", gap: 10, marginBottom: 12, alignItems: "center" }}>
                  <div style={{ width: 56, height: 56, borderRadius: 14, border: "3px solid #000", boxShadow: "3px 3px 0 #000", background: `linear-gradient(135deg, ${PALETTES[editPalette].bg}, #000)`, display: "grid", placeItems: "center", fontFamily: "Lalezar,serif", fontSize: 26, color: "#fff", textShadow: "2px 2px 0 #000", flexShrink: 0 }}>
                    {editNick || "؟"}
                  </div>
                  <div style={{ flex: 1 }}>
                    <input className="field" placeholder="الاسم" value={editName} onChange={e => setEditName(e.target.value)} style={{ marginBottom: 8, display: "block" }} />
                    <input className="field" placeholder="الحرف (حرف واحد)" value={editNick} maxLength={2} onChange={e => setEditNick(e.target.value.slice(0,1))} style={{ display: "block" }} />
                  </div>
                </div>
                <div style={{ fontFamily: "Lalezar,serif", fontSize: 15, color: "var(--cream)", marginBottom: 8 }}>اللون</div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 12 }}>
                  {PALETTES.map((pal, i) => (
                    <button key={i} onClick={() => setEditPalette(i)} style={{ width: 44, height: 44, background: pal.bg, border: editPalette === i ? "4px solid #fff" : "3px solid #000", borderRadius: 12, cursor: "pointer", boxShadow: editPalette === i ? "0 0 0 3px #000" : "2px 2px 0 #000" }} />
                  ))}
                </div>
                {pError && <div style={{ color: "var(--red)", fontFamily: "Lalezar,serif", fontSize: 15, marginBottom: 8 }}>{pError}</div>}
                <div style={{ display: "flex", gap: 10 }}>
                  <button className="btn-primary" style={{ fontSize: 18, padding: 10 }} onClick={savePlayerEdit}>حفظ ✓</button>
                  <button className="btn-primary" style={{ fontSize: 18, padding: 10, background: "#000", color: "var(--cream)" }} onClick={() => setEditPlayer(null)}>إلغاء</button>
                </div>
              </div>
            ) : (
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <Avatar player={p} size={52} showTag={false} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: "Lalezar,serif", fontSize: 20, color: "var(--cream)" }}>{p.name}</div>
                  <div style={{ fontSize: 12, color: "var(--cream)", opacity: 0.6, fontWeight: 700 }}>{p.wins} فوز · {p.losses} خسارة</div>
                </div>
                <button onClick={() => startEdit(p)} style={{ background: "var(--gold)", border: "2.5px solid #000", borderRadius: 12, padding: "8px 14px", fontFamily: "Lalezar,serif", fontSize: 16, cursor: "pointer", boxShadow: "3px 3px 0 #000" }}>تعديل</button>
              </div>
            )}
          </div>
        ))}
      </>}
    </div>
  );
}

Object.assign(window, { AdminPage });