// Dopamine layer — XP/level HUD, streak meter, jackpot ticker, leaderboard peek,
// win celebration overlay, achievement toasts. Restrained, terminal-flavored —
// glows and acid accents, NOT casino. All game numbers come from VD_PLAYER / VD_LEADERBOARD / VD_ACHIEVEMENTS.

const { useState: useStateD, useEffect: useEffectD, useRef: useRefD, useMemo: useMemoD } = React;

// =================== XP HUD (sits in top nav) ===================
// Compact strip: rank chip · streak · XP bar · jackpot ticker
function PlayerHUD({ onOpen }) {
  const VD = window.VD;
  const p = VD.VD_PLAYER;
  return (
    <button onClick={onOpen} className="vd-hud" title={`Streak ${p.streak}d · LV${p.level} · click for player file`} style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      height: 36, padding: '0 12px', borderRadius: 4,
      border: '1px solid var(--line-subtle)',
      background: 'var(--bg-elev-2)',
      transition: 'border-color 120ms var(--ease)',
    }} onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--acid)'}
       onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--line-subtle)'}>
      <FlameIcon active />
      <span className="num" style={{ fontSize: 12, fontWeight: 600 }}>
        {p.streak}<span style={{ color: 'var(--text-3)', fontSize: 10, marginLeft: 1 }}>d</span>
      </span>
    </button>
  );
}

// Octagonal rank pip — small SVG, color escalates with tier
function RankPip({ tier = 0, size = 14 }) {
  const colors = ['#5C6770', '#6BE5C1', '#8DA8C8', '#E8FF52', '#E8FF52', '#FF5C6E', '#F0B23F', '#FF5C6E'];
  const c = colors[Math.min(tier, colors.length - 1)];
  const filled = tier;
  return (
    <svg width={size} height={size} viewBox="0 0 16 16">
      <polygon points="8,1 13,3.5 15,8 13,12.5 8,15 3,12.5 1,8 3,3.5"
        fill="none" stroke={c} strokeWidth="1.5" />
      {filled >= 1 && <polygon points="8,4 11,5.5 12,8 11,10.5 8,12 5,10.5 4,8 5,5.5" fill={c} opacity="0.9"/>}
    </svg>
  );
}

function FlameIcon({ active = false, size = 12 }) {
  // Geometric flame — chevron stack — fits the terminal aesthetic, no emoji-style curves
  const c = active ? 'var(--coral)' : 'var(--text-4)';
  return (
    <svg width={size} height={size + 2} viewBox="0 0 12 14" fill="none" style={active ? { filter: 'drop-shadow(0 0 3px rgba(255,92,110,0.6))' } : undefined}>
      <path d="M6 1 L10 6 L8 6 L10 9.5 L7.5 9.5 L9 13 L3 13 L4.5 9.5 L2 9.5 L4 6 L2 6 Z" fill={c} />
      {active && <path d="M6 5 L7.5 7.5 L6.5 7.5 L7.5 10 L4.5 10 L5.5 7.5 L4.5 7.5 Z" fill="var(--amber)" opacity="0.95" />}
    </svg>
  );
}

// =================== Player drawer (opened from HUD) ===================
function PlayerDrawer({ onClose }) {
  const VD = window.VD;
  const p = VD.VD_PLAYER;
  const lb = VD.VD_LEADERBOARD;
  const ach = VD.VD_ACHIEVEMENTS;
  const xpPct = Math.min(1, p.xp / p.xpNext);

  useEffectD(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, []);

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 1200,
      background: 'rgba(7,9,12,0.6)',
      backdropFilter: 'blur(4px)',
      display: 'flex', justifyContent: 'flex-end',
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 480, maxWidth: '100vw', height: '100vh',
        background: 'var(--bg-base)',
        borderLeft: '1px solid var(--line-subtle)',
        display: 'flex', flexDirection: 'column',
        animation: 'vd-drawer 240ms var(--ease)',
        overflow: 'auto',
      }}>
        {/* Header */}
        <div style={{ padding: '24px 28px 20px', borderBottom: '1px solid var(--line-subtle)', position: 'relative' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <div className="cap-sm" style={{ marginBottom: 8 }}>↳ Player file</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <RankPip tier={p.tierIdx} size={20} />
                <span className="serif" style={{ fontSize: 32, letterSpacing: '-0.02em' }}>{p.handle}</span>
              </div>
              <div style={{ display: 'flex', gap: 14, marginTop: 8, alignItems: 'center' }}>
                <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'var(--text-3)', letterSpacing: '0.12em' }}>LV{p.level}</span>
                <span style={{ color: 'var(--text-4)' }}>·</span>
                <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'var(--text-3)', letterSpacing: '0.12em' }}>RANK #{p.rankNum} <span style={{ color: 'var(--mint)' }}>↑{p.rankDelta}</span></span>
              </div>
            </div>
            <button onClick={onClose} style={{ width: 32, height: 32, borderRadius: 4, border: '1px solid var(--line-subtle)', background: 'var(--bg-elev-2)', color: 'var(--text-2)', fontSize: 16 }}>×</button>
          </div>

          {/* Tier track */}
          <div style={{ marginTop: 22 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
              <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, color: 'var(--text-3)', letterSpacing: '0.1em' }}>TIER PROGRESSION</span>
              <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, color: 'var(--text-3)', letterSpacing: '0.1em' }}>TIER {p.tierIdx + 1} / {p.tiers.length}</span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: `repeat(${p.tiers.length}, 1fr)`, gap: 4 }}>
              {p.tiers.map((t, i) => {
                const reached = i <= p.tierIdx;
                return (
                  <div key={i} style={{
                    height: 4, background: reached ? 'var(--acid)' : 'var(--bg-elev-3)',
                    boxShadow: i === p.tierIdx ? '0 0 6px var(--acid)' : 'none',
                  }} />
                );
              })}
            </div>
          </div>

          {/* XP bar w label */}
          <div style={{ marginTop: 14 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
              <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, color: 'var(--text-3)', letterSpacing: '0.1em' }}>XP</span>
              <span className="num" style={{ fontSize: 11, color: 'var(--text-2)' }}>{p.xp.toLocaleString()} / {p.xpNext.toLocaleString()}</span>
            </div>
            <div style={{ height: 6, background: 'var(--bg-elev-3)', position: 'relative', overflow: 'hidden' }}>
              <div style={{ width: `${xpPct * 100}%`, height: '100%', background: 'linear-gradient(90deg, var(--acid-dim) 0%, var(--acid) 80%)', boxShadow: '0 0 10px var(--acid)' }} />
            </div>
          </div>
        </div>

        {/* Streak block */}
        <div style={{ padding: '20px 28px', borderBottom: '1px solid var(--line-subtle)', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 0 }}>
          <StatCell label="Streak"      value={`${p.streak}d`}       sub={`Best ${p.streakBest}`} accent="coral" icon={<FlameIcon active />} />
          <StatCell label="Hit streak"  value={`${p.hitStreak}W`}    sub="trades in a row"        accent="mint"  />
          <StatCell label="Jackpot"     value={`$${(p.jackpot/1000).toFixed(1)}k`} sub={p.jackpotResets} accent="acid" />
        </div>

        {/* Last 7 days */}
        <div style={{ padding: '18px 28px', borderBottom: '1px solid var(--line-subtle)' }}>
          <div className="cap-sm" style={{ marginBottom: 10 }}>↳ Last 7 days</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4 }}>
            {p.recent.map((d, i) => (
              <div key={i} style={{
                height: 36,
                background: d > 0 ? 'var(--mint-bg20)' : 'var(--coral-bg20)',
                border: `1px solid ${d > 0 ? 'rgba(107,229,193,0.3)' : 'rgba(255,92,110,0.3)'}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: 'JetBrains Mono, monospace', fontSize: 12, fontWeight: 600,
                color: d > 0 ? 'var(--mint)' : 'var(--coral)',
              }}>{d > 0 ? 'W' : 'L'}</div>
            ))}
          </div>
        </div>

        {/* Leaderboard peek */}
        <div style={{ padding: '18px 28px', borderBottom: '1px solid var(--line-subtle)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
            <div className="cap-sm">↳ This week's board</div>
            <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, color: 'var(--text-3)', letterSpacing: '0.1em' }}>RESETS {p.jackpotResets.toUpperCase()}</span>
          </div>
          <div style={{ border: '1px solid var(--line-subtle)' }}>
            {lb.map((row, i) => {
              const ahead = row.rank < p.rankNum;
              const skip = i === 3; // visual gap between top-3 and you
              return (
                <React.Fragment key={row.rank}>
                  {skip && <div style={{ padding: '4px 0', textAlign: 'center', color: 'var(--text-4)', fontFamily: 'JetBrains Mono, monospace', fontSize: 10, borderBottom: '1px solid var(--line-subtle)', borderTop: '1px solid var(--line-subtle)', background: 'var(--bg-elev-2)' }}>· · ·</div>}
                  <div style={{
                    display: 'grid', gridTemplateColumns: '40px 1fr auto auto', gap: 12,
                    padding: '10px 14px', alignItems: 'center',
                    background: row.you ? 'var(--acid-bg10)' : 'transparent',
                    borderBottom: i === lb.length - 1 ? 'none' : '1px solid var(--line-subtle)',
                  }}>
                    <span className="num" style={{ fontSize: 11, color: row.you ? 'var(--acid)' : 'var(--text-3)', fontWeight: 600 }}>#{row.rank}</span>
                    <span style={{ fontSize: 13, fontWeight: row.you ? 600 : 500, color: row.you ? 'var(--acid)' : 'var(--text)' }}>
                      {row.handle}{row.you && <span style={{ marginLeft: 8, fontFamily: 'JetBrains Mono, monospace', fontSize: 9, letterSpacing: '0.12em', color: 'var(--acid-dim)' }}>YOU</span>}
                    </span>
                    {row.rank <= 3 && <span style={{ fontSize: 11, fontFamily: 'JetBrains Mono, monospace', color: 'var(--amber)', letterSpacing: '0.1em' }}>{row.rank === 1 ? '◆ JACKPOT' : row.rank === 2 ? '◇ 2ND' : '◇ 3RD'}</span>}
                    {row.rank > 3 && <span></span>}
                    <span className="num" style={{ fontSize: 13, fontWeight: 600, color: 'var(--mint)' }}>+{row.pnlPct.toFixed(1)}%</span>
                  </div>
                </React.Fragment>
              );
            })}
          </div>
        </div>

        {/* Achievements */}
        <div style={{ padding: '18px 28px 32px' }}>
          <div className="cap-sm" style={{ marginBottom: 12 }}>↳ Achievements <span style={{ color: 'var(--text-4)' }}>· {ach.filter(a => a.done).length}/{ach.length}</span></div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {ach.map(a => <AchTile key={a.id} a={a} />)}
          </div>
        </div>
      </div>
    </div>
  );
}

function StatCell({ label, value, sub, accent, icon }) {
  const colorMap = { mint: 'var(--mint)', coral: 'var(--coral)', acid: 'var(--acid)' };
  return (
    <div style={{ padding: '4px 14px', borderRight: '1px solid var(--line-subtle)' }}>
      <div className="cap-sm" style={{ marginBottom: 6, display: 'flex', alignItems: 'center', gap: 6 }}>
        {icon}{label}
      </div>
      <div className="num" style={{ fontSize: 22, fontWeight: 600, color: colorMap[accent], lineHeight: 1, textShadow: `0 0 12px ${colorMap[accent]}33` }}>{value}</div>
      <div style={{ color: 'var(--text-3)', fontSize: 10, marginTop: 4, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.04em' }}>{sub}</div>
    </div>
  );
}

function AchTile({ a }) {
  const done = a.done;
  return (
    <div style={{
      padding: '12px 14px',
      border: '1px solid var(--line-subtle)',
      background: done ? 'var(--bg-elev-2)' : 'transparent',
      borderLeft: done ? '2px solid var(--acid)' : '2px solid var(--bg-elev-3)',
      position: 'relative',
      opacity: done ? 1 : 0.55,
    }}>
      {a.fresh && <span style={{ position: 'absolute', top: 8, right: 8, fontFamily: 'JetBrains Mono, monospace', fontSize: 8, letterSpacing: '0.1em', color: 'var(--acid)', background: 'var(--acid-bg20)', padding: '1px 5px', border: '1px solid rgba(232,255,82,0.3)' }}>NEW</span>}
      <div style={{ fontWeight: 600, fontSize: 13, marginBottom: 4, color: done ? 'var(--text)' : 'var(--text-2)' }}>{a.name}</div>
      <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 8, lineHeight: 1.4 }}>{a.desc}</div>
      {!done && a.progress != null && (
        <div style={{ height: 2, background: 'var(--bg-elev-3)', marginBottom: 6 }}>
          <div style={{ width: `${a.progress * 100}%`, height: '100%', background: 'var(--text-3)' }} />
        </div>
      )}
      <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, color: done ? 'var(--acid)' : 'var(--text-3)', letterSpacing: '0.1em' }}>+{a.xp} XP</div>
    </div>
  );
}

// =================== Achievement toast (corner) ===================
function AchievementToast({ a, onDone }) {
  useEffectD(() => {
    const t = setTimeout(onDone, 4400);
    return () => clearTimeout(t);
  }, []);
  return (
    <div style={{
      position: 'fixed', top: 84, right: 24, zIndex: 1300,
      width: 320, padding: '14px 16px',
      background: 'var(--bg-elev-2)',
      border: '1px solid var(--acid)',
      borderLeft: '3px solid var(--acid)',
      boxShadow: '0 0 24px rgba(232,255,82,0.25), 0 8px 32px rgba(0,0,0,0.4)',
      animation: 'vd-ach-pop 360ms var(--ease)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
        <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, color: 'var(--acid)', letterSpacing: '0.16em' }}>◆ ACHIEVEMENT UNLOCKED</span>
      </div>
      <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 4, letterSpacing: '-0.01em' }}>{a.name}</div>
      <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 8 }}>{a.desc}</div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'var(--mint)', letterSpacing: '0.1em' }}>+{a.xp} XP</span>
        <button onClick={onDone} style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, color: 'var(--text-3)', letterSpacing: '0.12em' }}>DISMISS</button>
      </div>
    </div>
  );
}

// =================== Win celebration overlay ===================
// Triggered programmatically: window.VDDopamine.celebrate({ pnl, pct, sym, side, strike })
function WinOverlay({ data, onDone }) {
  useEffectD(() => {
    const t = setTimeout(onDone, 2600);
    return () => clearTimeout(t);
  }, []);

  // Confetti particles
  const particles = useMemoD(() => {
    return Array.from({ length: 60 }, (_, i) => ({
      x: 50 + (Math.random() - 0.5) * 120,
      angle: Math.random() * 360,
      dist: 200 + Math.random() * 280,
      delay: Math.random() * 240,
      dur: 1400 + Math.random() * 800,
      size: 4 + Math.random() * 6,
      color: ['var(--acid)', 'var(--mint)', 'var(--amber)', 'var(--acid)'][i % 4],
      spin: Math.random() * 720,
    }));
  }, []);

  const win = data.pnl >= 0;

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 1500,
      pointerEvents: 'none',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      {/* Vignette */}
      <div style={{
        position: 'absolute', inset: 0,
        background: win
          ? 'radial-gradient(circle at center, rgba(232,255,82,0.18) 0%, transparent 50%)'
          : 'radial-gradient(circle at center, rgba(255,92,110,0.12) 0%, transparent 50%)',
        animation: 'vd-flash 600ms var(--ease)',
      }} />

      {/* Particles */}
      {win && particles.map((p, i) => (
        <div key={i} style={{
          position: 'absolute', top: '50%', left: '50%',
          width: p.size, height: p.size,
          background: p.color, borderRadius: i % 3 === 0 ? '50%' : 0,
          boxShadow: `0 0 6px ${p.color}`,
          animation: `vd-confetti-${i % 8} ${p.dur}ms var(--ease) ${p.delay}ms forwards`,
          ['--ang']: `${p.angle}deg`, ['--dist']: `${p.dist}px`, ['--spin']: `${p.spin}deg`,
        }} />
      ))}

      {/* Centered card */}
      <div style={{
        position: 'relative',
        padding: '32px 48px',
        background: 'var(--bg-elev-2)',
        border: `1px solid ${win ? 'var(--acid)' : 'var(--coral)'}`,
        boxShadow: win
          ? '0 0 64px rgba(232,255,82,0.4), 0 0 24px rgba(232,255,82,0.5) inset'
          : '0 0 48px rgba(255,92,110,0.3)',
        textAlign: 'center',
        animation: 'vd-win-pop 480ms cubic-bezier(.2,1.4,.4,1)',
        minWidth: 360,
      }}>
        <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: win ? 'var(--acid)' : 'var(--coral)', letterSpacing: '0.24em', marginBottom: 14 }}>
          {win ? '◆ ◆ ◆  VERDICT  ◆ ◆ ◆' : '✕  VERDICT  ✕'}
        </div>
        <div className="serif" style={{ fontSize: 64, lineHeight: 1, fontWeight: 400, marginBottom: 6, color: win ? 'var(--acid)' : 'var(--coral)', letterSpacing: '-0.03em', fontStyle: 'italic' }}>
          {win ? 'YOU WIN' : 'You miss'}
        </div>
        <div className="num" style={{ fontSize: 36, fontWeight: 600, color: win ? 'var(--mint)' : 'var(--coral)', marginTop: 12, letterSpacing: '-0.02em' }}>
          {data.pnl >= 0 ? '+' : ''}${Math.abs(data.pnl).toFixed(2)}
        </div>
        <div style={{ fontSize: 12, color: 'var(--text-3)', marginTop: 6, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.08em' }}>
          {data.sym} {data.side} ${data.strike} · {data.pct >= 0 ? '+' : ''}{data.pct.toFixed(1)}%
        </div>
        {win && data.xp && (
          <div style={{ marginTop: 18, padding: '10px 14px', background: 'var(--acid-bg10)', border: '1px solid rgba(232,255,82,0.3)', display: 'inline-flex', gap: 8, alignItems: 'center' }}>
            <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'var(--acid)', letterSpacing: '0.14em' }}>+{data.xp} XP</span>
            {data.streak && <><span style={{ color: 'var(--text-4)' }}>·</span><span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'var(--coral)', letterSpacing: '0.14em' }}>STREAK ×{data.streak}</span></>}
          </div>
        )}
      </div>
    </div>
  );
}

// =================== Public API + global event hub ===================
const VDDopamine = {
  PlayerHUD,
  PlayerDrawer,
  WinOverlay,
  AchievementToast,
  // Imperative helper used by anywhere in the app
  _listeners: [],
  on(fn) { this._listeners.push(fn); return () => { this._listeners = this._listeners.filter(f => f !== fn); }; },
  emit(ev) { this._listeners.forEach(fn => fn(ev)); },
  celebrate(payload) { this.emit({ kind: 'celebrate', payload }); },
  achievement(a) { this.emit({ kind: 'achievement', payload: a }); },
};

window.VDDopamine = VDDopamine;

// =================== Inject global keyframes ===================
(() => {
  if (document.getElementById('vd-dopamine-styles')) return;
  const s = document.createElement('style');
  s.id = 'vd-dopamine-styles';
  // Generate 8 confetti angle classes
  const confettiKfs = Array.from({ length: 8 }, (_, i) => {
    const ang = (i * 45) + (Math.random() * 30 - 15);
    return `
      @keyframes vd-confetti-${i} {
        0%   { transform: translate(-50%, -50%) rotate(0deg); opacity: 1; }
        100% { transform: translate(calc(-50% + ${Math.cos(ang * Math.PI/180) * 360}px), calc(-50% + ${Math.sin(ang * Math.PI/180) * 360 + 200}px)) rotate(${720 + i*60}deg); opacity: 0; }
      }`;
  }).join('\n');

  s.textContent = `
    @keyframes vd-drawer { from { transform: translateX(40px); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
    @keyframes vd-ach-pop { 0% { transform: translateX(40px) scale(0.96); opacity: 0; } 60% { transform: translateX(-4px) scale(1.02); opacity: 1; } 100% { transform: translateX(0) scale(1); opacity: 1; } }
    @keyframes vd-flash { 0% { opacity: 0; } 30% { opacity: 1; } 100% { opacity: 0.6; } }
    @keyframes vd-win-pop { 0% { transform: scale(0.7); opacity: 0; } 60% { transform: scale(1.05); opacity: 1; } 100% { transform: scale(1); opacity: 1; } }
    ${confettiKfs}
  `;
  document.head.appendChild(s);
})();
