// Daily result / leaderboard view.
// Props: mode ('xi'|'draft'), date (YYYY-MM-DD), onDone()
//
// Behavior:
//   - Loads top 5 scores for today + the user's rank if signed in
//   - For anon users: shows a teaser leaderboard with email capture below
//   - Always shows the user's own score at the top if they've played

function DailyResultScreen({ mode, date, onDone }) {
  const T = window.T;
  const [rows, setRows] = React.useState(null);
  const [signedIn, setSignedIn] = React.useState(false);
  const [authResolved, setAuthResolved] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [streak, setStreak] = React.useState(null);

  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const sig = await window.isSignedIn();
        if (cancelled) return;
        setSignedIn(sig);
        setAuthResolved(true);
        const lb = await window.getDailyLeaderboard(mode, date, 5);
        if (cancelled) return;
        setRows(lb);
        if (sig) {
          const st = await window.getMyStreaks();
          if (!cancelled) setStreak(st);
        }
      } catch (e) {
        if (!cancelled) {
          setError(e.message || 'Failed to load leaderboard');
          setAuthResolved(true);
        }
      }
    })();

    // Also subscribe to auth state changes so if the user signs in inline
    // (via the email prompt), the page reflects it immediately rather than
    // requiring a navigation.
    const { data: listener } = window.sb.auth.onAuthStateChange(async (_event, session) => {
      if (cancelled) return;
      const isNowSignedIn = !!session;
      setSignedIn(isNowSignedIn);
      setAuthResolved(true);
      // Refresh leaderboard so the user shows up as 'You' if they just signed in
      try {
        const lb = await window.getDailyLeaderboard(mode, date, 5);
        if (!cancelled) setRows(lb);
      } catch {}
      if (isNowSignedIn) {
        try {
          const st = await window.getMyStreaks();
          if (!cancelled) setStreak(st);
        } catch {}
      }
    });

    return () => {
      cancelled = true;
      listener?.subscription?.unsubscribe?.();
    };
  }, [mode, date]);

  const modeLabel = mode === 'xi' ? 'Name the XI' : 'Draft';
  const scoreLabel = mode === 'xi' ? 'guessed' : 'pts';

  // Find user's row (if any) — used for hero card if not in top 5
  const userRow = rows?.find(r => r.is_current_user);
  const top = rows?.filter(r => Number(r.rank) <= 5) || [];
  const userBelow = userRow && Number(userRow.rank) > 5 ? userRow : null;

  return (
    <Content>
      <AppHeader
        left={<PageWordmark text="DAILY"/>}
        right={<button onClick={onDone} style={{
          background:'transparent', border:'none', color:T.text,
          fontSize:24, lineHeight:1, cursor:'pointer', padding:'4px 8px',
        }}>×</button>}
      />

      <div style={{textAlign:'center', padding:'10px 0 18px'}}>
        <div style={{fontSize:11, color:T.gold400, fontFamily:'DM Sans', letterSpacing:'0.2em', textTransform:'uppercase'}}>
          Today's {modeLabel}
        </div>
        <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:24, color:T.text, letterSpacing:'0.04em', marginTop:6}}>
          LEADERBOARD
        </div>
        {streak?.any_daily > 0 && (
          <div style={{fontSize:12, color:T.textSec, marginTop:6}}>
            🔥 {streak.any_daily}-day streak
            {streak.daily_duo > 0 && <> · {streak.daily_duo}-day duo</>}
          </div>
        )}
      </div>

      {error && (
        <div style={{
          background: 'rgba(232,122,122,0.1)', border:'1px solid rgba(232,122,122,0.4)',
          color:'#E87A7A', padding:14, borderRadius:12, fontSize:13, marginBottom:14,
        }}>{error}</div>
      )}

      {/* User's own row prominently if outside top 5 */}
      {userBelow && <LbRow row={userBelow} highlighted scoreLabel={scoreLabel}/>}

      {!error && rows == null && (
        <div style={{textAlign:'center', color:T.textMute, padding:30, fontSize:13}}>Loading leaderboard…</div>
      )}

      {/* Top 5 */}
      {top.length > 0 && (
        <>
          <div style={{
            fontSize:10, color:T.textMute, fontFamily:'DM Sans', letterSpacing:'0.2em',
            textAlign:'center', margin:'14px 0 8px', textTransform:'uppercase',
          }}>Top 5</div>
          {top.map(r => <LbRow key={r.user_id} row={r} highlighted={r.is_current_user} scoreLabel={scoreLabel}/>)}
        </>
      )}

      {!error && rows != null && rows.length === 0 && (
        <div style={{textAlign:'center', color:T.textMute, padding:30, fontSize:13}}>
          No scores yet today. Be the first.
        </div>
      )}

      {/* Anon email capture — only shown once auth state is confirmed anonymous,
          so signed-in users never see this even briefly. */}
      {authResolved && !signedIn && rows && rows.length > 0 && (
        <div style={{
          marginTop: 16,
          background: 'linear-gradient(135deg, #172340 0%, #0D1828 100%)',
          border: `1px solid ${T.gold600}`,
          borderRadius: 16, padding: 18,
          textAlign:'center',
        }}>
          <div style={{fontSize:34, marginBottom:8}}>📊</div>
          <div style={{
            fontFamily:'Bakbak One, sans-serif', fontSize:17,
            color:T.text, letterSpacing:'0.03em', marginBottom:6,
          }}>See the Full Leaderboard</div>
          <div style={{fontSize:12, color:T.textSec, marginBottom:14, lineHeight:1.5}}>
            Sign in to see your rank, build a streak, and save your trophies.
          </div>
          {window.InlineAuthForm && <window.InlineAuthForm/>}
        </div>
      )}

      <div style={{position:'absolute', left:20, right:20, bottom:38}}>
        <button onClick={onDone} style={{
          width:'100%', padding:'14px', borderRadius:14,
          background: T.card, border:`1px solid ${T.border}`, color: T.text,
          cursor:'pointer', fontFamily:'Bakbak One, sans-serif', fontSize:14, letterSpacing:'0.06em',
        }}>DONE</button>
      </div>
    </Content>
  );
}

function LbRow({ row, highlighted, scoreLabel }) {
  const T = window.T;
  const initials = (row.display_name || '??').split(/\s+/).map(x => x[0]).slice(0, 2).join('').toUpperCase();
  const rank = Number(row.rank);
  const rankColor = rank === 1 ? '#F5C842' : rank === 2 ? '#E8E8E8' : rank === 3 ? '#CD9966' : T.textMute;
  return (
    <div style={{
      display:'flex', alignItems:'center', gap:12,
      padding:'10px 12px',
      background: highlighted ? 'rgba(245,200,66,0.08)' : T.card,
      border: `1px solid ${highlighted ? T.gold600 : T.border}`,
      borderRadius:12,
      marginBottom:8,
    }}>
      <div style={{
        width:30, textAlign:'center',
        fontFamily:'Bakbak One, sans-serif', fontSize:18,
        color:rankColor, letterSpacing:'0.02em',
      }}>{rank}</div>
      <div style={{
        width:32, height:32, borderRadius:'50%',
        background: rank <= 3 ? rankColor : T.navy700,
        color: rank <= 3 ? '#1A1200' : T.text,
        display:'flex', alignItems:'center', justifyContent:'center',
        fontFamily:'DM Sans', fontWeight:800, fontSize:11,
        flexShrink:0,
      }}>{initials}</div>
      <div style={{flex:1, minWidth:0}}>
        <div style={{
          fontSize:13, color:T.text, fontWeight:600,
          whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis',
        }}>{highlighted ? `You · ${row.display_name}` : row.display_name}</div>
        {row.metadata?.home_club && row.metadata?.away_club && (
          <div style={{
            fontSize:10, color:T.textMute, marginTop:1,
            whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis',
          }}>{row.metadata.home_club} vs {row.metadata.away_club}</div>
        )}
        {row.metadata?.year && (
          <div style={{fontSize:10, color:T.textMute, marginTop:1}}>{row.metadata.year} Draft</div>
        )}
      </div>
      <div style={{
        fontFamily:'Bakbak One, sans-serif', fontSize:18,
        color:T.gold400, letterSpacing:'0.02em',
      }}>{row.score}<span style={{fontSize:9, color:T.textMute, marginLeft:3}}>{scoreLabel}</span></div>
    </div>
  );
}

window.DailyResultScreen = DailyResultScreen;
