// Vault tab — locked behind password. Once unlocked, shows ALL eligible suspects
// at once, each paired with their own object and place. Refreshes every 6 hours.
const { useState: useStateVault, useEffect: useEffectVault } = React;

/*
 * ╔══════════════════════════════════════════════════════════════════════╗
 * ║  Bravo Lancelot, je savais que tu trouverais facilement.             ║
 * ║  Use it to your advantage :)                                         ║
 * ║                                  — la direction des Jeux Oléampics   ║
 * ╚══════════════════════════════════════════════════════════════════════╝
 */
const VAULT_PASSWORD = 'TRAITORS';
const SIX_HOURS_MS = 6 * 60 * 60 * 1000;
// Hosts don't appear as suspects — everyone else does.
const EXCLUDED_SUSPECTS = ['lea', 'marius'];

const OBJECTS = [
  { id: 'candle',   name: 'Candle',        icon: '🕯️' },
  { id: 'card',     name: 'Card',          icon: '💌' },
  { id: 'umbrella', name: 'Umbrella',      icon: '🌂' },
  { id: 'water',    name: 'Water Bottle',  icon: '💧' },
  { id: 'sunglass', name: 'Sunglasses',    icon: '🕶️' },
  { id: 'pillow',   name: 'Pillow',        icon: '🛏️' },
  { id: 'phone',    name: 'Phone',         icon: '📱' },
  { id: 'speaker',  name: 'Speaker',       icon: '🔊' },
  { id: 'dollar',   name: 'Dollar Bill',   icon: '💵' },
  { id: 'keys',     name: 'Keys',          icon: '🔑' },
  { id: 'lipstick', name: 'Lipstick',      icon: '💄' },
  { id: 'book',     name: 'Book',          icon: '📖' },
  { id: 'socks',    name: 'Socks',         icon: '🧦' },
];
const PLACES = [
  { id: 'spa',      name: 'The Outdoor Spa' },
  { id: 'lodge',    name: 'The Main Lodge' },
  { id: 'dome',     name: 'The Dome' },
  { id: 'tiny',     name: 'The Tiny House' },
  { id: 'car',      name: 'The Car' },
  { id: 'bathroom', name: 'The Bathroom' },
  { id: 'yoga',     name: 'The Yoga Room' },
  { id: 'trail',    name: 'The Trail' },
];

// Deterministic hash so each player gets distinct, repeatable picks per 6h-window
function pixHash(str, salt, bucket) {
  let h = (bucket * 2654435761) ^ salt;
  for (let i = 0; i < str.length; i++) {
    h = ((h * 31) ^ str.charCodeAt(i)) >>> 0;
  }
  h = (h ^ (h >>> 16)) >>> 0;
  return h;
}

function buildCases(bucket, killedSlugs) {
  // Compute everyone's assignment first (stable across kills), then filter out the dead.
  const eligible = window.LEA30.PLAYERS.filter(p => !EXCLUDED_SUSPECTS.includes(p.slug));
  const usedObj = new Set();
  const usedPlace = new Set();
  const all = eligible.map(p => {
    let oi = pixHash(p.slug, 17, bucket) % OBJECTS.length;
    let pi = pixHash(p.slug, 31, bucket) % PLACES.length;
    let tries = 0;
    while (usedObj.has(oi) && tries < OBJECTS.length) { oi = (oi + 1) % OBJECTS.length; tries++; }
    tries = 0;
    while (usedPlace.has(pi) && tries < PLACES.length) { pi = (pi + 1) % PLACES.length; tries++; }
    usedObj.add(oi); usedPlace.add(pi);
    return { player: p, object: OBJECTS[oi], place: PLACES[pi] };
  });
  return killedSlugs ? all.filter(c => !killedSlugs[c.player.slug]) : all;
}

function currentBucket() { return Math.floor(Date.now() / SIX_HOURS_MS); }
function msUntilNextCase() { return SIX_HOURS_MS - (Date.now() % SIX_HOURS_MS); }

function VaultTab() {
  // Always locked at start (no persistence across reloads)
  const [unlocked, setUnlocked] = useStateVault(false);
  return (
    <div>
      <div className="section-title">
        VAULT
        {unlocked && (
          <button
            className="pixel-btn ghost"
            style={{ marginLeft: 'auto', padding: '4px 8px', fontSize: 7 }}
            onClick={() => setUnlocked(false)}
          >LOCK</button>
        )}
      </div>
      {unlocked ? <VaultInside /> : <VaultDoor onUnlock={() => setUnlocked(true)} />}
    </div>
  );
}

function VaultDoor({ onUnlock }) {
  const [code, setCode] = useStateVault('');
  const [shake, setShake] = useStateVault(false);
  const [tries, setTries] = useStateVault(0);
  const [opening, setOpening] = useStateVault(false);

  const submit = (e) => {
    if (e) e.preventDefault();
    if (code.trim().toUpperCase() === VAULT_PASSWORD) {
      setOpening(true);
      setTimeout(() => onUnlock(), 1100);
    } else {
      setShake(true);
      setTries(t => t + 1);
      setTimeout(() => { setShake(false); setCode(''); }, 500);
    }
  };

  return (
    <div style={{ padding: '0 12px 24px' }}>
      <div className={`vault-door ${shake ? 'shake' : ''} ${opening ? 'opening' : ''}`}>
        <VaultDoorArt opening={opening} />
        {opening && <div className="vault-flash" />}
      </div>

      {!opening && (
        <form onSubmit={submit} className="vault-input-row">
          <input
            type="text"
            inputMode="text"
            autoCapitalize="characters"
            autoComplete="off"
            spellCheck="false"
            value={code}
            onChange={e => setCode(e.target.value)}
            placeholder="ENTER PASSWORD"
            className="vault-input"
            maxLength={20}
          />
          <button type="submit" className="pixel-btn vault-input-go">ENTER</button>
        </form>
      )}
      {!opening && tries > 0 && (
        <div className="vault-err">ACCESS DENIED · {tries} {tries === 1 ? 'TRY' : 'TRIES'}</div>
      )}
      {!opening && tries >= 3 && (
        <div className="vault-hint">hint: who's playing dirty this weekend?</div>
      )}
    </div>
  );
}

function VaultDoorArt({ opening }) {
  return (
    <svg viewBox="0 0 160 160" className="vault-door-svg" shapeRendering="crispEdges" preserveAspectRatio="xMidYMid meet">
      <rect x="0" y="0" width="160" height="160" fill="#1a1310" />
      <rect x="6" y="6" width="148" height="148" fill="#2a1a0d" />
      <rect x="10" y="10" width="140" height="140" fill="#5a3a1a" />
      <rect x="14" y="14" width="132" height="132" fill="#3a2820" />
      <rect x="2" y="22" width="6" height="14" fill="#7a5a3a" />
      <rect x="2" y="62" width="6" height="14" fill="#7a5a3a" />
      <rect x="2" y="102" width="6" height="14" fill="#7a5a3a" />
      <rect x="152" y="22" width="6" height="14" fill="#7a5a3a" />
      <rect x="152" y="62" width="6" height="14" fill="#7a5a3a" />
      <rect x="152" y="102" width="6" height="14" fill="#7a5a3a" />

      <g className={`door-left ${opening ? 'open' : ''}`}>
        <rect x="14" y="14" width="66" height="132" fill="#4a3025" />
        <rect x="18" y="18" width="58" height="124" fill="#5a3a25" />
        {[24,44,64,84,104,124].map(y => <rect key={y} x="22" y={y} width="4" height="4" fill="#8b6a3a" />)}
        {[24,44,64,84,104,124].map(y => <rect key={y+'b'} x="68" y={y} width="4" height="4" fill="#8b6a3a" />)}
        <g transform="translate(76,80)">
          <circle r="14" fill="#cfb074" />
          <circle r="11" fill="#a88848" />
          <circle r="3" fill="#3a2820" />
          {[0,60,120,180,240,300].map(a => <rect key={a} x="-2" y="-16" width="4" height="6" fill="#cfb074" transform={`rotate(${a})`} />)}
        </g>
      </g>
      <g className={`door-right ${opening ? 'open' : ''}`}>
        <rect x="80" y="14" width="66" height="132" fill="#4a3025" />
        <rect x="84" y="18" width="58" height="124" fill="#5a3a25" />
        {[24,44,64,84,104,124].map(y => <rect key={y} x="88" y={y} width="4" height="4" fill="#8b6a3a" />)}
        {[24,44,64,84,104,124].map(y => <rect key={y+'b'} x="134" y={y} width="4" height="4" fill="#8b6a3a" />)}
        <g transform="translate(84,80)">
          <circle r="14" fill="#cfb074" />
          <circle r="11" fill="#a88848" />
          <circle r="3" fill="#3a2820" />
          {[0,60,120,180,240,300].map(a => <rect key={a} x="-2" y="-16" width="4" height="6" fill="#cfb074" transform={`rotate(${a})`} />)}
        </g>
      </g>
      {opening && <rect x="14" y="14" width="132" height="132" fill="url(#vaultglow)" />}
      <defs>
        <radialGradient id="vaultglow" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#ffd24a" stopOpacity="1" />
          <stop offset="60%" stopColor="#e85d2f" stopOpacity=".6" />
          <stop offset="100%" stopColor="#000" stopOpacity="0" />
        </radialGradient>
      </defs>
    </svg>
  );
}

/* ----- Inside ----- */
function VaultInside() {
  const [bucket, setBucket] = useStateVault(currentBucket());
  const [tick, setTick] = useStateVault(0);
  const [kills, setKills] = useStateVault({}); // { slug: { killer, time, ts } }
  const cases = React.useMemo(() => buildCases(bucket, kills), [bucket, kills]);

  // Countdown ticker — refresh case set every 6h
  useEffectVault(() => {
    const i = setInterval(() => {
      const nb = currentBucket();
      if (nb !== bucket) setBucket(nb);
      setTick(t => t + 1);
    }, 1000);
    return () => clearInterval(i);
  }, [bucket]);

  // Live kill log from Firebase
  useEffectVault(() => {
    const ref = firebase.database().ref('kills');
    const onValue = (snap) => setKills(snap.val() || {});
    ref.on('value', onValue);
    return () => ref.off('value', onValue);
  }, []);

  const ms = msUntilNextCase();
  const hh = String(Math.floor(ms / 3600000)).padStart(2, '0');
  const mm = String(Math.floor((ms % 3600000) / 60000)).padStart(2, '0');
  const ss = String(Math.floor((ms % 60000) / 1000)).padStart(2, '0');

  return (
    <div className="vault-inside">
      <div className="vault-banner">
        <div className="vault-banner-title">WHO · WHAT · WHERE</div>
        <div className="vault-banner-sub">You need to hand the object to the person in that space for it to count.</div>
      </div>

      <div className="vault-timer">
        <span className="vault-timer-label">NEW DOSSIER IN</span>
        <span className="vault-timer-clock">{hh}:{mm}:{ss}</span>
      </div>

      <div className="dossier-list">
        {cases.map((c, idx) => (
          <DossierRow key={c.player.slug} c={c} idx={idx} />
        ))}
      </div>

    </div>
  );
}

function DossierRow({ c, idx }) {
  const team = window.LEA30.TEAMS[c.player.team];
  const [expanded, setExpanded] = useStateVault(false);
  const [confirming, setConfirming] = useStateVault(false);
  const [killer, setKiller] = useStateVault('');
  const [time, setTime] = useStateVault(() => {
    const n = new Date();
    return `${String(n.getHours()).padStart(2,'0')}:${String(n.getMinutes()).padStart(2,'0')}`;
  });
  const [submitting, setSubmitting] = useStateVault(false);
  const [err, setErr] = useStateVault('');

  const submit = async (e) => {
    if (e) e.preventDefault();
    if (!killer.trim() || submitting) return;
    setSubmitting(true);
    setErr('');
    try {
      await firebase.database().ref(`kills/${c.player.slug}`).set({
        killer: killer.trim(),
        time,
        ts: Date.now(),
      });
      // The /kills listener in VaultInside will remove this row from the list.
    } catch (ex) {
      setErr('Failed to save. Try again.');
      setSubmitting(false);
    }
  };

  return (
    <div className="dossier-wrap">
      <div
        className={`dossier ${expanded ? 'expanded' : ''}`}
        style={{ '--team-col': team.color, animationDelay: `${idx * 60}ms` }}
        onClick={() => setExpanded(v => !v)}
      >
        <div className="dossier-num">{String(idx + 1).padStart(2, '0')}</div>
        <div className="dossier-suspect">
          <div className="dossier-head">
            <HeadImg slug={c.player.slug} name={c.player.name} />
          </div>
          <div className="dossier-name">{c.player.name.toUpperCase()}</div>
          <div className="dossier-team">{team.label}</div>
        </div>
        <div className="dossier-arrow">·</div>
        <div className="dossier-cell">
          <div className="dossier-cell-label">WITH</div>
          <div className="dossier-glyph">{c.object.icon}</div>
          <div className="dossier-cell-name">{c.object.name}</div>
        </div>
        <div className="dossier-arrow">·</div>
        <div className="dossier-cell">
          <div className="dossier-cell-label">IN</div>
          <div className="dossier-scene">
            <VaultPlaceArt id={c.place.id} />
          </div>
          <div className="dossier-cell-name">{c.place.name}</div>
        </div>
      </div>

      {expanded && (
        <div className="dossier-action" onClick={(e) => e.stopPropagation()}>
          {!confirming ? (
            <button
              className="pixel-btn"
              style={{ background: '#a01818', borderColor: '#7a0d0d', color: '#fff', width: '100%' }}
              onClick={() => setConfirming(true)}
            >KILL</button>
          ) : (
            <form onSubmit={submit} className="kill-form">
              <input
                autoFocus
                className="vault-input"
                placeholder="YOUR NAME"
                value={killer}
                onChange={e => setKiller(e.target.value)}
                maxLength={30}
              />
              <input
                type="time"
                className="vault-input"
                value={time}
                onChange={e => setTime(e.target.value)}
                style={{ flex: '0 0 110px' }}
              />
              <div style={{ display: 'flex', gap: 6, marginTop: 6, width: '100%' }}>
                <button
                  type="submit"
                  className="pixel-btn"
                  disabled={!killer.trim() || submitting}
                  style={{ flex: 1, background: '#a01818', borderColor: '#7a0d0d', color: '#fff' }}
                >{submitting ? 'SAVING…' : 'CONFIRM KILL'}</button>
                <button
                  type="button"
                  className="pixel-btn ghost"
                  onClick={() => { setConfirming(false); setErr(''); }}
                >CANCEL</button>
              </div>
              {err && <div className="vault-err" style={{ marginTop: 6 }}>{err}</div>}
            </form>
          )}
        </div>
      )}
    </div>
  );
}

function VaultPlaceArt({ id }) {
  const scenes = {
    // Outdoor spa: pine trees flanking a hot tub with steam
    spa:      [[1,12,14,3,'#3ec46a'],[1,2,3,10,'#1a5a30'],[12,2,3,10,'#1a5a30'],[4,7,8,5,'#3aa0ff'],[4,6,8,1,'#67b9ff'],[5,4,1,1,'#cfd8dc'],[8,3,1,1,'#cfd8dc'],[10,4,1,1,'#cfd8dc']],
    // Main lodge: large cabin, peaked roof, two windows, door
    lodge:    [[3,5,10,9,'#5a3a25'],[2,4,12,1,'#a85c14'],[3,3,10,1,'#a85c14'],[5,2,6,1,'#a85c14'],[7,1,2,1,'#a85c14'],[5,7,2,2,'#67b9ff'],[9,7,2,2,'#67b9ff'],[7,10,2,4,'#3a2820']],
    // Geodesic dome: rounded silhouette with seam lines
    dome:     [[2,12,12,2,'#5a3a25'],[3,9,10,3,'#cfd8dc'],[4,8,8,1,'#cfd8dc'],[5,6,6,2,'#cfd8dc'],[6,5,4,1,'#cfd8dc'],[7,4,2,1,'#cfd8dc'],[8,5,1,7,'#9aa3a8'],[3,9,10,1,'#9aa3a8']],
    // Tiny house on wheels
    tiny:     [[3,11,10,2,'#5a3a25'],[4,7,8,4,'#cfb074'],[5,6,6,1,'#a85c14'],[6,5,4,1,'#a85c14'],[7,4,2,1,'#a85c14'],[6,9,2,2,'#3a2820'],[9,8,2,2,'#67b9ff'],[4,13,2,2,'#3a2820'],[10,13,2,2,'#3a2820']],
    // Car: orange body, two windows, two black wheels
    car:      [[2,9,12,3,'#e85d2f'],[3,6,10,3,'#e85d2f'],[4,7,3,2,'#67b9ff'],[9,7,3,2,'#67b9ff'],[3,12,2,2,'#1a1310'],[11,12,2,2,'#1a1310']],
    // Bathroom: tiles with sink and shower
    bathroom: [[2,4,12,9,'#cfd8dc'],[6,5,4,4,'#3aa0ff'],[3,11,3,2,'#9aa3a8']],
    // Yoga room: wooden floor with a mat and a plant
    yoga:     [[2,2,12,12,'#cfb074'],[4,8,8,4,'#a85c14'],[5,9,6,2,'#e85d2f'],[7,4,2,2,'#3ec46a'],[7,3,2,1,'#1a5a30']],
    // Trail through evergreens
    trail:    [[1,2,4,12,'#1a5a30'],[11,2,4,12,'#1a5a30'],[5,12,6,3,'#a85c14'],[6,9,4,3,'#a85c14'],[7,5,2,4,'#a85c14'],[3,3,2,3,'#3ec46a'],[11,4,2,3,'#3ec46a']],
  };
  const def = scenes[id] || scenes.lodge;
  return (
    <svg viewBox="0 0 16 16" shapeRendering="crispEdges" width="100%" height="100%">
      <rect x="0" y="0" width="16" height="16" fill="#1a1310" />
      {def.map(([x,y,w,h,c], i) => <rect key={i} x={x} y={y} width={w} height={h} fill={c} />)}
    </svg>
  );
}

window.VaultTab = VaultTab;
