// Admin tab — password-gated control panel for entering team medals.
// Password is checked via PBKDF2-SHA256 (100k iterations) against a stored hash.
// Plaintext is never in source — even brute-forcing the hash takes ~years.
const { useState: useStateAdmin, useEffect: useEffectAdmin } = React;

const ADMIN_PASSWORD_HASH = 'bfa22f165e210f2f29690930980b23bbe3d6d2bb1134e1462f4655e3871be461';
const ADMIN_PASSWORD_SALT = 'oleampics-xxx-2026-admin';
const ADMIN_PASSWORD_ITERATIONS = 100000;

async function checkAdminPassword(input) {
  const enc = new TextEncoder();
  const keyMaterial = await crypto.subtle.importKey(
    'raw', enc.encode(input.trim().toUpperCase()), 'PBKDF2', false, ['deriveBits']
  );
  const bits = await crypto.subtle.deriveBits(
    { name: 'PBKDF2', salt: enc.encode(ADMIN_PASSWORD_SALT), iterations: ADMIN_PASSWORD_ITERATIONS, hash: 'SHA-256' },
    keyMaterial,
    256
  );
  const hex = Array.from(new Uint8Array(bits)).map(b => b.toString(16).padStart(2, '0')).join('');
  return hex === ADMIN_PASSWORD_HASH;
}

function AdminTab({ medals, setMedals, onAuthChange }) {
  const [authed, setAuthed] = useStateAdmin(false);
  const [pwd, setPwd] = useStateAdmin('');
  const [err, setErr] = useStateAdmin('');
  const [shake, setShake] = useStateAdmin(false);

  useEffectAdmin(() => { onAuthChange && onAuthChange(authed); }, [authed]);

  const [checking, setChecking] = useStateAdmin(false);
  const submit = async (e) => {
    if (e) e.preventDefault();
    if (checking) return;
    setChecking(true);
    setErr('');
    try {
      const ok = await checkAdminPassword(pwd);
      if (ok) {
        setAuthed(true);
        setPwd('');
      } else {
        setShake(true);
        setErr('WRONG PASSWORD');
        setTimeout(() => setShake(false), 500);
      }
    } catch {
      setErr('CHECK FAILED');
    } finally {
      setChecking(false);
    }
  };

  return (
    <div>
      <div className="section-title">
        ADMIN
        {authed && (
          <button
            className="pixel-btn ghost"
            style={{ marginLeft: 'auto', padding: '4px 8px', fontSize: 7 }}
            onClick={() => setAuthed(false)}
          >LOCK</button>
        )}
      </div>
      {authed
        ? <AdminPanel medals={medals} setMedals={setMedals} />
        : (
          <form onSubmit={submit} className={`admin-gate ${shake ? 'shake' : ''}`}>
            <div className="admin-gate-card">
              <div className="admin-gate-eye">RESTRICTED</div>
              <div className="admin-gate-title">HOST PANEL</div>
              <p className="admin-gate-sub">Cause you thought you were old enough to have access??</p>
              <input
                type="password"
                inputMode="text"
                autoCapitalize="characters"
                autoComplete="off"
                spellCheck="false"
                value={pwd}
                onChange={e => setPwd(e.target.value)}
                placeholder="PASSWORD"
                className="admin-gate-input"
                maxLength={20}
              />
              <button type="submit" className="pixel-btn" style={{ width: '100%' }}>UNLOCK</button>
              {err && <div className="admin-gate-err">{err}</div>}
            </div>
          </form>
        )}
    </div>
  );
}

function AdminPanel({ medals, setMedals }) {
  const { TEAMS, PLAYERS } = window.LEA30;
  const teamOrder = ['orange', 'yellow', 'green', 'blue'];

  const setVal = (tk, key, n) => {
    const v = Math.max(0, Math.min(99, parseInt(n, 10) || 0));
    setMedals(prev => ({
      ...prev,
      [tk]: { ...prev[tk], [key]: v },
    }));
  };
  const adjust = (tk, key, delta) => {
    setMedals(prev => ({
      ...prev,
      [tk]: { ...prev[tk], [key]: Math.max(0, Math.min(99, (prev[tk]?.[key] || 0) + delta)) },
    }));
  };
  const reset = () => {
    if (confirm('Reset all medals to zero?')) setMedals(window.LEA30.DEFAULT_MEDALS);
  };
  const score = (m) => m.gold * 3 + m.silver * 2 + m.bronze * 1;

  return (
    <div className="admin-panel">
      <div className="admin-blurb">
        Award medals as games end. Updates the home page podium and the rankings tab in real time.
      </div>

      {teamOrder.map(tk => {
        const team = TEAMS[tk];
        const m = medals[tk] || { gold: 0, silver: 0, bronze: 0 };
        const players = PLAYERS.filter(p => p.team === tk).map(p => p.name).join(' · ');
        return (
          <div key={tk} className="admin-team-card" style={{ '--team-col': team.color }}>
            <div className="admin-team-head">
              <div className="admin-team-pip" />
              <div className="admin-team-name">{team.label}</div>
              <div className="admin-team-score">SCORE · {score(m)}</div>
            </div>
            <div className="admin-team-roster">{players}</div>

            {[
              { k: 'gold',   label: 'GOLD',   color: 'var(--gold)' },
              { k: 'silver', label: 'SILVER', color: 'var(--silver)' },
              { k: 'bronze', label: 'BRONZE', color: 'var(--bronze)' },
            ].map(({ k, label, color }) => (
              <div key={k} className="admin-medal-row">
                <div className="admin-medal-tag">
                  <span className="admin-medal-dot" style={{ background: color }} />
                  <span style={{ color }}>{label}</span>
                </div>
                <button type="button" className="pixel-btn ghost admin-step" onClick={() => adjust(tk, k, -1)}>−</button>
                <input
                  type="number"
                  min="0"
                  max="99"
                  value={m[k]}
                  onChange={e => setVal(tk, k, e.target.value)}
                  className="admin-num"
                />
                <button type="button" className="pixel-btn ghost admin-step" onClick={() => adjust(tk, k, +1)}>+</button>
              </div>
            ))}
          </div>
        );
      })}

      <div className="admin-actions">
        <button className="pixel-btn ghost" onClick={reset}>RESET ALL</button>
      </div>

      <p className="admin-footnote">
        Tip: tap +/− for one-tap medals or type a number for big jumps. Saved to this device.
      </p>
    </div>
  );
}

window.AdminTab = AdminTab;
