// screens-player.jsx — Individual athlete page: bio, stats, game log, store.
// Reached by tapping a player from the Roster or Stats tabs.

function ScreenPlayer({ player, sport, onBack, onOpenNIL, fireReward }) {
  const p = player || {};
  const [tab, setTab] = React.useState('overview');
  const tabs = ['Overview','Game Log','Bio','Store'];

  // Generate a game log from the player's season
  const games = React.useMemo(() => {
    const seed = (p.id || 'x').split('').reduce((a, c) => a + c.charCodeAt(0), 0);
    const rng = _rngP(seed);
    const opps = ['Texas Tech','Kansas','Baylor','Iowa State','TCU','Cincinnati','Houston','BYU','Arizona','Colorado'];
    return Array.from({ length: 8 }, (_, i) => ({
      id: i, opp: opps[Math.floor(rng()*opps.length)], date: `${['SEP','OCT','NOV'][Math.floor(i/3)]} ${2+i*3}`,
      isHome: rng() > 0.5, won: rng() > 0.4,
      line: (p.statCols || ['GP']).slice(1).map(() => Math.floor(rng()*20)),
    }));
  }, [p.id]);

  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'auto', background: WVU.ink, color: WVU.cream, paddingBottom: 120 }} className="mtn-scrollbar">
      {/* ─── HERO ─── */}
      <div style={{ position: 'relative', paddingTop: 54 }}>
        {/* Background photo wash */}
        <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
          <div style={{ position: 'absolute', inset: 0, background: `linear-gradient(180deg, ${hexA(WVU.gold, 0.22)}, rgb(26,26,34) 75%)` }} />
        </div>

        <div style={{ position: 'relative', padding: '0 16px' }}>
          <button onClick={onBack} style={{
            width: 34, height: 34, borderRadius: 17, marginBottom: 14,
            background: 'rgba(0,0,0,0.4)', border: '0.5px solid rgba(255,255,255,0.2)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: '#fff', padding: 0,
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M9 2L4 7l5 5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>

          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 16 }}>
            <div style={{ width: 96, height: 96, borderRadius: 48, overflow: 'hidden', flexShrink: 0, background: '#15151B', border: `3px solid ${WVU.gold}`, boxShadow: `0 8px 24px ${hexA(WVU.gold, 0.4)}` }}>
              <img src={p.avatar} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
            </div>
            <div style={{ flex: 1, minWidth: 0, paddingBottom: 4 }}>
              <div style={{ fontFamily: DS.mono, fontSize: 12, fontWeight: 700, color: WVU.gold, letterSpacing: '0.1em' }}>#{p.num} · {p.pos}</div>
              <div style={{ fontFamily: DS.display, fontSize: 28, fontWeight: 900, color: WVU.cream, letterSpacing: '-0.02em', lineHeight: 1.05, marginTop: 2 }}>{p.name}</div>
              <div style={{ fontFamily: DS.sans, fontSize: 12, color: WVU.creamDim, marginTop: 4 }}>{(sport && sport.name) || 'Team'} · {p.cls} · {p.home}</div>
            </div>
          </div>

          {/* Quick stat strip */}
          <div style={{ display: 'flex', gap: 0, marginTop: 16, borderRadius: DS.r.md, overflow: 'hidden', background: '#15151B', border: `0.5px solid ${WVU.line}` }}>
            {(p.statCols || []).slice(1, 5).map((c, i) => (
              <div key={c} style={{ flex: 1, textAlign: 'center', padding: '12px 4px', borderLeft: i ? `0.5px solid ${WVU.line}` : 'none' }}>
                <div style={{ fontFamily: DS.display, fontSize: 18, fontWeight: 900, color: WVU.cream, fontVariantNumeric: 'tabular-nums' }}>{(p.stats||[])[i+1]}</div>
                <div style={{ fontFamily: DS.mono, fontSize: 10, color: WVU.creamDim, letterSpacing: '0.08em', marginTop: 2 }}>{c}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* ─── TABS ─── */}
      <div style={{ display: 'flex', gap: 0, padding: '14px 8px 0', borderBottom: `1px solid rgba(255,255,255,0.08)`, marginTop: 16 }}>
        {tabs.map(tb => {
          const id = tb.toLowerCase().replace(' ', '');
          const on = id === tab;
          return (
            <button key={id} onClick={() => setTab(id)} style={{
              flex: 1, padding: '10px 4px 12px', background: 'transparent', border: 'none', cursor: 'pointer',
              fontFamily: DS.sans, fontSize: 12.5, fontWeight: 700,
              color: on ? '#fff' : 'rgba(255,255,255,0.5)', letterSpacing: '0.01em',
              borderBottom: on ? `3px solid ${WVU.gold}` : '3px solid transparent',
            }}>{tb}</button>
          );
        })}
      </div>

      <div style={{ padding: '16px 16px 0' }}>
        {tab === 'overview' && <PlayerOverview p={p} games={games} />}
        {tab === 'gamelog'  && <PlayerGameLog p={p} games={games} />}
        {tab === 'bio'      && <PlayerBio p={p} sport={sport} />}
        {tab === 'store'    && <PlayerStore p={p} onOpenNIL={onOpenNIL} fireReward={fireReward} />}
      </div>
    </div>
  );
}

function _rngP(seed) {
  let s = (seed || 1) >>> 0;
  return () => { s = (Math.imul(s, 1664525) + 1013904223) >>> 0; return s / 4294967296; };
}

function PlayerOverview({ p, games }) {
  return (
    <div>
      {/* Season story */}
      <div style={{ borderRadius: DS.r.md, background: `linear-gradient(135deg, ${hexA(WVU.gold, 0.12)}, #15151B)`, border: `0.5px solid ${hexA(WVU.gold, 0.3)}`, padding: 14, marginBottom: 14 }}>
        <div style={{ fontFamily: DS.mono, fontSize: 11, fontWeight: 700, color: WVU.gold, letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: 6 }}>The Story</div>
        <div style={{ fontFamily: DS.sans, fontSize: 14, fontWeight: 700, color: WVU.cream, lineHeight: 1.35 }}>
          {p.firstName} has been a cornerstone of the {WVU.nick || 'team'} this season — a {p.cls} {p.pos} out of {p.home}.
        </div>
        <div style={{ fontFamily: DS.sans, fontSize: 12.5, color: WVU.creamDim, marginTop: 8, lineHeight: 1.5 }}>
          A consistent presence on both sides of the ball, {p.lastName} has earned the trust of the coaching staff and the adoration of the fan base in {WVU.city || 'town'}.
        </div>
      </div>

      {/* Recent form */}
      <div style={{ fontFamily: DS.sans, fontSize: 12, fontWeight: 700, color: WVU.gold, letterSpacing: '0.11em', textTransform: 'uppercase', marginBottom: 10 }}>Recent Form</div>
      <div style={{ display: 'flex', gap: 6, marginBottom: 16 }}>
        {games.slice(0, 6).map(g => (
          <div key={g.id} style={{ flex: 1, textAlign: 'center' }}>
            <div style={{ width: '100%', height: 36, borderRadius: 6, background: g.won ? hexA(WVU.gold, 0.2) : 'rgba(255,90,90,0.15)', border: `0.5px solid ${g.won ? hexA(WVU.gold, 0.4) : 'rgba(255,90,90,0.3)'}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: DS.display, fontSize: 13, fontWeight: 900, color: g.won ? WVU.gold : '#FF8484' }}>{g.won ? 'W' : 'L'}</div>
            <div style={{ fontFamily: DS.mono, fontSize: 9.5, color: WVU.creamDim, marginTop: 3 }}>{g.opp.slice(0,3).toUpperCase()}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function PlayerGameLog({ p, games }) {
  const cols = (p.statCols || ['GP']).slice(1);
  return (
    <div>
      <div style={{ fontFamily: DS.sans, fontSize: 12, fontWeight: 700, color: WVU.gold, letterSpacing: '0.11em', textTransform: 'uppercase', marginBottom: 12 }}>2024 Game Log</div>
      <div style={{ borderRadius: DS.r.md, overflow: 'hidden', border: `0.5px solid ${WVU.line}` }}>
        <div style={{ display: 'grid', gridTemplateColumns: `1.4fr repeat(${cols.length}, 1fr)`, gap: 4, background: 'rgba(255,255,255,0.05)', padding: '8px 10px' }}>
          <div style={{ fontFamily: DS.mono, fontSize: 10.5, fontWeight: 700, color: WVU.creamDim, letterSpacing: '0.06em' }}>OPP</div>
          {cols.map(c => <div key={c} style={{ fontFamily: DS.mono, fontSize: 10.5, fontWeight: 700, color: WVU.creamDim, textAlign: 'right' }}>{c}</div>)}
        </div>
        {games.map((g, ri) => (
          <div key={g.id} style={{ display: 'grid', gridTemplateColumns: `1.4fr repeat(${cols.length}, 1fr)`, gap: 4, padding: '10px', alignItems: 'center', background: ri%2?'rgba(255,255,255,0.02)':'transparent', borderTop: `0.5px solid ${WVU.line}` }}>
            <div>
              <div style={{ fontFamily: DS.sans, fontSize: 12, fontWeight: 700, color: WVU.cream }}>{g.isHome ? 'vs' : '@'} {g.opp.split(' ')[0]}</div>
              <div style={{ fontFamily: DS.mono, fontSize: 10, color: g.won ? WVU.gold : '#FF8484' }}>{g.won ? 'W' : 'L'} · {g.date}</div>
            </div>
            {g.line.map((v, ci) => <div key={ci} style={{ fontFamily: DS.sans, fontSize: 12, fontWeight: 600, color: WVU.creamDim, textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{v}</div>)}
          </div>
        ))}
      </div>
    </div>
  );
}

function PlayerBio({ p, sport }) {
  const rows = [
    ['Position', p.pos], ['Class', p.cls], ['Height', p.ht], ['Weight', `${p.wt} lb`],
    ['Hometown', p.home], ['Sport', (sport && sport.name) || '—'], ['Jersey', `#${p.num}`],
  ];
  return (
    <div>
      <div style={{ fontFamily: DS.sans, fontSize: 12, fontWeight: 700, color: WVU.gold, letterSpacing: '0.11em', textTransform: 'uppercase', marginBottom: 12 }}>Player Bio</div>
      <div style={{ borderRadius: DS.r.md, overflow: 'hidden', background: '#15151B', border: `0.5px solid ${WVU.line}` }}>
        {rows.map(([k, v], i) => (
          <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '13px 14px', borderTop: i ? `0.5px solid ${WVU.line}` : 'none' }}>
            <div style={{ fontFamily: DS.sans, fontSize: 13, color: WVU.creamDim }}>{k}</div>
            <div style={{ fontFamily: DS.sans, fontSize: 13, fontWeight: 700, color: WVU.cream }}>{v}</div>
          </div>
        ))}
      </div>
      <div style={{ marginTop: 14, padding: 14, borderRadius: DS.r.md, background: '#15151B', border: `0.5px solid ${WVU.line}`, fontFamily: DS.sans, fontSize: 13, color: WVU.creamDim, lineHeight: 1.5 }}>
        {p.firstName} {p.lastName} committed to {WVU.name} out of {p.home}, choosing the {WVU.nick || 'program'} over a host of other offers. Known for a relentless motor and leadership in the locker room.
      </div>
    </div>
  );
}

function PlayerStore({ p, onOpenNIL, fireReward }) {
  const items = [
    { id: 'jersey', title: `${p.lastName} #${p.num} Jersey`, price: '$95', tag: 'OFFICIAL' },
    { id: 'tee', title: `${p.lastName} Name & Number Tee`, price: '$38', tag: 'NEW' },
    { id: 'poster', title: `${p.firstName} ${p.lastName} Poster`, price: '$22', tag: null },
    { id: 'signed', title: `Signed ${p.lastName} Photo`, price: '$60', tag: 'LIMITED' },
  ];
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
        <div style={{ fontFamily: DS.sans, fontSize: 12, fontWeight: 700, color: WVU.gold, letterSpacing: '0.11em', textTransform: 'uppercase' }}>{p.lastName} Store</div>
        <button onClick={onOpenNIL} style={{ padding: '6px 12px', borderRadius: DS.r.pill, background: hexA(WVU.gold, 0.14), border: `0.5px solid ${hexA(WVU.gold, 0.4)}`, fontFamily: DS.sans, fontSize: 12, fontWeight: 700, color: WVU.gold, cursor: 'pointer' }}>Support via NIL →</button>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {items.map((it, i) => (
          <div key={it.id} onClick={() => fireReward && fireReward({ pts: 25, reason: 'Added player gear', label: it.title.slice(0, 24) })} style={{ borderRadius: DS.r.md, overflow: 'hidden', background: '#15151B', border: `0.5px solid ${WVU.line}`, cursor: 'pointer' }}>
            <div style={{ position: 'relative', height: 120 }}>
              <WarmHero h={120} variant={['gold','blue','ember','gold'][i%4]} imgIndex={i*5+3} caption={null} />
              {it.tag && <div style={{ position: 'absolute', top: 8, left: 8, padding: '2px 7px', borderRadius: 3, background: WVU.gold, color: WVU.blueDim, fontFamily: DS.mono, fontSize: 9.5, fontWeight: 800, letterSpacing: '0.08em' }}>{it.tag}</div>}
            </div>
            <div style={{ padding: 10 }}>
              <div style={{ fontFamily: DS.sans, fontSize: 12.5, fontWeight: 700, color: WVU.cream, lineHeight: 1.25 }}>{it.title}</div>
              <div style={{ fontFamily: DS.display, fontSize: 15, fontWeight: 800, color: WVU.gold, marginTop: 6 }}>{it.price}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ScreenPlayer });
