// Profile screen — shows real authed user + real stats
function ProfileScreen() {
  const T = window.T;
  const [user, setUser] = React.useState(null);
  const [profile, setProfile] = React.useState(null);
  const [mySessions, setMySessions] = React.useState(null);
  const [allSessions, setAllSessions] = React.useState(null);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const [u, p, mine, all] = await Promise.all([
          window.getCurrentUser(),
          window.getCurrentProfile(),
          window.fetchMySessions(),
          window.fetchAllCompletedSessions(),
        ]);
        if (!mounted) return;
        setUser(u);
        setProfile(p);
        setMySessions(mine);
        setAllSessions(all);
      } finally {
        if (mounted) setLoading(false);
      }
    })();
    return () => { mounted = false; };
  }, []);

  const handleSignOut = async () => {
    if (confirm('Sign out of Futball?')) {
      await window.signOut();
    }
  };

  // Compute user's stats and rank
  const stats = React.useMemo(() => {
    if (!mySessions || !allSessions || !user) return null;

    const gamesPlayed = mySessions.length;
    const myXi = mySessions.filter(s => s.mode === 'xi');
    const myDraft = mySessions.filter(s => s.mode === 'draft');
    const myXiCorrect = myXi.reduce((sum, s) => sum + (s.metadata?.guessed_count || 0), 0);
    const myXiTotal = myXi.reduce((sum, s) => sum + (s.metadata?.total_starters || 22), 0);
    const myAcc = myXiTotal > 0 ? Math.round((myXiCorrect / myXiTotal) * 100) : 0;

    // Best Draft combined score (with backfill)
    const myBestDraft = myDraft.reduce((best, s) => {
      const combined = s.metadata?.combined_score != null
        ? s.metadata.combined_score
        : (s.metadata?.average_rating || 0) + (s.metadata?.chemistry || 0);
      return Math.max(best, combined);
    }, 0);

    // Compute global rank by XI accuracy
    const xiSessions = allSessions.filter(s => s.mode === 'xi');
    const byUser = {};
    xiSessions.forEach(s => {
      const uid = s.user_id;
      if (!byUser[uid]) byUser[uid] = { correct: 0, total: 0 };
      byUser[uid].correct += s.metadata?.guessed_count || 0;
      byUser[uid].total += s.metadata?.total_starters || 22;
    });
    const ranked = Object.entries(byUser)
      .map(([uid, data]) => ({ uid, acc: data.total > 0 ? data.correct / data.total : 0 }))
      .filter(r => r.acc > 0)
      .sort((a, b) => b.acc - a.acc);

    let myRank = null;
    if (myXi.length > 0) {
      const idx = ranked.findIndex(r => r.uid === user.id);
      if (idx >= 0) myRank = idx + 1;
    }

    return { gamesPlayed, myAcc, myRank, totalRanked: ranked.length, myBestDraft };
  }, [mySessions, allSessions, user]);

  const Stat = ({ value, label, divider }) => (
    <div style={{ textAlign:'center', padding:'0 8px', position:'relative' }}>
      {divider && <span style={{position:'absolute', left:0, top:'15%', bottom:'15%', width:1, background:T.border}}/>}
      <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:22, color:T.gold400, letterSpacing:'0.02em'}}>{value}</div>
      <div style={{fontFamily:'DM Sans', fontSize:9, letterSpacing:'0.18em', color:T.textMute, textTransform:'uppercase', marginTop:2}}>{label}</div>
    </div>
  );

  const Item = ({ icon, label, danger, onClick }) => (
    <div onClick={onClick} style={{
      display:'flex', alignItems:'center', gap:14, padding:16,
      background:T.card, borderRadius:14, marginBottom:8,
      cursor: onClick ? 'pointer' : 'default',
    }}>
      <div style={{
        width:34, height:34, borderRadius:10, background:T.navy700,
        display:'flex', alignItems:'center', justifyContent:'center',
        color:T.gold400, fontSize:16,
      }}>{icon}</div>
      <div style={{flex:1, fontSize:14, fontWeight:500, color: danger ? T.red : T.text}}>{label}</div>
      <div style={{color:T.textMute, fontSize:18}}>›</div>
    </div>
  );

  if (loading) {
    return (
      <Content>
        <AppHeader left={<PageWordmark text="PROFILE"/>}/>
        <div style={{textAlign:'center', padding:'40px 0', color:T.textSec}}>Loading…</div>
      </Content>
    );
  }

  const displayName = profile?.display_name || (user?.email ? user.email.split('@')[0] : 'Player');
  const email = user?.email || '';
  const initials = displayName.slice(0, 2).toUpperCase();
  const joinDate = user?.created_at ? new Date(user.created_at).toLocaleDateString('en-US', {month:'short', year:'numeric'}) : '';

  // Values for the three stat pills
  const rankValue = stats?.myRank ? `#${stats.myRank}` : '—';
  const gamesValue = stats?.gamesPlayed || 0;
  const draftBestValue = stats?.myBestDraft > 0 ? stats.myBestDraft : '—';

  return (
    <Content>
      <AppHeader left={<PageWordmark text="PROFILE"/>}/>

      <div style={{textAlign:'center', padding:'16px 0 24px'}}>
        <div style={{
          width:88, height:88, borderRadius:'50%',
          background:`linear-gradient(135deg, ${T.gold500}, ${T.gold600})`,
          margin:'0 auto 12px',
          display:'flex', alignItems:'center', justifyContent:'center',
          fontFamily:'Bakbak One, sans-serif', fontSize:32, color:T.navy950, letterSpacing:'0.04em',
          boxShadow:'0 10px 30px rgba(232,184,32,0.25)',
        }}>{initials}</div>
        <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:24, letterSpacing:'0.04em', color:T.text, textTransform:'uppercase'}}>
          {displayName}
        </div>
        <div style={{fontSize:12, color:T.textMute, marginTop:4}}>
          {email}{joinDate ? ` · Joined ${joinDate}` : ''}
        </div>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', background:T.card, borderRadius:16, padding:'16px 8px', marginBottom:20}}>
        <Stat value={rankValue} label="XI Rank"/>
        <Stat value={gamesValue} label="Games" divider/>
        <Stat value={draftBestValue} label="Draft Best" divider/>
      </div>

      <SectionLabel size={16} top={8} bottom={8}>Account</SectionLabel>
      <Item icon={<HexIcon size={14}/>} label="Buy Tokens"/>
      <Item icon="✎" label="Edit Profile"/>
      <Item icon="◉" label="Notifications"/>

      <SectionLabel size={16} top={20} bottom={8}>App</SectionLabel>
      <Item icon="♪" label="Sound & Haptics"/>
      <Item icon="?" label="Help & Support"/>
      <Item icon="⎋" label="Sign Out" danger onClick={handleSignOut}/>
    </Content>
  );
}
window.ProfileScreen = ProfileScreen;
