/* ============================================================
   画面: 4人見比べ ＆ ランキング（ポイント集計）
   ============================================================ */

// ===== 見比べ画面 ===========================================
function CompareScreen({ T, state, goTab }) {
  const M = window.WC.MEMBERS;

  // ある項目で同じ予想をしている人数 → 一致ハイライト用
  const tally = (getter) => {
    const map = {};
    M.forEach(m => { const v = getter(state.preds[m.id]); if (v) map[v] = (map[v] || 0) + 1; });
    return map;
  };

  const Section = ({ title, sub, color, icon, getter, isTeam }) => {
    const counts = tally(getter);
    return (
      <div style={{ marginBottom: 8 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '0 4px 10px' }}>
          <Icon name={icon} size={18} color={color} />
          <span style={{ fontWeight: 800, fontSize: 16, color: T.text }}>{title}</span>
          <span style={{ fontFamily: 'Archivo', fontWeight: 700, fontSize: 10,
            letterSpacing: 1.4, color: T.faint, whiteSpace: 'nowrap' }}>{sub}</span>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {M.map(m => {
            const v = getter(state.preds[m.id]);
            const team = isTeam ? window.WC.TEAM[v] : null;
            const agree = v && counts[v] > 1;
            return (
              <div key={m.id} style={{
                display: 'flex', alignItems: 'center', gap: 12, background: T.card,
                borderRadius: 16, padding: '11px 14px',
                boxShadow: `inset 0 0 0 1px ${agree ? color + '4D' : T.line}` }}>
                <Avatar m={m} size={30} T={T} />
                <span style={{ fontWeight: 700, color: T.sub, fontSize: 14, width: 52 }}>{m.name}</span>
                <span style={{ fontSize: 22 }}>{isTeam ? (team ? team.flag : '🏳️') : '⚽️'}</span>
                <span style={{ fontWeight: 800, color: T.text, fontSize: 15.5, flex: 1,
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {isTeam ? (team ? team.ja : '未選択') : (v || '未選択')}</span>
                {agree && (
                  <span style={{
                    fontFamily: 'Archivo', fontWeight: 800, fontSize: 10, letterSpacing: 0.6,
                    color: color, background: `${color}1F`, padding: '3px 7px', borderRadius: 6 }}>
                    {counts[v]}人一致</span>
                )}
              </div>
            );
          })}
        </div>
      </div>
    );
  };

  return (
    <div style={{ padding: '4px 16px 16px' }}>
      <Eyebrow T={T}>COMPARE</Eyebrow>
      <div style={{ fontSize: 23, fontWeight: 800, color: T.text, marginTop: 3, marginBottom: 16 }}>
        4人の予想を見比べ</div>
      <Section title="優勝" sub="CHAMPION" color={T.gold} icon="trophy"
        getter={p => p.champion} isTeam />
      <Section title="準優勝" sub="RUNNER-UP" color={T.silver} icon="medal"
        getter={p => p.runnerUp} isTeam />
      <Section title="得点王" sub="TOP SCORER" color={T.boot} icon="boot"
        getter={p => p.topScorer} isTeam={false} />

      <button onClick={() => goTab('rank')} style={{
        marginTop: 10, width: '100%', border: 'none', borderRadius: 16, padding: '15px',
        cursor: 'pointer', background: T.accent, color: T.accentInk, fontSize: 16,
        fontWeight: 800, fontFamily: 'inherit', display: 'flex', alignItems: 'center',
        justifyContent: 'center', gap: 8 }}>
        <Icon name="medal" size={19} color={T.accentInk} />ランキングを見る
      </button>
    </div>
  );
}

// ===== ランキング画面 =======================================
function RankingScreen({ T, state }) {
  const M = window.WC.MEMBERS;
  const R = window.WC.RESULT;
  const scored = M.map(m => ({ m, s: window.WC.scoreMember(state.preds[m.id]) }))
    .sort((a, b) => b.s.total - a.s.total);
  const [open, setOpen] = React.useState(null);
  const maxTotal = Math.max(1, ...scored.map(x => x.s.total));
  const rankColor = i => i === 0 ? T.gold : i === 1 ? T.silver : i === 2 ? T.boot : T.faint;

  const HitBadge = ({ ok, label }) => (
    <div style={{ display: 'flex', alignItems: 'center', gap: 3, opacity: ok ? 1 : 0.4 }}>
      <Icon name={ok ? 'check' : 'close'} size={12} color={ok ? T.accent : T.faint} sw={2.6} />
      <span style={{ fontSize: 11, fontWeight: 700, color: ok ? T.text : T.faint }}>{label}</span>
    </div>
  );

  return (
    <div style={{ padding: '4px 16px 16px' }}>
      <Eyebrow T={T}>RANKING</Eyebrow>
      <div style={{ fontSize: 23, fontWeight: 800, color: T.text, marginTop: 3 }}>
        予想の的中ランキング</div>

      {/* サンプル結果バナー */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, background: T.panel2,
        borderRadius: 14, padding: '11px 13px', margin: '12px 0 16px' }}>
        <Icon name="flame" size={17} color={T.accent} />
        <div style={{ fontSize: 12, color: T.sub, lineHeight: 1.45 }}>
          <b style={{ color: T.text }}>サンプル結果</b>で集計中 ·
          優勝 {window.WC.TEAM[R.champion].flag}{window.WC.TEAM[R.champion].ja} /
          準優勝 {window.WC.TEAM[R.runnerUp].flag}{window.WC.TEAM[R.runnerUp].ja} /
          得点王 {R.topScorer}
        </div>
      </div>

      {/* 表彰台 トップ3 */}
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, marginBottom: 18 }}>
        {[1, 0, 2].map(pos => {
          const item = scored[pos]; if (!item) return <div key={pos} style={{ flex: 1 }} />;
          const h = pos === 0 ? 116 : pos === 1 ? 92 : 78;
          return (
            <div key={pos} style={{ flex: 1, display: 'flex', flexDirection: 'column',
              alignItems: 'center', gap: 7 }}>
              <Avatar m={item.m} size={pos === 0 ? 48 : 40} T={T} />
              <div style={{ fontWeight: 800, fontSize: 13, color: T.text }}>{item.m.name}</div>
              <div style={{
                width: '100%', height: h, borderRadius: '14px 14px 0 0',
                background: `linear-gradient(180deg, ${rankColor(pos)}38, ${T.card})`,
                boxShadow: `inset 0 0 0 1px ${T.line}`,
                display: 'flex', flexDirection: 'column', alignItems: 'center',
                justifyContent: 'flex-start', paddingTop: 12, gap: 2 }}>
                <div style={{ fontFamily: 'Archivo', fontWeight: 900, fontSize: 22,
                  color: rankColor(pos) }}>{pos + 1}</div>
                <div style={{ fontFamily: 'Archivo', fontWeight: 900, fontSize: 26,
                  color: T.text }}>{item.s.total}</div>
                <div style={{ fontSize: 10, color: T.faint, fontWeight: 700 }}>pt</div>
              </div>
            </div>
          );
        })}
      </div>

      {/* 詳細リスト */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {scored.map((item, i) => {
          const p = state.preds[item.m.id];
          const isOpen = open === item.m.id;
          return (
            <div key={item.m.id} style={{ background: T.card, borderRadius: 16,
              boxShadow: `inset 0 0 0 1px ${T.line}`, overflow: 'hidden' }}>
              <button onClick={() => setOpen(isOpen ? null : item.m.id)} style={{
                display: 'flex', alignItems: 'center', gap: 12, width: '100%', border: 'none',
                background: 'transparent', cursor: 'pointer', padding: '12px 14px',
                fontFamily: 'inherit', textAlign: 'left' }}>
                <span style={{ fontFamily: 'Archivo', fontWeight: 900, fontSize: 18,
                  color: rankColor(i), width: 22 }}>{i + 1}</span>
                <Avatar m={item.m} size={34} T={T} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 800, color: T.text, fontSize: 15 }}>{item.m.name}</div>
                  {/* 内訳バー */}
                  <div style={{ display: 'flex', height: 6, borderRadius: 4, overflow: 'hidden',
                    marginTop: 5, background: T.panel2, width: 130 }}>
                    {[['champion', T.gold], ['runnerUp', T.silver], ['topScorer', T.boot],
                      ['bracket', T.accent]].map(([k, c]) => (
                      <div key={k} style={{ width: `${(item.s[k] / maxTotal) * 100}%`,
                        background: c }} />
                    ))}
                  </div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <span style={{ fontFamily: 'Archivo', fontWeight: 900, fontSize: 22,
                    color: T.text }}>{item.s.total}</span>
                  <span style={{ fontSize: 11, color: T.faint, fontWeight: 700 }}> pt</span>
                </div>
                <div style={{ transform: isOpen ? 'rotate(90deg)' : 'none', transition: '.2s' }}>
                  <Icon name="chevron" size={16} color={T.faint} />
                </div>
              </button>
              {isOpen && (
                <div style={{ padding: '0 14px 14px 48px' }}>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, marginBottom: 10 }}>
                    <HitBadge ok={p.champion === R.champion}
                      label={`優勝 +${item.s.champion}`} />
                    <HitBadge ok={p.runnerUp === R.runnerUp}
                      label={`準優勝 +${item.s.runnerUp}`} />
                    <HitBadge ok={p.topScorer && p.topScorer.trim() === R.topScorer.trim()}
                      label={`得点王 +${item.s.topScorer}`} />
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <Icon name="bracket" size={15} color={T.accent} />
                    <span style={{ fontSize: 12.5, color: T.sub }}>
                      トーナメント的中 <b style={{ color: T.text }}>+{item.s.bracket}pt</b>
                      <span style={{ color: T.faint }}> （16強{item.s.bracketHits.r16}・8強{item.s.bracketHits.qf}・4強{item.s.bracketHits.sf}・決勝{item.s.bracketHits.final}）</span>
                    </span>
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>

      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, marginTop: 16,
        padding: '12px 14px', background: T.panel2, borderRadius: 14 }}>
        {[['優勝', T.gold, '+25'], ['準優勝', T.silver, '+15'], ['得点王', T.boot, '+20'],
          ['トーナメント', T.accent, '+2〜10']].map(([l, c, v]) => (
          <div key={l} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <div style={{ width: 10, height: 10, borderRadius: 3, background: c }} />
            <span style={{ fontSize: 12, color: T.sub, fontWeight: 600 }}>{l}</span>
            <span style={{ fontFamily: 'Archivo', fontSize: 11, fontWeight: 700, color: T.faint }}>{v}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { CompareScreen, RankingScreen });
