// Draft Mode flow — wired to Supabase
const FORMATIONS = {
  '4-3-3':   { name: '4-3-3',   meta: '1 GK · 4 DEF · 3 MID · 3 ATT',
    positions: [
      { id:'gk',  label:'GK',  x:50, y:92 },
      { id:'lb',  label:'LB',  x:15, y:75 }, { id:'cb1', label:'CB', x:37, y:78 },
      { id:'cb2', label:'CB',  x:63, y:78 }, { id:'rb', label:'RB', x:85, y:75 },
      { id:'cm1', label:'CM',  x:25, y:52 }, { id:'cm2', label:'CM', x:50, y:55 }, { id:'cm3', label:'CM', x:75, y:52 },
      { id:'lw',  label:'LW',  x:20, y:24 }, { id:'st',  label:'ST', x:50, y:18 }, { id:'rw', label:'RW', x:80, y:24 },
    ],
    adj: [['gk','cb1'],['gk','cb2'],['cb1','cb2'],['cb1','lb'],['cb2','rb'],['lb','cm1'],['rb','cm3'],['cm1','cm2'],['cm2','cm3'],['cm1','lw'],['cm2','st'],['cm3','rw'],['lw','st'],['st','rw']],
  },
  '4-4-2':   { name: '4-4-2', meta: '1 GK · 4 DEF · 4 MID · 2 ATT',
    positions: [
      { id:'gk',  label:'GK',  x:50, y:92 },
      { id:'lb',  label:'LB',  x:15, y:75 }, { id:'cb1', label:'CB', x:37, y:78 },
      { id:'cb2', label:'CB',  x:63, y:78 }, { id:'rb', label:'RB', x:85, y:75 },
      { id:'lm',  label:'LM',  x:15, y:50 }, { id:'cm1',label:'CM', x:38, y:52 },
      { id:'cm2', label:'CM',  x:62, y:52 }, { id:'rm', label:'RM', x:85, y:50 },
      { id:'st1', label:'ST',  x:38, y:22 }, { id:'st2',label:'ST', x:62, y:22 },
    ],
    adj: [['gk','cb1'],['gk','cb2'],['cb1','cb2'],['cb1','lb'],['cb2','rb'],['lb','lm'],['rb','rm'],['lm','cm1'],['cm1','cm2'],['cm2','rm'],['cm1','st1'],['cm2','st2'],['st1','st2']],
  },
  '4-2-3-1': { name: '4-2-3-1', meta: '1 GK · 4 DEF · 5 MID · 1 ATT',
    positions: [
      { id:'gk', label:'GK', x:50, y:92 },
      { id:'lb', label:'LB', x:15, y:75 }, { id:'cb1',label:'CB',x:37,y:78 },
      { id:'cb2',label:'CB', x:63, y:78 }, { id:'rb', label:'RB',x:85,y:75 },
      { id:'cdm1',label:'CDM',x:38,y:58 }, { id:'cdm2',label:'CDM',x:62,y:58 },
      { id:'lam',label:'LAM',x:20,y:36 }, { id:'cam',label:'CAM',x:50,y:38 },
      { id:'ram',label:'RAM',x:80,y:36 }, { id:'st',label:'ST',x:50,y:16 },
    ],
    adj: [['gk','cb1'],['gk','cb2'],['cb1','cb2'],['cb1','lb'],['cb2','rb'],['lb','cdm1'],['rb','cdm2'],['cdm1','cdm2'],['cdm1','cam'],['cdm2','cam'],['lam','cam'],['cam','ram'],['lam','st'],['cam','st'],['ram','st']],
  },
  '3-5-2':   { name: '3-5-2', meta: '1 GK · 3 DEF · 5 MID · 2 ATT',
    positions: [
      { id:'gk', label:'GK', x:50, y:92 },
      { id:'cb1',label:'CB', x:25, y:78 }, { id:'cb2',label:'CB',x:50,y:80 }, { id:'cb3',label:'CB', x:75, y:78 },
      { id:'lwb',label:'LWB',x:10, y:52 }, { id:'cm1',label:'CM',x:32,y:54 },
      { id:'cdm',label:'CDM',x:50, y:62 }, { id:'cm2',label:'CM',x:68,y:54 }, { id:'rwb',label:'RWB',x:90, y:52 },
      { id:'st1',label:'ST', x:38, y:20 }, { id:'st2',label:'ST',x:62,y:20 },
    ],
    adj: [['gk','cb2'],['cb1','cb2'],['cb2','cb3'],['cb1','lwb'],['cb3','rwb'],['lwb','cm1'],['rwb','cm2'],['cm1','cdm'],['cm2','cdm'],['cm1','cm2'],['cm1','st1'],['cm2','st2'],['cdm','st1'],['cdm','st2'],['st1','st2']],
  },
  '4-1-2-1-2': { name: '4-1-2-1-2', meta: '1 GK · 4 DEF · 4 MID · 2 ATT',
    positions: [
      { id:'gk', label:'GK', x:50, y:92 },
      { id:'lb', label:'LB', x:15, y:75 }, { id:'cb1',label:'CB',x:37,y:78 },
      { id:'cb2',label:'CB', x:63, y:78 }, { id:'rb', label:'RB',x:85,y:75 },
      { id:'cdm',label:'CDM',x:50, y:65 },
      { id:'cm1',label:'CM', x:28, y:48 }, { id:'cm2',label:'CM',x:72,y:48 },
      { id:'cam',label:'CAM',x:50, y:36 },
      { id:'st1',label:'ST', x:38, y:18 }, { id:'st2',label:'ST',x:62,y:18 },
    ],
    adj: [['gk','cb1'],['gk','cb2'],['cb1','cb2'],['cb1','lb'],['cb2','rb'],['lb','cdm'],['rb','cdm'],['cdm','cm1'],['cdm','cm2'],['cm1','cam'],['cm2','cam'],['cam','st1'],['cam','st2'],['st1','st2']],
  },
  '3-4-3':   { name: '3-4-3', meta: '1 GK · 3 DEF · 4 MID · 3 ATT',
    positions: [
      { id:'gk',  label:'GK',  x:50, y:92 },
      { id:'cb1', label:'CB',  x:25, y:78 }, { id:'cb2',label:'CB', x:50, y:80 }, { id:'cb3',label:'CB', x:75, y:78 },
      { id:'lm',  label:'LM',  x:12, y:55 }, { id:'cm1',label:'CM', x:38, y:58 },
      { id:'cm2', label:'CM',  x:62, y:58 }, { id:'rm', label:'RM', x:88, y:55 },
      { id:'lw',  label:'LW',  x:20, y:22 }, { id:'st', label:'ST', x:50, y:18 }, { id:'rw', label:'RW', x:80, y:22 },
    ],
    adj: [['gk','cb2'],['cb1','cb2'],['cb2','cb3'],['cb1','lm'],['cb3','rm'],['lm','cm1'],['rm','cm2'],['cm1','cm2'],['lm','lw'],['rm','rw'],['cm1','lw'],['cm2','rw'],['lw','st'],['st','rw'],['cm1','st'],['cm2','st']],
  },
};

// Classify a link between two picks:
//   'club'   — same club (strongest)
//   'duo'    — same league AND same nation (strong)
//   'league' — same league only
//   'nation' — same nation only
//   null     — no link
function linkType(a, b) {
  if (!a || !b) return null;
  if (a.club_team_id && a.club_team_id === b.club_team_id) return 'club';
  const sameLeague = a.league_id && a.league_id === b.league_id;
  const sameNation = a.nationality_id && a.nationality_id === b.nationality_id;
  if (sameLeague && sameNation) return 'duo';
  if (sameLeague) return 'league';
  if (sameNation) return 'nation';
  return null;
}

const LINK_COLORS = {
  club:   '#00ac0b',
  duo:    '#00ac0b',     // same green as club — "stronger chem" visual
  league: '#EFEF00',
  nation: '#EFEF00',
  none:   'rgba(255,255,255,0.18)',
};

// ────── Landing ──────
function DraftLanding({ onStart, onBack, tokens, cost }) {
  const T = window.T;
  const canAfford = tokens === null || tokens >= cost;
  return (
    <Content>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'12px 0 6px'}}>
        <button onClick={onBack} style={{background:'transparent',border:'none',color:T.text,fontSize:22,cursor:'pointer'}}>‹</button>
        <TokenPill amount={tokens ?? '—'}/>
      </div>
      <div style={{textAlign:'center', marginBottom:24}}>
        <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:30, letterSpacing:'0.04em', color:T.text, display:'inline-flex',alignItems:'center',gap:8}}>
          DRAFT <span style={{color:T.gold400,fontSize:22}}>⇄</span>
        </div>
        <div style={{fontSize:14, color:T.textSec, marginTop:2, fontWeight:500}}>Ultimate Legends</div>
      </div>
      <div style={{
        position:'relative', margin:'8px auto 0', width:230, height:300, borderRadius:22,
        background:'linear-gradient(160deg, #E8B820 0%, #C99A10 45%, #8F6D0C 100%)',
        boxShadow:'0 30px 60px rgba(232,184,32,0.25), inset 0 2px 0 rgba(255,255,255,0.4), inset 0 -2px 0 rgba(0,0,0,0.25)',
        display:'flex', alignItems:'center', justifyContent:'center',
      }}>
        <div style={{position:'absolute', inset:14, borderRadius:16, background:'linear-gradient(135deg, rgba(255,255,255,0.25), transparent 55%)', pointerEvents:'none'}}/>
        <div style={{textAlign:'center', color:'#1A1200', fontFamily:'Bakbak One, sans-serif'}}>
          <div style={{fontSize:60, lineHeight:1}}>?</div>
          <div style={{fontSize:12, letterSpacing:'0.2em', marginTop:10, fontWeight:400}}>BUILD YOUR SQUAD</div>
        </div>
      </div>
      <button onClick={canAfford ? onStart : undefined} style={{
        display:'flex', alignItems:'center', gap:8,
        margin:'22px auto 0', padding:'16px 40px', borderRadius:14,
        background: canAfford ? 'linear-gradient(180deg, #F5C842, #C99A10)' : T.card,
        color: canAfford ? '#1A1200' : T.textMute,
        border: canAfford ? 'none' : `1px solid ${T.border}`,
        cursor: canAfford ? 'pointer' : 'not-allowed',
        fontFamily:'Bakbak One, sans-serif', fontSize:20, letterSpacing:'0.06em',
        boxShadow: canAfford ? '0 10px 24px rgba(232,184,32,0.35)' : 'none',
      }}>
        {canAfford ? 'START DRAFT' : 'NOT ENOUGH TOKENS'}
        {canAfford && (
          <span style={{fontSize:13, fontFamily:'DM Sans', color:'rgba(26,18,0,0.6)', letterSpacing:'0.05em'}}>⬡{cost}</span>
        )}
      </button>
      <div style={{display:'flex', justifyContent:'center', gap:30, marginTop:40}}>
        {[{icon:'🏆', title:'FIFA 15–24', sub:'Random Year'},{icon:'👥', title:'11 Players', sub:'Build Squad'},{icon:'⚡', title:'Chemistry', sub:'Star Links'}].map((c,i)=>(
          <div key={i} style={{textAlign:'center'}}>
            <div style={{width:42, height:42, borderRadius:'50%', background:'rgba(232,184,32,0.12)', border:`1px solid ${T.gold600}`, display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 8px', color:T.gold400, fontSize:16}}>{c.icon}</div>
            <div style={{fontSize:11, fontWeight:700, color:T.text}}>{c.title}</div>
            <div style={{fontSize:11, color:T.textMute, fontFamily:'DM Sans', fontWeight:500, marginTop:3}}>{c.sub}</div>
          </div>
        ))}
      </div>
    </Content>
  );
}

// ────── Era reveal with slot-machine cycling ──────
function DraftEra({ year, onNext }) {
  const T = window.T;
  const [phase, setPhase] = React.useState('spinning');
  const [displayYear, setDisplayYear] = React.useState(2015);

  React.useEffect(() => {
    let mounted = true;
    let tick = 0;
    const totalTicks = 28;
    const minYear = 2015, maxYear = 2024;

    const spin = () => {
      if (!mounted) return;
      tick += 1;
      const progress = tick / totalTicks;
      const eased = 1 - Math.pow(1 - progress, 3);
      const delay = 45 + eased * 215;

      if (tick < totalTicks) {
        let next;
        do {
          next = minYear + Math.floor(Math.random() * (maxYear - minYear + 1));
        } while (next === displayYear);
        setDisplayYear(next);
        setTimeout(spin, delay);
      } else {
        setDisplayYear(year);
        setTimeout(() => { if (mounted) setPhase('settled'); }, 280);
        setTimeout(() => { if (mounted) setPhase('revealed'); }, 750);
      }
    };
    const first = setTimeout(spin, 200);
    return () => { mounted = false; clearTimeout(first); };
  }, []);

  const spinning = phase === 'spinning';
  const settled = phase === 'settled' || phase === 'revealed';
  const revealed = phase === 'revealed';

  return (
    <Content>
      <div style={{textAlign:'center', padding:'20px 0 8px'}}>
        <div style={{display:'inline-flex', alignItems:'center', gap:10}}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={T.gold400} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <rect x="3" y="4" width="18" height="18" rx="2"/>
            <path d="M16 2v4M8 2v4M3 10h18"/>
          </svg>
          <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:22, letterSpacing:'0.08em', color:T.text}}>YOUR ERA</div>
        </div>
        <div style={{fontSize:13, color:T.textSec, marginTop:6}}>Build your squad from this year</div>
      </div>

      <div style={{position:'relative', height: 460, display:'flex', alignItems:'center', justifyContent:'center'}}>
        <div style={{
          position:'absolute', inset:0,
          display:'flex', alignItems:'center', justifyContent:'center',
          fontFamily:'Bakbak One, sans-serif', fontSize: 170, letterSpacing:'0.02em',
          color: spinning ? 'rgba(136,150,176,0.35)' : 'rgba(136,150,176,0.18)',
          transition: 'color 600ms ease, transform 600ms ease, opacity 600ms ease',
          transform: settled ? 'scale(1.02)' : 'scale(1)',
          userSelect:'none',
          textShadow: spinning ? '0 -3px 12px rgba(136,150,176,0.2), 0 3px 12px rgba(136,150,176,0.2)' : 'none',
          lineHeight: 1, zIndex: 1,
        }}>{displayYear}</div>

        <div style={{
          position:'relative', zIndex: 2,
          width: revealed ? 260 : 0, height: revealed ? 260 : 0,
          borderRadius:'50%',
          background:'radial-gradient(circle at 30% 30%, #D8A718, #8F6D0C)',
          opacity: revealed ? 0.95 : 0,
          transform: revealed ? 'scale(1)' : 'scale(0.3)',
          transition:'all 650ms cubic-bezier(0.2,0.9,0.3,1)',
          display:'flex', alignItems:'center', justifyContent:'center',
          boxShadow: revealed ? '0 0 80px rgba(232,184,32,0.45), 0 0 30px rgba(232,184,32,0.3)' : 'none',
        }}>
          <div style={{
            background:'linear-gradient(180deg, #F5C842, #C99A10)',
            padding:'18px 36px', borderRadius:16,
            boxShadow:'inset 0 2px 0 rgba(255,255,255,0.4), inset 0 -2px 0 rgba(0,0,0,0.2), 0 10px 30px rgba(0,0,0,0.3)',
            opacity: revealed ? 1 : 0,
            transform: revealed ? 'scale(1)' : 'scale(0.6)',
            transition: 'all 450ms cubic-bezier(0.2,0.9,0.3,1) 200ms',
          }}>
            <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:56, color:'#1A1200', letterSpacing:'0.04em', lineHeight:1}}>{year}</div>
          </div>
        </div>
      </div>

      <div style={{
        textAlign:'center', color:T.textSec, fontSize:14, marginTop:-20,
        opacity: revealed ? 1 : 0,
        transform: revealed ? 'translateY(0)' : 'translateY(12px)',
        transition: 'all 500ms cubic-bezier(0.2,0.9,0.3,1) 350ms',
      }}>
        Draft legends from <span style={{color: T.gold400, fontWeight:700}}>{year}</span>
      </div>

      <div style={{position:'absolute', left:20, right:20, bottom:38}}>
        <button onClick={onNext} disabled={!revealed} style={{
          width:'100%', padding:'16px', borderRadius:14,
          background: revealed ? 'linear-gradient(180deg, #F5C842, #C99A10)' : T.card,
          color: revealed ? '#1A1200' : T.textMute,
          border: revealed ? 'none' : `1px solid ${T.border}`,
          cursor: revealed ? 'pointer' : 'default',
          fontFamily:'Bakbak One, sans-serif', fontSize:16, letterSpacing:'0.06em',
          display:'inline-flex', alignItems:'center', justifyContent:'center', gap:8,
          boxShadow: revealed ? '0 10px 24px rgba(232,184,32,0.3)' : 'none',
          opacity: revealed ? 1 : 0.6,
          transform: revealed ? 'translateY(0)' : 'translateY(14px)',
          transition: 'all 500ms cubic-bezier(0.2,0.9,0.3,1) 450ms',
        }}>CHOOSE FORMATION <span>›</span></button>
      </div>
    </Content>
  );
}

function MiniPitch({ positions }) {
  return (
    <div style={{position:'relative', height:120, borderRadius:8, background:'linear-gradient(180deg, #2D8C4E, #256b3d)', border:'1px solid rgba(255,255,255,0.08)', overflow:'hidden'}}>
      <div style={{position:'absolute', inset:4, border:'1px solid rgba(255,255,255,0.18)', borderRadius:4}}/>
      <div style={{position:'absolute', top:'50%', left:0, right:0, height:1, background:'rgba(255,255,255,0.18)'}}/>
      <div style={{position:'absolute', left:'50%', top:'50%', width:30, height:30, transform:'translate(-50%,-50%)', border:'1px solid rgba(255,255,255,0.18)', borderRadius:'50%'}}/>
      {positions.map(p=>(<div key={p.id} style={{position:'absolute', left:`${p.x}%`, top:`${p.y}%`, width:10, height:10, borderRadius:'50%', background:'rgba(255,255,255,0.85)', transform:'translate(-50%,-50%)'}}/>))}
    </div>
  );
}

function DraftFormation({ year, onPick, onBack }) {
  const T = window.T;
  const [selected, setSelected] = React.useState(null);
  const keys = Object.keys(FORMATIONS);
  return (
    <Content>
      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'10px 0'}}>
        <button onClick={onBack} style={{background:'transparent',border:'none',color:T.text,fontSize:22,cursor:'pointer'}}>‹</button>
        <TokenPill/>
      </div>
      <div style={{textAlign:'center', marginBottom:14}}>
        <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:20, letterSpacing:'0.06em', color:T.text}}>CHOOSE FORMATION</div>
        <div style={{display:'inline-block', marginTop:10, padding:'3px 12px', borderRadius:100, background:'rgba(232,184,32,0.12)', border:`1px solid ${T.gold600}`, color:T.gold400, fontSize:11, fontWeight:700}}>{year} Draft</div>
      </div>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
        {keys.map(k=>{
          const f = FORMATIONS[k];
          const isSel = selected === k;
          return (
            <button key={k} onClick={()=>setSelected(k)} style={{background: isSel ? 'rgba(232,184,32,0.1)' : T.card, border:`1px solid ${isSel ? T.gold500 : T.border}`, borderRadius:14, padding:12, cursor:'pointer', textAlign:'left'}}>
              <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:16, color:T.text, letterSpacing:'0.04em', marginBottom:8, textAlign:'center'}}>{f.name}</div>
              <MiniPitch positions={f.positions}/>
              <div style={{marginTop:8, display:'flex', flexWrap:'wrap', gap:4, justifyContent:'center'}}>
                {f.meta.split(' · ').map((m,i)=>(<span key={i} style={{fontSize:9, fontFamily:'DM Sans', letterSpacing:'0.06em', background:T.navy700, color:T.textSec, padding:'3px 6px', borderRadius:4}}>{m}</span>))}
              </div>
            </button>
          );
        })}
      </div>
      <div style={{height:90}}/>
      <div style={{position:'absolute', left:20, right:20, bottom:38}}>
        <button disabled={!selected} onClick={()=>selected && onPick(selected)} style={{
          width:'100%', padding:'16px', borderRadius:14,
          background: selected ? 'linear-gradient(180deg, #F5C842, #C99A10)' : T.card,
          color: selected ? '#1A1200' : T.textMute, border: selected ? 'none' : `1px solid ${T.border}`,
          cursor: selected ? 'pointer' : 'default', fontFamily:'Bakbak One, sans-serif', fontSize:16, letterSpacing:'0.06em',
        }}>START DRAFTING <span>›</span></button>
      </div>
    </Content>
  );
}

// Chemistry line overlay
function ChemistryLines({ formation, picks, pitchWidth, pitchHeight }) {
  const posById = {};
  formation.positions.forEach(p => { posById[p.id] = p; });
  return (
    <svg style={{position:'absolute', inset:0, width:'100%', height:'100%', pointerEvents:'none', zIndex:1}}>
      {formation.adj.map(([aId, bId], i) => {
        const posA = posById[aId], posB = posById[bId];
        if (!posA || !posB) return null;
        const x1 = (posA.x / 100) * pitchWidth;
        const y1 = (posA.y / 100) * pitchHeight;
        const x2 = (posB.x / 100) * pitchWidth;
        const y2 = (posB.y / 100) * pitchHeight;
        const type = linkType(picks[aId], picks[bId]);
        const color = type ? LINK_COLORS[type] : LINK_COLORS.none;
        const width = type ? 2.5 : 1.5;
        const opacity = type ? 0.85 : 0.4;
        return (
          <line key={i} x1={x1} y1={y1} x2={x2} y2={y2}
            stroke={color} strokeWidth={width} opacity={opacity} strokeLinecap="round"
            style={{transition:'stroke 300ms, opacity 300ms, stroke-width 300ms'}}/>
        );
      })}
    </svg>
  );
}

function PitchView({ year, formationKey, picks, activePos, onPosClick, onSwap, onBack, onFinish }) {
  const T = window.T;
  const f = FORMATIONS[formationKey];
  const filled = Object.keys(picks).length;
  const PITCH_W = 353, PITCH_H = 460;

  const pitchRef = React.useRef(null);
  const [drag, setDrag] = React.useState(null);
  // drag = { fromId, startX, startY, x, y, longPressTimer, moved, suppressTap }
  const dragRef = React.useRef(null);
  const [hoverSlotId, setHoverSlotId] = React.useState(null);
  // swapPair = { aId, bId } — triggers the scale-down/up animation for both
  const [swapPair, setSwapPair] = React.useState(null);

  const LONG_PRESS_MS = 220;
  const MOVE_TOLERANCE = 6; // pixels before long-press is cancelled

  const slotById = React.useMemo(() => {
    const map = {};
    f.positions.forEach(p => { map[p.id] = p; });
    return map;
  }, [f]);

  const getPitchPoint = (clientX, clientY) => {
    const rect = pitchRef.current?.getBoundingClientRect();
    if (!rect) return { x: clientX, y: clientY };
    return { x: clientX - rect.left, y: clientY - rect.top, rect };
  };

  // Find which filled slot the pointer is currently over
  const findSlotAtPoint = (clientX, clientY) => {
    const rect = pitchRef.current?.getBoundingClientRect();
    if (!rect) return null;
    const localX = clientX - rect.left;
    const localY = clientY - rect.top;
    let closest = null;
    let closestDist = Infinity;
    for (const slot of f.positions) {
      if (!picks[slot.id]) continue;
      const sx = (slot.x / 100) * rect.width;
      const sy = (slot.y / 100) * rect.height;
      const dx = localX - sx;
      const dy = localY - sy;
      const dist = Math.sqrt(dx*dx + dy*dy);
      if (dist < 40 && dist < closestDist) {
        closest = slot;
        closestDist = dist;
      }
    }
    return closest;
  };

  const clientXY = (e) => {
    if (e.touches && e.touches[0]) return { x: e.touches[0].clientX, y: e.touches[0].clientY };
    if (e.changedTouches && e.changedTouches[0]) return { x: e.changedTouches[0].clientX, y: e.changedTouches[0].clientY };
    return { x: e.clientX, y: e.clientY };
  };

  const onPointerDown = (e, posId) => {
    // Only filled slots can start a drag
    if (!picks[posId]) return;
    const { x, y } = clientXY(e);
    const pt = getPitchPoint(x, y);

    const state = {
      fromId: posId,
      startX: x, startY: y,
      x: pt.x, y: pt.y,
      moved: false,
      suppressTap: false,
      longPressTimer: null,
      active: false,
    };
    dragRef.current = state;

    state.longPressTimer = setTimeout(() => {
      if (dragRef.current === state) {
        state.active = true;
        state.suppressTap = true;
        if (navigator.vibrate) navigator.vibrate(30);
        setDrag({ ...state });
      }
    }, LONG_PRESS_MS);
  };

  const onPointerMove = (e) => {
    const state = dragRef.current;
    if (!state) return;
    const { x, y } = clientXY(e);
    const dx = x - state.startX;
    const dy = y - state.startY;

    // Cancel long-press if user moved before it triggered
    if (!state.active && Math.sqrt(dx*dx + dy*dy) > MOVE_TOLERANCE) {
      clearTimeout(state.longPressTimer);
      dragRef.current = null;
      return;
    }

    if (state.active) {
      if (e.cancelable) e.preventDefault();
      const pt = getPitchPoint(x, y);
      state.x = pt.x;
      state.y = pt.y;
      state.moved = true;
      setDrag({ ...state });
      const hovered = findSlotAtPoint(x, y);
      setHoverSlotId(hovered && hovered.id !== state.fromId ? hovered.id : null);
    }
  };

  const onPointerUp = (e) => {
    const state = dragRef.current;
    if (!state) return;
    clearTimeout(state.longPressTimer);

    if (state.active && state.moved) {
      const { x, y } = clientXY(e);
      const target = findSlotAtPoint(x, y);
      if (target && target.id !== state.fromId && picks[target.id]) {
        // Trigger the swap animation
        setSwapPair({ aId: state.fromId, bId: target.id });
        // After the scale-down, do the swap, then scale back up
        setTimeout(() => {
          onSwap(state.fromId, target.id);
        }, 180);
        setTimeout(() => {
          setSwapPair(null);
        }, 420);
      }
    }

    dragRef.current = null;
    setDrag(null);
    setHoverSlotId(null);
  };

  const onPointerCancel = () => {
    const state = dragRef.current;
    if (state) clearTimeout(state.longPressTimer);
    dragRef.current = null;
    setDrag(null);
    setHoverSlotId(null);
  };

  // Prevent browser scroll while dragging
  React.useEffect(() => {
    if (drag?.active) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = prev; };
    }
  }, [drag?.active]);

  return (
    <Content>
      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'8px 0 4px'}}>
        <button onClick={onBack} style={{background:'transparent',border:'none',color:T.text,fontSize:22,cursor:'pointer'}}>‹</button>
        <div style={{display:'flex', gap:8, alignItems:'center'}}>
          {filled === 11 && (
            <button onClick={onFinish} style={{background:T.gold500, border:'none', borderRadius:100, padding:'6px 14px', color:T.navy950, fontWeight:700, fontSize:12, cursor:'pointer'}}>Finish</button>
          )}
        </div>
      </div>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:6}}>
        <div>
          <div style={{fontSize:12, color:T.textSec}}>{year} Draft</div>
          <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:20, color:T.text, letterSpacing:'0.06em'}}>{f.name}</div>
        </div>
        <div style={{fontSize:12, color:T.textSec, fontFamily:'DM Sans', fontWeight:500, marginTop:6}}>{filled} of 11 filled</div>
      </div>
      <div style={{height:4, background:T.border, borderRadius:100, overflow:'hidden', marginBottom:14}}>
        <div style={{width:`${(filled/11)*100}%`, height:'100%', background:T.gold400, transition:'width 300ms'}}/>
      </div>
      <div
        ref={pitchRef}
        onTouchMove={onPointerMove}
        onTouchEnd={onPointerUp}
        onTouchCancel={onPointerCancel}
        onMouseMove={onPointerMove}
        onMouseUp={onPointerUp}
        onMouseLeave={onPointerCancel}
        style={{
          position:'relative', height:PITCH_H, borderRadius:16,
          background:'linear-gradient(180deg, #2D8C4E, #1F6638)',
          border:'1px solid rgba(255,255,255,0.08)', overflow:'hidden',
          touchAction: drag?.active ? 'none' : 'auto',
        }}>
        <div style={{position:'absolute', inset:10, border:'2px solid rgba(255,255,255,0.35)', borderRadius:6}}/>
        <div style={{position:'absolute', top:'50%', left:10, right:10, height:2, background:'rgba(255,255,255,0.35)'}}/>
        <div style={{position:'absolute', left:'50%', top:'50%', width:80, height:80, transform:'translate(-50%,-50%)', border:'2px solid rgba(255,255,255,0.35)', borderRadius:'50%'}}/>
        <div style={{position:'absolute', left:'25%', right:'25%', top:10, height:60, border:'2px solid rgba(255,255,255,0.35)', borderTop:'none'}}/>
        <div style={{position:'absolute', left:'25%', right:'25%', bottom:10, height:60, border:'2px solid rgba(255,255,255,0.35)', borderBottom:'none'}}/>

        <ChemistryLines formation={f} picks={picks} pitchWidth={PITCH_W} pitchHeight={PITCH_H}/>

        {f.positions.map(p=>{
          const pick = picks[p.id];
          const active = activePos === p.id;
          const isDragging = drag?.active && drag?.fromId === p.id;
          const isHoverTarget = hoverSlotId === p.id;
          const isInSwap = swapPair && (swapPair.aId === p.id || swapPair.bId === p.id);
          const label = pick ? (pick.short_name || '').split(' ').slice(-1)[0].slice(0,6).toUpperCase() : p.label;

          let bg, border, boxShadow, color;
          if (pick) {
            bg = 'linear-gradient(180deg, #F5C842, #C99A10)';
            color = '#1A1200';
            if (isHoverTarget) {
              border = '2px solid #fff';
              boxShadow = '0 0 0 3px rgba(245,200,66,0.5), 0 0 24px rgba(245,200,66,0.8)';
            } else {
              border = '2px solid rgba(255,255,255,0.5)';
              boxShadow = active ? '0 0 24px rgba(245,200,66,0.6)' : 'none';
            }
          } else {
            bg = active ? T.gold400 : 'rgba(255,255,255,0.18)';
            color = 'rgba(255,255,255,0.95)';
            border = '2px solid rgba(255,255,255,0.4)';
            boxShadow = active ? '0 0 24px rgba(245,200,66,0.6)' : 'none';
          }

          // Swap animation: scale down briefly, then back up after swap happens
          let scaleTransform = 'translate(-50%,-50%)';
          if (isInSwap) {
            scaleTransform = 'translate(-50%,-50%) scale(0.2)';
          } else if (isHoverTarget) {
            scaleTransform = 'translate(-50%,-50%) scale(1.12)';
          }

          return (
            <button
              key={p.id}
              onClick={() => {
                // Suppress tap if we were dragging
                if (dragRef.current?.suppressTap) return;
                // Filled slots are locked — can only swap via drag
                if (picks[p.id]) return;
                onPosClick(p);
              }}
              onTouchStart={(e) => onPointerDown(e, p.id)}
              onMouseDown={(e) => onPointerDown(e, p.id)}
              style={{
                position:'absolute', left:`${p.x}%`, top:`${p.y}%`,
                transform: scaleTransform,
                width:48, height:48, borderRadius:'50%',
                background: bg, border, boxShadow, color,
                fontSize: 9, fontWeight: 700, fontFamily:'DM Sans',
                cursor: pick ? 'grab' : 'pointer',
                padding:0,
                display:'flex', alignItems:'center', justifyContent:'center',
                zIndex: isDragging ? 20 : 2,
                visibility: isDragging ? 'hidden' : 'visible',
                transition: isInSwap
                  ? 'transform 180ms cubic-bezier(0.4, 0, 0.6, 1), box-shadow 200ms, border 200ms'
                  : 'transform 280ms cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 200ms, border 200ms',
                userSelect:'none', WebkitUserSelect:'none',
                touchAction: 'none',
              }}>{label}</button>
          );
        })}

        {/* Ghost card that follows the drag */}
        {drag?.active && (() => {
          const pick = picks[drag.fromId];
          if (!pick) return null;
          const label = (pick.short_name || '').split(' ').slice(-1)[0].slice(0,6).toUpperCase();
          return (
            <div style={{
              position:'absolute',
              left: drag.x, top: drag.y,
              transform: 'translate(-50%,-50%) scale(1.15)',
              width: 48, height: 48, borderRadius: '50%',
              background: 'linear-gradient(180deg, #F5C842, #C99A10)',
              color: '#1A1200',
              border: '2px solid #fff',
              boxShadow: '0 8px 24px rgba(0,0,0,0.4), 0 0 32px rgba(245,200,66,0.6)',
              fontSize: 9, fontWeight: 700, fontFamily: 'DM Sans',
              display: 'flex', alignItems:'center', justifyContent:'center',
              pointerEvents: 'none', zIndex: 25,
              userSelect: 'none', WebkitUserSelect: 'none',
            }}>{label}</div>
          );
        })()}
      </div>

      <div style={{marginTop:14, padding:'12px 16px', borderRadius:14,
        background:'rgba(232,184,32,0.06)',
        border:`1px solid ${T.gold600}`, display:'flex', alignItems:'center', gap:10}}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill={T.gold400}>
          <path d="M13 2L4 14h6l-1 8 9-12h-6l1-8z"/>
        </svg>
        <div style={{fontSize:12.5, color:T.text}}>
          Tap an empty slot to pick. Long-press a player to drag them to another spot.
        </div>
      </div>

      {filled >= 2 && (
        <div style={{marginTop:10, padding:'10px 14px', borderRadius:12, background:T.card, border:`1px solid ${T.border}`, display:'flex', justifyContent:'space-around', alignItems:'center'}}>
          <LegendItem color={LINK_COLORS.club} label="Club"/>
          <LegendItem color={LINK_COLORS.league} label="League"/>
          <LegendItem color={LINK_COLORS.nation} label="Nation"/>
        </div>
      )}
    </Content>
  );
}

function LegendItem({ color, label }) {
  const T = window.T;
  return (
    <div style={{display:'flex', alignItems:'center', gap:6}}>
      <div style={{width:14, height:3, borderRadius:2, background:color}}/>
      <span style={{fontSize:10.5, color:T.textSec, fontFamily:'DM Sans', letterSpacing:'0.08em'}}>{label}</span>
    </div>
  );
}

function PlayerSheet({ posLabel, players, loading, error, onPick, onClose }) {
  const T = window.T;
  return (
    <div style={{position:'absolute', inset:0, zIndex:50}}>
      <div onClick={onClose} style={{position:'absolute', inset:0, background:'rgba(0,0,0,0.55)'}}/>
      <div style={{position:'absolute', left:0, right:0, bottom:0, background:T.navy900, borderTopLeftRadius:24, borderTopRightRadius:24, padding:'14px 20px 28px', borderTop:`1px solid ${T.border}`}}>
        <div style={{width:40, height:4, background:T.border, borderRadius:100, margin:'0 auto 14px'}}/>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14}}>
          <div>
            <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:22, color:T.text, letterSpacing:'0.04em'}}>Select {posLabel}</div>
            <div style={{fontSize:12, color:T.textSec, marginTop:2}}>{loading ? 'Loading players…' : error ? 'Error loading players' : 'Choose one of these players'}</div>
          </div>
          <button onClick={onClose} style={{width:34, height:34, borderRadius:'50%', background:T.card, border:'none', color:T.text, cursor:'pointer', fontSize:16}}>✕</button>
        </div>
        {loading && <div style={{padding:'40px 0', textAlign:'center', color:T.textSec}}>Loading…</div>}
        {error && <div style={{padding:'40px 0', textAlign:'center', color:T.red, fontSize:12}}>{String(error)}</div>}
        {!loading && !error && (
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8}}>
            {players.map((p,i)=>{
              const primaryPos = (p.player_positions||'').split(',')[0].trim().toUpperCase();
              const lastName = (p.short_name || p.long_name || '').split(' ').slice(-1)[0];
              return (
                <button key={i} onClick={()=>onPick(p)} style={{
                  background:'linear-gradient(160deg, #E8B820, #C99A10 70%, #8F6D0C)', borderRadius:12, padding:10, border:'none', cursor:'pointer',
                  textAlign:'left', position:'relative', color:'#1A1200', boxShadow:'inset 0 1px 0 rgba(255,255,255,0.3)',
                  minWidth: 0, // critical: allow flex/grid item to shrink below content size
                  overflow:'hidden',
                }}>
                  <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:24, letterSpacing:'0.02em', lineHeight:1}}>{p.overall}</div>
                  <div style={{fontSize:10, fontWeight:700, marginTop:1}}>{primaryPos}</div>
                  <div style={{width:44, height:44, borderRadius:'50%', background:'rgba(255,255,255,0.3)', margin:'10px auto 8px', display:'flex', alignItems:'center', justifyContent:'center', fontFamily:'Bakbak One, sans-serif', fontSize:22}}>{lastName[0] || '?'}</div>
                  <div style={{fontSize:10, fontWeight:800, textAlign:'center', textTransform:'uppercase', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis', minWidth: 0}}>{p.short_name}</div>
                  <div style={{fontSize:9, textAlign:'center', opacity:0.85, marginTop:2, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis', minWidth: 0}}>{p.club_name || '—'}</div>
                  <div style={{display:'block', marginTop:6, padding:'2px 6px', borderRadius:4, background:'rgba(0,0,0,0.18)', fontSize:8.5, fontWeight:700, textAlign:'center', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis', minWidth: 0}}>{p.nationality_name}</div>
                </button>
              );
            })}
          </div>
        )}
        <div style={{marginTop:14, padding:'10px 14px', borderRadius:12, background:'rgba(232,184,32,0.06)', border:`1px solid ${T.border}`, display:'flex', alignItems:'center', gap:10}}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill={T.gold400}><path d="M13 2L4 14h6l-1 8 9-12h-6l1-8z"/></svg>
          <div style={{fontSize:11.5, color:T.textSec}}>Match leagues, nations, or teams for better chemistry!</div>
        </div>
      </div>
    </div>
  );
}

function computeChemistry(formationKey, picks) {
  const f = FORMATIONS[formationKey];
  if (!f || !f.adj) return 0;
  let raw = 0;
  f.adj.forEach(([a,b])=>{
    const type = linkType(picks[a], picks[b]);
    if (type === 'club')        raw += 3;
    else if (type === 'duo')    raw += 3;   // league + nation = as strong as club
    else if (type === 'league') raw += 2;
    else if (type === 'nation') raw += 1;
  });
  const max = f.adj.length * 3;
  return Math.round((raw / max) * 100);
}

function DraftResult({ year, formationKey, picks, onDone }) {
  const T = window.T;
  const arr = Object.values(picks);
  const avg = Math.round(arr.reduce((a,b)=>a+(b.overall||0),0) / (arr.length||1));
  const chem = computeChemistry(formationKey, picks);
  const combined = avg + chem;
  return (
    <Content>
      <div style={{textAlign:'center', padding:'40px 0 16px'}}>
        <div style={{fontSize:11, color:T.textMute, fontFamily:'DM Sans', letterSpacing:'0.2em'}}>{year} DRAFT COMPLETE</div>
        <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:30, color:T.text, letterSpacing:'0.04em', marginTop:8}}>FINAL SQUAD</div>
      </div>

      {/* Combined score — headline */}
      <div style={{background:T.card, borderRadius:16, padding:20, textAlign:'center', marginBottom:12}}>
        <div style={{fontSize:10, fontFamily:'DM Sans', letterSpacing:'0.18em', color:T.textMute}}>SCORE</div>
        <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:72, color:T.gold400, lineHeight:1, marginTop:4, letterSpacing:'0.02em'}}>
          {combined}
          <span style={{fontSize:22, color:T.textMute, letterSpacing:0}}> / 199</span>
        </div>
      </div>

      {/* Rating + Chemistry — breakdown */}
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
        <div style={{background:T.card, borderRadius:16, padding:20, textAlign:'center'}}>
          <div style={{fontSize:10, fontFamily:'DM Sans', letterSpacing:'0.18em', color:T.textMute}}>RATING</div>
          <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:44, color:T.gold400, lineHeight:1, marginTop:6}}>{avg}</div>
        </div>
        <div style={{background:T.card, borderRadius:16, padding:20, textAlign:'center'}}>
          <div style={{fontSize:10, fontFamily:'DM Sans', letterSpacing:'0.18em', color:T.textMute}}>CHEMISTRY</div>
          <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:44, color:T.greenLt, lineHeight:1, marginTop:6}}>{chem}</div>
        </div>
      </div>

      <div style={{marginTop:18, background:T.card, borderRadius:16, padding:16}}>
        <div style={{fontSize:11, fontFamily:'DM Sans', letterSpacing:'0.15em', color:T.textMute, marginBottom:10}}>YOUR XI</div>
        {Object.entries(picks).map(([k,p])=>(
          <div key={k} style={{display:'flex', alignItems:'center', gap:10, padding:'6px 0', borderBottom:`1px solid ${T.border}`}}>
            <div style={{width:42, fontFamily:'DM Sans', fontSize:10, color:T.textSec}}>{p._posLabel || (p.player_positions||'').split(',')[0]}</div>
            <div style={{flex:1, fontSize:13, color:T.text, fontWeight:600, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{p.short_name}</div>
            <div style={{fontSize:10, color:T.textSec, maxWidth:80, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{p.club_name}</div>
            <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:16, color:T.gold400, width:30, textAlign:'right'}}>{p.overall}</div>
          </div>
        ))}
      </div>
      <div style={{position:'absolute', left:20, right:20, bottom:38}}>
        <button onClick={onDone} style={{width:'100%', padding:'16px', borderRadius:14, background:'linear-gradient(180deg, #F5C842, #C99A10)', color:'#1A1200', border:'none', cursor:'pointer', fontFamily:'Bakbak One, sans-serif', fontSize:16, letterSpacing:'0.06em'}}>SUBMIT TO LEADERBOARD</button>
      </div>
    </Content>
  );
}

function DraftFlow({ onExit }) {
  const [stage, setStage] = React.useState('landing');
  const [version, setVersion] = React.useState(null);
  const [year, setYear] = React.useState(null);
  const [formationKey, setFormationKey] = React.useState(null);
  const [picks, setPicks] = React.useState({});
  const [activePos, setActivePos] = React.useState(null);
  const [sheetPlayers, setSheetPlayers] = React.useState([]);
  const [sheetLoading, setSheetLoading] = React.useState(false);
  const [sheetError, setSheetError] = React.useState(null);
  const [lowerTierSlots, setLowerTierSlots] = React.useState(new Set());
  const [tokens, setTokens] = React.useState(null);
  const [tokenError, setTokenError] = React.useState(false);
  const sessionIdRef = React.useRef(null);
  const GAME_COST = 2;

  React.useEffect(() => {
    let mounted = true;
    window.isSignedIn().then(signedIn => {
      if (!signedIn || !mounted) return;
      window.fetchTokens()
        .then(t => { if (mounted) setTokens(t?.balance ?? 0); })
        .catch(() => {});
    });
    return () => { mounted = false; };
  }, []);

  const start = async () => {
    const signedIn = await window.isSignedIn();
    if (signedIn) {
      // Check + deduct tokens before starting
      try {
        const newBalance = await window.spendTokens(GAME_COST);
        setTokens(newBalance);
      } catch (e) {
        if (e.message === 'insufficient_tokens') { setTokenError(true); return; }
        console.error('Token deduct failed:', e);
        return;
      }
    }
    const v = 15 + Math.floor(Math.random() * 10);
    setVersion(v);
    setYear(2000 + v);
    setStage('era');
    trackPage('/play/draft/era', 'Draft Era');
    if (signedIn) {
      try {
        const sess = await window.createGameSession('draft', { fifa_version: v, year: 2000 + v });
        sessionIdRef.current = sess.id;
      } catch (e) {
        console.error('Failed to create draft session:', e);
      }
    }
  };

  const pickFormation = (k) => {
    setFormationKey(k);
    // Pick 2-3 random slots to be lower-tier (overall 80-84 range)
    const allSlots = FORMATIONS[k].positions.map(p => p.id);
    const count = 1 + Math.floor(Math.random() * 2); // 1 or 2
    const shuffled = [...allSlots].sort(() => Math.random() - 0.5);
    setLowerTierSlots(new Set(shuffled.slice(0, count)));
    setStage('pitch');
  };

  const onPosClick = async (p) => {
    setActivePos(p);
    setSheetPlayers([]); setSheetError(null); setSheetLoading(true);
    try {
      const excludeIds = Object.values(picks).map(pl => pl.player_id).filter(Boolean);
      const minTier = lowerTierSlots.has(p.id) ? 80 : 85;
      const rows = await window.fetchPlayersFor(version, p.label, excludeIds, minTier);
      setSheetPlayers(rows);
    } catch (e) {
      setSheetError(e.message || 'Failed to load');
    } finally {
      setSheetLoading(false);
    }
  };

  const onSwap = (fromId, toId) => {
    // Swap the two picks, updating each player's _posLabel to match their new slot
    const formation = FORMATIONS[formationKey];
    const slotFrom = formation.positions.find(pos => pos.id === fromId);
    const slotTo = formation.positions.find(pos => pos.id === toId);
    if (!slotFrom || !slotTo) return;
    setPicks(prev => {
      if (!prev[fromId] || !prev[toId]) return prev;
      const next = { ...prev };
      next[fromId] = { ...prev[toId], _posLabel: slotFrom.label };
      next[toId] = { ...prev[fromId], _posLabel: slotTo.label };
      return next;
    });
  };

  const onPickPlayer = (player) => {
    setPicks(prev => ({ ...prev, [activePos.id]: { ...player, _posLabel: activePos.label } }));
    setActivePos(null);
    setSheetPlayers([]);
  };

  const finishDraft = async () => {
    // Finalize session with results
    const arr = Object.values(picks);
    const avg = arr.length > 0 ? Math.round(arr.reduce((a,b)=>a+(b.overall||0),0) / arr.length) : 0;
    const chem = computeChemistry(formationKey, picks);
    const combined = avg + chem;
    // Capture the draft picks in a slim format for Rank detail view
    const picksSnapshot = Object.entries(picks).map(([slotId, p]) => ({
      slot_id: slotId,
      position: p._posLabel || (p.player_positions || '').split(',')[0],
      short_name: p.short_name,
      long_name: p.long_name,
      overall: p.overall,
      club: p.club_name,
      league: p.league_name,
      nation: p.nationality_name,
    }));
    const id = sessionIdRef.current;
    if (id) {
      try {
        await window.endGameSession(id, {
          fifa_version: version,
          year,
          formation: formationKey,
          average_rating: avg,
          chemistry: chem,
          combined_score: combined,
          picks_count: arr.length,
          picks: picksSnapshot,
        }, true);
      } catch (e) {
        console.error('Failed to end draft session:', e);
      }
    }
    setStage('result');

    // Fire GA4 event for funnel tracking
    if (typeof window.trackEvent === 'function') {
      window.trackEvent('draft_completed', {
        year, formation: formationKey,
        rating: avg, chemistry: chem, combined_score: combined,
        signed_in: !!sessionIdRef.current,
      });
    }

    // Award tokens for performance and check achievements (only if signed in)
    (async () => {
      if (!await window.isSignedIn()) return;
      try {
        const all = await window.fetchMySessions();
        const latest = all[0];
        const tokenBonus = window.DRAFT_GAME_TOKENS ? window.DRAFT_GAME_TOKENS(latest) : 3;
        await window.awardTokens(tokenBonus);
        const newlyUnlocked = await window.checkAchievements(all);
        if (newlyUnlocked.length > 0) {
          window._pendingAchievements = (window._pendingAchievements || []).concat(newlyUnlocked);
        }
      } catch (e) {
        console.error('Post-game awards failed:', e);
      }
    })();
  };

  // Not enough tokens
  if (tokenError) {
    const T = window.T;
    return (
      <Content>
        <div style={{textAlign:'center', padding:'60px 20px'}}>
          <div style={{fontSize:56, marginBottom:16}}>⬡</div>
          <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:26, color:T.text, letterSpacing:'0.04em', marginBottom:8}}>
            NOT ENOUGH TOKENS
          </div>
          <div style={{fontSize:14, color:T.textSec, lineHeight:1.6, marginBottom:32}}>
            You need <span style={{color:T.gold400, fontWeight:700}}>{GAME_COST} tokens</span> to play.<br/>
            Earn more by completing games<br/>and unlocking achievements.
          </div>
          <button onClick={onExit} style={{
            width:'100%', padding:'14px', borderRadius:12,
            background:T.card, border:`1px solid ${T.border}`,
            color:T.text, fontFamily:'DM Sans', fontSize:14, fontWeight:600, cursor:'pointer',
          }}>← Back</button>
        </div>
      </Content>
    );
  }

  if (stage === 'landing')   return <DraftLanding onStart={start} onBack={onExit} tokens={tokens} cost={GAME_COST}/>;
  if (stage === 'era')       return <DraftEra year={year} onNext={()=>setStage('formation')}/>;
  if (stage === 'formation') return <DraftFormation year={year} onBack={()=>setStage('era')} onPick={pickFormation}/>;
  if (stage === 'pitch') {
    return (
      <>
        <PitchView year={year} formationKey={formationKey} picks={picks}
          activePos={activePos?.id}
          onPosClick={onPosClick} onSwap={onSwap}
          onBack={()=>setStage('formation')} onFinish={finishDraft}/>
        {activePos && (
          <PlayerSheet posLabel={activePos.label} players={sheetPlayers}
            loading={sheetLoading} error={sheetError}
            onPick={onPickPlayer} onClose={()=>{setActivePos(null); setSheetPlayers([]);}}/>
        )}
      </>
    );
  }
  if (stage === 'result') return <DraftResult year={year} formationKey={formationKey} picks={picks} onDone={onExit}/>;
  return null;
}

window.DraftFlow = DraftFlow;
