// Home screen
function HomeScreen({ onOpenDraft, onOpenXi }) {
  const T = window.T;
  const [displayName, setDisplayName] = React.useState('');
  const [sessions, setSessions] = React.useState(null);

  React.useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const signedIn = await window.isSignedIn();
        if (!signedIn) {
          if (mounted) { setDisplayName(''); setSessions([]); }
          return;
        }
        const [user, profile, mySess] = await Promise.all([
          window.getCurrentUser(),
          window.getCurrentProfile(),
          window.fetchMySessions(),
        ]);
        if (!mounted) return;
        const name = profile?.display_name || (user?.email ? user.email.split('@')[0] : 'player');
        setDisplayName(name);
        setSessions(mySess);
      } catch (e) {
        if (mounted) setDisplayName('');
      }
    })();
    return () => { mounted = false; };
  }, []);

  const modes = [
    { title: 'DRAFT MODE', icon: '⚡', desc: 'Random year, 3 picks per position. Build the best squad.', handler: onOpenDraft, available: true },
    { title: 'NAME THE XI', icon: '📋', desc: 'Name each player from an iconic match. Beat the clock.', handler: onOpenXi, available: true },
    { title: 'ROAD TO GLORY', icon: '🏆', desc: 'Earn Players. Beat 32 teams. Win the cup.', handler: null, available: false },
  ];

  // Compute last 5 sessions per mode
  // fetchMySessions returns sessions ordered by started_at desc, so first 5 are the most recent
  const recent = React.useMemo(() => {
    if (!sessions) return null;
    const xi = sessions
      .filter(s => s.mode === 'xi' && s.metadata?.total_starters > 0)
      .slice(0, 5)
      .reverse() // chart goes left-to-right (oldest → newest)
      .map(s => ({
        value: Math.round(((s.metadata.guessed_count || 0) / s.metadata.total_starters) * 100),
        label: `${s.metadata.home_club || '?'} vs ${s.metadata.away_club || '?'}`,
      }));
    const draft = sessions
      .filter(s => s.mode === 'draft')
      .slice(0, 5)
      .reverse()
      .map(s => {
        const combined = s.metadata?.combined_score != null
          ? s.metadata.combined_score
          : (s.metadata?.average_rating || 0) + (s.metadata?.chemistry || 0);
        return { value: combined, label: `${s.metadata?.year || '?'} Draft` };
      });
    return { xi, draft };
  }, [sessions]);

  return (
    <Content>
      <AppHeader left={<Wordmark size={30} />} />

      <div style={{
        fontFamily: 'DM Sans', fontSize: 22, fontWeight: 700, color: T.text,
        marginBottom: 4,
      }}>{displayName ? `Welcome, ${displayName}` : 'Welcome'}</div>

      <SectionLabel>Play Now</SectionLabel>

      {modes.map(m => (
        <div key={m.title} onClick={m.available ? m.handler : undefined} style={{
          background: T.card,
          border: '1px solid rgba(255,255,255,0.04)',
          borderRadius: 18, padding: '18px 20px', marginBottom: 12,
          cursor: m.available ? 'pointer' : 'not-allowed',
          opacity: m.available ? 1 : 0.45,
          position: 'relative',
        }}>
          <div style={{
            fontFamily: 'Bakbak One, sans-serif', fontSize: 20,
            letterSpacing: '0.03em', color: T.text,
            display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6,
          }}>
            {m.title} <span style={{ color: T.gold500, fontSize: 18 }}>{m.icon}</span>
            {!m.available && (
              <span style={{
                marginLeft:'auto',
                fontSize: 9, fontFamily:'DM Sans', letterSpacing:'0.18em',
                padding:'3px 8px', borderRadius: 100,
                background:'rgba(255,255,255,0.06)', color: T.textMute,
              }}>COMING SOON</span>
            )}
          </div>
          <div style={{ fontSize: 12.5, color: T.textSec, lineHeight: 1.4 }}>{m.desc}</div>
        </div>
      ))}

      {displayName ? (
        <>
          <SectionLabel>Recent Form</SectionLabel>
          <div style={{display:'flex', flexDirection:'column', gap:12, marginBottom: 12}}>
            <MiniChart
              title="Name the XI"
              subtitle="Accuracy % across last 5 games"
              data={recent?.xi}
              maxValue={100}
              color={T.gold400}
              suffix="%"
              full
            />
            <MiniChart
              title="Draft"
              subtitle="Score (of 199) across last 5 games"
              data={recent?.draft}
              maxValue={199}
              color={T.greenLt}
              suffix=""
              full
            />
          </div>
        </>
      ) : (
        <div style={{
          background: T.card, borderRadius: 16,
          padding:'20px 18px', marginTop: 8,
          display:'flex', alignItems:'center', gap: 14,
          border: `1px solid ${T.border}`,
        }}>
          <div style={{fontSize: 28, lineHeight: 1, flexShrink: 0}}>📊</div>
          <div style={{flex: 1, minWidth: 0}}>
            <div style={{
              fontFamily:'DM Sans', fontSize: 13, fontWeight: 700,
              color: T.text, marginBottom: 3,
            }}>Track your progress</div>
            <div style={{fontSize: 12, color: T.textSec, lineHeight: 1.5}}>
              Sign in to save your stats and trophies. Tap any locked tab below to get a code.
            </div>
          </div>
        </div>
      )}
    </Content>
  );
}

// ────── MiniChart — sparkline with dots showing last 5 games ──────
function MiniChart({ title, subtitle, data, maxValue, color, suffix, full }) {
  const T = window.T;
  // Full mode = wider chart, taller, larger typography
  const W = full ? 600 : 280;
  const H = full ? 130 : 80;
  const padding = full ? 14 : 8;
  const chartW = W - padding * 2;
  const chartH = H - padding * 2;

  const isEmpty = !data || data.length === 0;
  const isLoading = data === undefined;

  // Build path coordinates if we have data
  let pathD = '';
  let areaD = '';
  let points = [];
  if (data && data.length > 0) {
    const n = data.length;
    points = data.map((d, i) => {
      const x = n === 1 ? chartW / 2 + padding : padding + (i / (n - 1)) * chartW;
      const y = padding + chartH - (d.value / maxValue) * chartH;
      return { x, y, value: d.value };
    });
    pathD = points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`).join(' ');
    areaD = `${pathD} L ${points[points.length-1].x} ${H - padding} L ${points[0].x} ${H - padding} Z`;
  }

  const latest = data && data.length > 0 ? data[data.length - 1].value : null;
  const best = data && data.length > 0 ? Math.max(...data.map(d => d.value)) : null;
  const avg = data && data.length > 0 ? Math.round(data.reduce((s,d) => s + d.value, 0) / data.length) : null;

  return (
    <div style={{
      background: T.card, borderRadius: 16,
      padding: full ? '16px 18px 14px' : '14px 14px 12px',
      position:'relative', overflow:'hidden',
    }}>
      <div style={{
        display:'flex', justifyContent:'space-between', alignItems:'flex-start',
        marginBottom: full ? 12 : 8,
      }}>
        <div>
          <div style={{
            fontFamily:'DM Sans',
            fontSize: full ? 15 : 12,
            fontWeight: 700, color: T.text,
            letterSpacing: '0.01em',
          }}>{title}</div>
          <div style={{
            fontFamily:'DM Sans',
            fontSize: full ? 11 : 10,
            color: T.textMute, marginTop: full ? 2 : 1,
          }}>{subtitle}</div>
        </div>
        {latest != null && (
          <div style={{textAlign:'right'}}>
            <div style={{
              fontFamily:'Bakbak One, sans-serif',
              fontSize: full ? 28 : 22,
              color, letterSpacing:'0.02em', lineHeight: 1,
            }}>{latest}{suffix}</div>
            <div style={{fontSize: 9, color: T.textMute, fontFamily:'DM Sans', letterSpacing:'0.1em', marginTop: 4}}>LATEST</div>
          </div>
        )}
      </div>

      <svg width="100%" height={H} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{display:'block'}}>
        <defs>
          <linearGradient id={`grad-${title.replace(/\s+/g,'')}`} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity="0.35"/>
            <stop offset="100%" stopColor={color} stopOpacity="0"/>
          </linearGradient>
        </defs>

        {(isEmpty || isLoading) && (
          <>
            <line x1={padding} y1={H/2} x2={W - padding} y2={H/2}
              stroke={T.border} strokeWidth="1" strokeDasharray="3 4"/>
            <text x={W/2} y={H/2 + 4} textAnchor="middle"
              fontFamily="DM Sans" fontSize={full ? 12 : 10} fill={T.textMute}>
              {isLoading ? 'Loading…' : 'Play to start tracking'}
            </text>
          </>
        )}

        {!isEmpty && !isLoading && (
          <>
            {points.length > 1 && <path d={areaD} fill={`url(#grad-${title.replace(/\s+/g,'')})`}/>}
            {points.length > 1 && <path d={pathD} stroke={color} strokeWidth={full ? 2.5 : 2}
              fill="none" strokeLinecap="round" strokeLinejoin="round"/>}
            {points.map((p, i) => (
              <circle key={i} cx={p.x} cy={p.y}
                r={i === points.length - 1 ? (full ? 5 : 4) : (full ? 4 : 3)}
                fill={color}
                stroke={i === points.length - 1 ? '#fff' : 'none'}
                strokeWidth="1.5"/>
            ))}
          </>
        )}
      </svg>

      {/* Footer stats — only in full mode, shows avg/best/games */}
      {full && data && data.length > 0 && (
        <div style={{
          display:'flex', justifyContent:'space-between',
          marginTop: 10, paddingTop: 10,
          borderTop: `1px solid ${T.border}`,
        }}>
          <FootStat label="Best"  value={`${best}${suffix}`}/>
          <FootStat label="Avg"   value={`${avg}${suffix}`}/>
          <FootStat label="Games" value={data.length}/>
        </div>
      )}

      {!full && data && data.length > 0 && (
        <div style={{fontSize: 9, color: T.textMute, fontFamily:'DM Sans', textAlign:'center', marginTop: 4}}>
          Last {data.length} {data.length === 1 ? 'game' : 'games'}
        </div>
      )}
    </div>
  );
}

function FootStat({ label, value }) {
  const T = window.T;
  return (
    <div style={{textAlign:'center', flex: 1}}>
      <div style={{
        fontSize: 9, fontFamily:'DM Sans', letterSpacing:'0.15em',
        color: T.textMute, textTransform:'uppercase',
      }}>{label}</div>
      <div style={{
        fontFamily:'Bakbak One, sans-serif', fontSize: 16,
        color: T.gold400, marginTop: 3,
      }}>{value}</div>
    </div>
  );
}

window.HomeScreen = HomeScreen;
window.MiniChart = MiniChart;
