// Result & Records components

function ResultScreen({ score, config, reason, appleShape, onRestart, onNewSettings, onMain, onLeaderboard, multiState, onMultiRematch, onMultiLeave, breakpoint }) {
  const isMulti = !!(multiState && multiState.finalPlayers && Object.keys(multiState.finalPlayers).length > 0);

  const rankedPlayers = isMulti
    ? Object.entries(multiState.finalPlayers)
        .sort((a, b) => (b[1].score || 0) - (a[1].score || 0))
    : [];

  const medals = ['🥇', '🥈', '🥉'];

  return (
    <>
    <style>{`
      .result-layout { padding: clamp(24px, 5vw, 44px); }
      .result-grid { display: grid; grid-template-columns: 1fr 1.2fr; gap: 40px; align-items: center; position: relative; z-index: 1; flex: 1; }
      .result-score { font-size: clamp(100px, 15vw, 200px); line-height: 0.8; }
      .mascot-result svg { width: clamp(200px, 30vw, 320px); height: auto; }
      @media (max-width: 850px) {
        .result-grid { grid-template-columns: 1fr; text-align: center; }
        .mascot-result { display: none; }
      }
    `}</style>
    <div className="result-layout" style={{
      width: '100%', height: '100%',
      background: `radial-gradient(ellipse at 50% 30%, rgba(244,162,97,0.30), transparent 60%), var(--paper)`,
      display: 'flex', flexDirection: 'column',
      fontFamily: 'var(--font-body)', position: 'relative', overflow: 'auto'
    }}>
      <div style={{ position: 'absolute', left: '6%', top: '8%', transform: 'rotate(-12deg)', opacity: 0.6 }}><AppleCell n={7} size={36} shape="realistic" /></div>
      <div style={{ position: 'absolute', right: '6%', top: '12%', transform: 'rotate(18deg)', opacity: 0.6 }}><AppleCell n={3} size={44} shape="realistic" /></div>

      {isMulti ? (
        /* 멀티플레이 결과 화면 */
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 28, flex: 1, justifyContent: 'center', position: 'relative', zIndex: 1 }}>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--apple-deep)', letterSpacing: '0.3em', textTransform: 'uppercase' }}>같이 따기 · RESULT</div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(32px, 6vw, 56px)', fontWeight: 700, color: 'var(--ink)', marginTop: 8 }}>
              {rankedPlayers[0] && rankedPlayers[0][0] === multiState.userId ? '🎉 1등이다!' : '수확 완료!'}
            </div>
          </div>

          {/* 순위표 */}
          <div style={{ width: '100%', maxWidth: 480, display: 'flex', flexDirection: 'column', gap: 10 }}>
            {rankedPlayers.map(([uid, p], i) => (
              <div key={uid} style={{
                display: 'flex', alignItems: 'center', gap: 16,
                padding: '16px 20px', borderRadius: 16,
                background: uid === multiState.userId ? 'rgba(27,67,50,0.08)' : 'var(--paper-warm)',
                border: uid === multiState.userId ? '2px solid var(--leaf)' : '1.5px solid var(--hairline)',
                boxShadow: i === 0 ? '0 4px 16px rgba(244,162,97,0.2)' : 'none'
              }}>
                <span style={{ fontSize: 28, minWidth: 36, textAlign: 'center' }}>
                  {medals[i] || `${i + 1}`}
                </span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 700, fontSize: 16, color: uid === multiState.userId ? 'var(--leaf)' : 'var(--ink)' }}>
                    {p.displayName || '플레이어'}
                    {uid === multiState.userId && <span style={{ fontSize: 12, color: 'var(--ink-mute)', marginLeft: 6 }}>(나)</span>}
                  </div>
                </div>
                <div style={{ fontFamily: 'var(--font-num)', fontSize: 32, fontWeight: 900, color: i === 0 ? 'var(--apple)' : 'var(--ink)' }}>
                  {p.score || 0}
                </div>
              </div>
            ))}
          </div>

          {/* 멀티플레이 버튼 */}
          <div style={{ display: 'flex', gap: 12, width: '100%', maxWidth: 480 }}>
            <button onClick={onMultiRematch} style={{
              flex: 1, padding: '16px', borderRadius: 14, border: 'none',
              background: 'var(--leaf)', color: '#fff', fontWeight: 700, cursor: 'pointer', fontSize: 16
            }}>
              {multiState.isHost ? '한 판 더 (같은 방)' : '한 판 더 (대기)'}
            </button>
            <button onClick={onMultiLeave} style={{
              flex: 1, padding: '16px', borderRadius: 14,
              border: '1.5px solid var(--hairline)',
              background: 'var(--paper)', color: 'var(--ink-soft)', fontWeight: 700, cursor: 'pointer', fontSize: 16
            }}>나가기</button>
          </div>

          {!multiState.isHost && (
            <div style={{ fontSize: 13, color: 'var(--ink-mute)', textAlign: 'center' }}>
              "한 판 더" 클릭 시 대기실로 이동합니다. 호스트가 게임을 시작하면 자동으로 시작됩니다.
            </div>
          )}
        </div>
      ) : (
        /* 싱글 결과 화면 */
        <div className="result-grid">
          <div className="mascot-result" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <AppleMascot size={320} mood={reason === 'clear' ? "happy" : "neutral"} />
            <div style={{ marginTop: 15, fontFamily: 'var(--font-display)', fontSize: 28, color: 'var(--ink)', fontWeight: 700, fontStyle: 'italic' }}>
              {reason === 'clear' ? "완벽한 수확이야!" : (reason === 'nomoves' ? "더 이상 할 수 있는게 없어!" : "이만큼이나 땄어!")}
            </div>
          </div>

          <div>
            <div style={{ fontFamily: 'var(--font-en)', fontSize: 18, color: 'var(--apple-deep)', letterSpacing: '0.3em', textTransform: 'uppercase' }}>
              Result
            </div>
            <div className="result-score" style={{
              fontFamily: 'var(--font-num)', color: 'var(--apple)',
              letterSpacing: '-0.04em', marginTop: 10, fontWeight: 900
            }}>
              {score}
            </div>

            <div style={{ marginTop: 40, display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div style={{ width: '100%', maxWidth: 400 }}>
                <PrimaryButton onClick={onRestart} variant="primary">같은 모드로 한 번 더 →</PrimaryButton>
              </div>
              <div style={{ display: 'flex', gap: 12, width: '100%', maxWidth: 400 }}>
                <button onClick={onNewSettings} style={{
                  flex: 1, padding: '14px', borderRadius: 14, border: '1.5px solid var(--hairline)',
                  background: 'var(--paper-warm)', color: 'var(--ink)', fontWeight: 700, cursor: 'pointer', fontSize: 15
                }}>다른 설정</button>
                <button onClick={onMain} style={{
                  flex: 1, padding: '14px', borderRadius: 14, border: '1.5px solid var(--hairline)',
                  background: 'var(--paper)', color: 'var(--ink-soft)', fontWeight: 700, cursor: 'pointer', fontSize: 15
                }}>메인으로</button>
                <button onClick={onLeaderboard} style={{
                  flex: 1, padding: '14px', borderRadius: 14, border: '1.5px solid var(--hairline)',
                  background: 'var(--ink)', color: '#fff', fontWeight: 700, cursor: 'pointer', fontSize: 15
                }}>리더보드</button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
    </>
  );
}

function RecordsScreen({ records, appleShape, onMain, breakpoint }) {
  const { isMobile, isUltrawide } = breakpoint || {};
  const [activeTab, setActiveTab] = React.useState('all');

  const allEntries = Object.entries(records);

  // ── Summary 계산 ──
  const totalPlays   = allEntries.reduce((s, [, r]) => s + (r.playCount  || 0), 0);
  const totalScore   = allEntries.reduce((s, [, r]) => s + (r.totalScore || 0), 0);
  const bestScore    = allEntries.reduce((s, [, r]) => Math.max(s, r.highScore || 0), 0);
  const overallAvg   = totalPlays > 0 ? (totalScore / totalPlays) : 0;

  // 모드별 평균: 2분 / 무한 각각
  const byTime = (prefix) => {
    const entries = allEntries.filter(([k]) => k.startsWith(prefix));
    const plays = entries.reduce((s, [, r]) => s + (r.playCount  || 0), 0);
    const score = entries.reduce((s, [, r]) => s + (r.totalScore || 0), 0);
    return plays > 0 ? (score / plays) : null;
  };
  const avg2min    = byTime('120');
  const avgInfin   = byTime('infinite');

  // 모드별 최고: 2분 / 무한
  const best2min  = allEntries.filter(([k]) => k.startsWith('120')).reduce((s, [, r]) => Math.max(s, r.highScore || 0), 0);
  const bestInfin = allEntries.filter(([k]) => k.startsWith('infinite')).reduce((s, [, r]) => Math.max(s, r.highScore || 0), 0);

  const filteredRecords = activeTab === 'all'
    ? allEntries
    : allEntries.filter(([k]) => k.startsWith(activeTab === '2min' ? '120' : 'infinite'));

  const StatTile = ({ label, value, sub, accent }) => (
    <div style={{
      flex: '1 1 0', minWidth: 100,
      background: 'var(--paper-warm)', borderRadius: 16,
      border: '1.5px solid var(--hairline)', padding: '16px 20px',
      display: 'flex', flexDirection: 'column', gap: 4
    }}>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-mute)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>{label}</span>
      <span style={{ fontFamily: 'var(--font-num)', fontSize: 30, fontWeight: 800, lineHeight: 1, color: accent || 'var(--ink)' }}>{value}</span>
      {sub && <span style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 2 }}>{sub}</span>}
    </div>
  );

  return (
    <>
    <style>{`
      .records-layout { padding: clamp(16px, 3vw, 32px) clamp(16px, 4vw, 40px); }
      .records-header { flex-direction: row; }
      .summary-grid { display: flex; flex-wrap: wrap; gap: 10px; }
      .mode-avg-row { display: flex; flex-wrap: wrap; gap: 10px; }
      @media (max-width: 600px) {
        .records-header { flex-direction: column; gap: 12px; }
        .records-controls { width: 100%; flex-wrap: wrap; justify-content: flex-start; }
      }
    `}</style>
    <div className="records-layout" style={{
      width: '100%', height: '100%', background: 'var(--paper)',
      display: 'flex', flexDirection: 'column', gap: 20,
      fontFamily: 'var(--font-body)', overflowY: 'auto', boxSizing: 'border-box',
      maxWidth: isUltrawide ? 1400 : '100%',
      margin: isUltrawide ? '0 auto' : undefined,
    }}>
      {/* ── 헤더 ── */}
      <div className="records-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--apple-deep)', letterSpacing: '0.22em', textTransform: 'uppercase' }}>● 나의 기록 · ARCHIVE</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(28px, 5vw, 44px)', color: 'var(--ink)', fontWeight: 700, marginTop: 4, lineHeight: 1 }}>
            한 해의 수확.
          </div>
        </div>
        <div className="records-controls" style={{ display: 'flex', gap: 8 }}>
          <button onClick={onMain} style={{ padding: '10px 18px', background: 'transparent', border: '1.5px solid var(--hairline)', borderRadius: 12, color: 'var(--ink-soft)', fontSize: 14, fontWeight: 600, cursor: 'pointer' }}>메인으로</button>
        </div>
      </div>

      {/* ── MY SUMMARY ── */}
      {totalPlays > 0 && (
        <div style={{
          background: 'var(--paper-warm)', borderRadius: 20,
          border: '1.5px solid var(--ink)', padding: '22px 24px',
          display: 'flex', flexDirection: 'column', gap: 16
        }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '0.16em', textTransform: 'uppercase' }}>
            🍎 My Summary
          </div>

          {/* 핵심 스탯 4개 */}
          <div className="summary-grid">
            <StatTile label="총 판수"  value={totalPlays.toLocaleString()}               sub="games played" />
            <StatTile label="총 점수"  value={totalScore.toLocaleString()}               sub="cumulative"   accent="var(--apple)" />
            <StatTile label="최고 점수" value={bestScore.toLocaleString()}               sub="all-time best" accent="var(--gold)" />
            <StatTile label="전체 평균" value={overallAvg.toFixed(1)}                    sub="per game" />
          </div>

          {/* 모드별 평균 */}
          <div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-mute)', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 10 }}>
              MODE AVERAGES
            </div>
            <div className="mode-avg-row">
              {avg2min !== null && (
                <div style={{
                  flex: '1 1 0', minWidth: 140,
                  background: 'var(--paper)', borderRadius: 12,
                  border: '1px solid var(--hairline)', padding: '12px 16px',
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center'
                }}>
                  <div>
                    <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--ink)' }}>⏱ 2분 모드</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 2 }}>최고 {best2min.toLocaleString()}</div>
                  </div>
                  <span style={{ fontFamily: 'var(--font-num)', fontSize: 26, fontWeight: 800, color: 'var(--leaf)' }}>
                    {avg2min.toFixed(1)}
                  </span>
                </div>
              )}
              {avgInfin !== null && (
                <div style={{
                  flex: '1 1 0', minWidth: 140,
                  background: 'var(--paper)', borderRadius: 12,
                  border: '1px solid var(--hairline)', padding: '12px 16px',
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center'
                }}>
                  <div>
                    <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--ink)' }}>∞ 무한 모드</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 2 }}>최고 {bestInfin.toLocaleString()}</div>
                  </div>
                  <span style={{ fontFamily: 'var(--font-num)', fontSize: 26, fontWeight: 800, color: 'var(--leaf)' }}>
                    {avgInfin.toFixed(1)}
                  </span>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* ── 상세 로그 ── */}
      <div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '0.14em', textTransform: 'uppercase' }}>
            모드별 기록
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            <button onClick={() => setActiveTab('all')} style={{ padding: '6px 12px', background: activeTab === 'all' ? 'var(--ink)' : 'transparent', color: activeTab === 'all' ? 'var(--paper)' : 'var(--ink-soft)', border: '1px solid var(--hairline)', borderRadius: 999, cursor: 'pointer', fontSize: 13 }}>전체</button>
            <button onClick={() => setActiveTab('2min')} style={{ padding: '6px 12px', background: activeTab === '2min' ? 'var(--ink)' : 'transparent', color: activeTab === '2min' ? 'var(--paper)' : 'var(--ink-soft)', border: '1px solid var(--hairline)', borderRadius: 999, cursor: 'pointer', fontSize: 13 }}>2분</button>
            <button onClick={() => setActiveTab('infinite')} style={{ padding: '6px 12px', background: activeTab === 'infinite' ? 'var(--ink)' : 'transparent', color: activeTab === 'infinite' ? 'var(--paper)' : 'var(--ink-soft)', border: '1px solid var(--hairline)', borderRadius: 999, cursor: 'pointer', fontSize: 13 }}>무한</button>
          </div>
        </div>
        <div style={{
          background: 'var(--paper)', borderRadius: 16,
          border: '1px solid var(--hairline)', overflow: 'auto'
        }}>
          {isMobile ? (
            // 모바일: 카드형 (모드명 + 최고점수)
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {filteredRecords.length === 0 ? (
                <div style={{ padding: 40, textAlign: 'center', color: 'var(--ink-mute)' }}>기록이 없습니다.</div>
              ) : filteredRecords.map(([key, r], i) => {
                const parts = key.split('_');
                const timeLabel = parts[0] === '120' ? '2분' : '무한';
                const modeLabel = `${timeLabel} · ${parts[1]} · ${parts[3] === 'original' ? '오리지널' : '10의 배수'}`;
                return (
                  <div key={key} style={{
                    display: 'flex', alignItems: 'center', gap: 12,
                    padding: '12px 16px', borderBottom: '1px solid var(--hairline)'
                  }}>
                    <AppleCell n={(i % 9) + 1} size={24} shape="realistic" leaf={false} />
                    <span style={{
                      flex: 1, fontWeight: 600, fontSize: 13,
                      overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'
                    }}>{modeLabel}</span>
                    <span style={{
                      fontFamily: 'var(--font-num)', fontSize: 20,
                      color: 'var(--apple)', fontWeight: 800
                    }}>{(r.highScore ?? 0).toLocaleString()}</span>
                  </div>
                );
              })}
            </div>
          ) : (
            // 태블릿·데스크탑: 기존 테이블
            <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 420 }}>
              <thead>
                <tr style={{
                  background: 'var(--paper-warm)', borderBottom: '1.5px solid var(--ink)',
                  fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.2em',
                  textTransform: 'uppercase', color: 'var(--ink-soft)', textAlign: 'left'
                }}>
                  <th style={{ padding: '12px 20px' }}>MODE</th>
                  <th style={{ padding: '12px 20px' }}>PLAYS</th>
                  <th style={{ padding: '12px 20px' }}>BEST</th>
                  <th style={{ padding: '12px 20px' }}>AVG</th>
                </tr>
              </thead>
              <tbody>
                {filteredRecords.length === 0 ? (
                  <tr><td colSpan="4" style={{ padding: 40, textAlign: 'center', color: 'var(--ink-mute)' }}>기록이 없습니다.</td></tr>
                ) : filteredRecords.map(([key, r], i) => {
                  const parts = key.split('_');
                  const timeLabel = parts[0] === '120' ? '2분' : '무한';
                  const modeLabel = `${timeLabel} · ${parts[1]} · ${parts[3] === 'original' ? '오리지널' : '10의 배수'}`;
                  return (
                    <tr key={key} style={{ borderBottom: '1px solid var(--hairline)' }}>
                      <td style={{ padding: '14px 20px', display: 'flex', alignItems: 'center', gap: 10 }}>
                        <AppleCell n={(i % 9) + 1} size={26} shape="realistic" leaf={false} />
                        <span style={{ fontWeight: 600, fontSize: 14 }}>{modeLabel}</span>
                      </td>
                      <td style={{ padding: '14px 20px', fontFamily: 'var(--font-num)', fontSize: 20 }}>{r.playCount}</td>
                      <td style={{ padding: '14px 20px', fontFamily: 'var(--font-num)', fontSize: 20, color: 'var(--apple)' }}>{r.highScore}</td>
                      <td style={{ padding: '14px 20px', fontFamily: 'var(--font-num)', fontSize: 20, color: 'var(--ink-soft)' }}>{(r.totalScore / r.playCount).toFixed(1)}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </div>
    </>
  );
}


function LeaderboardScreen({ leaderboard, onMain, onRefresh, filters, onFilterChange, breakpoint }) {
  const { isMobile, isUltrawide } = breakpoint || {};
  return (
    <>
    <style>{`
      .lb-layout { padding: clamp(20px, 4vw, 36px) clamp(20px, 5vw, 44px); }
      .lb-header { flex-direction: row; }
      @media (max-width: 800px) {
        .lb-header { flex-direction: column; gap: 16px; }
        .lb-controls { width: 100%; flex-wrap: wrap; justify-content: flex-start; }
      }
    `}</style>
    <div className="lb-layout" style={{
      width: '100%', height: '100%', background: 'var(--paper)',
      display: 'flex', flexDirection: 'column', gap: 24,
      fontFamily: 'var(--font-body)', overflow: 'hidden',
      maxWidth: isUltrawide ? 1400 : '100%',
      margin: isUltrawide ? '0 auto' : undefined,
      boxSizing: 'border-box',
    }}>
      <div className="lb-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--gold)', letterSpacing: '0.22em', textTransform: 'uppercase' }}>● 글로벌 랭킹 · LEADERBOARD</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(32px, 6vw, 48px)', color: 'var(--ink)', fontWeight: 700, marginTop: 4, lineHeight: 1 }}>
            명예의 전당.
          </div>
        </div>
        <div className="lb-controls" style={{ display: 'flex', gap: 8 }}>
           <select value={filters.time} onChange={(e) => onFilterChange('time', e.target.value)} style={{ padding: '8px', borderRadius: 8, border: '1px solid var(--hairline)', flex: '1 1 120px' }}>
             <option value="120">2분 모드</option>
             <option value="infinite">무한 모드</option>
           </select>
           <select value={filters.size} onChange={(e) => onFilterChange('size', e.target.value)} style={{ padding: '8px', borderRadius: 8, border: '1px solid var(--hairline)', flex: '1 1 120px' }}>
             <option value="17x10">17x10</option>
             <option value="50x50">50x50</option>
           </select>
           <select value={filters.clearType} onChange={(e) => onFilterChange('clearType', e.target.value)} style={{ padding: '8px', borderRadius: 8, border: '1px solid var(--hairline)', flex: '1 1 120px' }}>
             <option value="original">오리지널</option>
             <option value="multiples">10의 배수</option>
           </select>
           <select value={filters.sort} onChange={(e) => onFilterChange('sort', e.target.value)} style={{ padding: '8px', borderRadius: 8, border: '1px solid var(--hairline)', flex: '1 1 120px' }}>
             <option value="highScore">최고 점수 순</option>
             <option value="playCount">판수 순</option>
           </select>
           <button onClick={onRefresh} style={{ padding: '8px 14px', background: 'var(--ink)', color: 'var(--paper)', border: 'none', borderRadius: 8, cursor: 'pointer', whiteSpace: 'nowrap' }}>조회</button>
           <button onClick={onMain} style={{ marginLeft: 'auto', padding: '10px 18px', background: 'transparent', border: '1.5px solid var(--hairline)', borderRadius: 12, color: 'var(--ink-soft)', fontSize: 14, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap' }}>메인으로</button>
        </div>
      </div>

      <div style={{
        background: 'var(--paper)', borderRadius: 16,
        border: '1px solid var(--hairline)', overflow: 'auto', flex: 1
      }}>
        {isMobile ? (
          // 모바일: 카드형 (순위 + 이름 + 최고점수)
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {leaderboard.length === 0 ? (
              <div style={{ padding: 40, textAlign: 'center', color: 'var(--ink-mute)' }}>
                데이터를 불러오거나 기록이 없습니다.
              </div>
            ) : leaderboard.map((data, i) => (
              <div key={data.uid || data.name || i} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '14px 16px',
                background: i < 3 ? 'rgba(233,196,106,0.06)' : 'transparent',
                borderBottom: '1px solid var(--hairline)'
              }}>
                <span style={{
                  fontFamily: 'var(--font-num)', fontSize: 20,
                  color: i === 0 ? 'var(--gold)' : 'var(--ink)',
                  minWidth: 28, textAlign: 'center'
                }}>
                  {i === 0 ? '🥇' : i === 1 ? '🥈' : i === 2 ? '🥉' : i + 1}
                </span>
                <span style={{
                  flex: 1, fontWeight: 600, fontSize: 15,
                  overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'
                }}>{data.name}</span>
                <span style={{
                  fontFamily: 'var(--font-num)', fontSize: 22,
                  color: 'var(--apple)', fontWeight: 800
                }}>{(data.highScore ?? 0).toLocaleString()}</span>
              </div>
            ))}
          </div>
        ) : (
          // 태블릿·데스크탑: 기존 테이블
          <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 500 }}>
            <thead>
              <tr style={{
                background: 'var(--paper-warm)', borderBottom: '1.5px solid var(--ink)',
                fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.2em',
                textTransform: 'uppercase', color: 'var(--ink-soft)', textAlign: 'left'
              }}>
                <th style={{ padding: '14px 22px', width: 80 }}>RANK</th>
                <th style={{ padding: '14px 22px' }}>NAME</th>
                <th style={{ padding: '14px 22px' }}>SCORE</th>
                <th style={{ padding: '14px 22px' }}>PLAYS</th>
              </tr>
            </thead>
            <tbody>
              {leaderboard.length === 0 ? (
                <tr><td colSpan="4" style={{ padding: 40, textAlign: 'center', color: 'var(--ink-mute)' }}>데이터를 불러오거나 기록이 없습니다.</td></tr>
              ) : leaderboard.map((data, i) => (
                <tr key={i} style={{ borderBottom: '1px solid var(--hairline)', background: i < 3 ? 'rgba(233,196,106,0.05)' : 'transparent' }}>
                  <td style={{ padding: '16px 22px', fontFamily: 'var(--font-num)', fontSize: 24, color: i === 0 ? 'var(--gold)' : 'var(--ink)' }}>
                    {i === 0 ? '🥇' : i === 1 ? '🥈' : i === 2 ? '🥉' : i + 1}
                  </td>
                  <td style={{ padding: '16px 22px', fontWeight: 600 }}>{data.name}</td>
                  <td style={{ padding: '16px 22px', fontFamily: 'var(--font-num)', fontSize: 28, color: 'var(--apple)' }}>{(data.highScore ?? 0).toLocaleString()}</td>
                  <td style={{ padding: '16px 22px', color: 'var(--ink-mute)' }}>{data.playCount} 회</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
    </>
  );
}

Object.assign(window, { ResultScreen, RecordsScreen, LeaderboardScreen });
