import * as scene from '../../../core/scene.js';
import * as net from '../../../core/net.js';
import * as audio from '../../../core/audio.js';
import * as store from '../../../core/store.js';
import { emoji } from '../../../core/theme.js';
import { t } from '../../../core/i18n.js';

export async function mountTournamentBracket(el, params) {
  const { tournamentId } = params;
  const userId = store.get('auth.userId');

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;height:100%;background:var(--bg-deep);">
      <div style="display:flex;align-items:center;gap:12px;padding:10px 14px;background:var(--bg-panel);border-bottom:1px solid var(--border);">
        <button class="btn btn-secondary" id="back-btn" style="min-height:32px;padding:4px 12px;font-size:12px;">←</button>
        <span style="font-size:15px;font-weight:700;color:var(--text-primary);">${t('tournament.bracket')}</span>
      </div>
      <div id="bracket-container" style="flex:1;overflow:auto;padding:12px;">
        <div style="text-align:center;color:var(--text-muted);padding:32px;">${t('common.loading')}</div>
      </div>
    </div>
  `;

  el.querySelector('#back-btn').addEventListener('click', () => { audio.play('click'); scene.pop(); });

  try {
    const data = await net.get('swiss.php', { action: 'bracket', tournament_id: tournamentId });
    const container = el.querySelector('#bracket-container');

    if (!data.bracket || !data.matches || data.matches.length === 0) {
      container.innerHTML = `<div style="text-align:center;color:var(--text-muted);padding:32px;">${t('tournament.no_bracket_yet')}</div>`;
      return;
    }

    const totalRounds = data.bracket.total_rounds || Math.max(...data.matches.map(m => m.round));
    const matchesByRound = {};
    for (let r = 1; r <= totalRounds; r++) matchesByRound[r] = [];
    data.matches.forEach(m => {
      if (matchesByRound[m.round]) matchesByRound[m.round].push(m);
    });

    const roundLabels = getRoundLabels(totalRounds);

    let html = `<div style="display:flex;direction:ltr;gap:0;min-width:${totalRounds * 160}px;overflow-x:auto;">`;

    for (let r = totalRounds; r >= 1; r--) {
      const matches = matchesByRound[r] || [];
      const gap = Math.pow(2, totalRounds - r) * 8;

      html += `<div style="display:flex;flex-direction:column;justify-content:space-around;min-width:150px;gap:${gap}px;padding:8px 4px;">`;
      html += `<div style="text-align:center;font-size:11px;font-weight:700;color:var(--text-muted);margin-bottom:8px;">${roundLabels[r - 1] || t('tournament.round', { n: r })}</div>`;

      matches.forEach(m => {
        const isMyMatch = (m.player_a_id === userId || m.player_b_id === userId);
        const borderColor = isMyMatch ? 'var(--gold)' : 'var(--border)';
        const statusBg = m.status === 'completed' ? '#1a2e1a' : m.status === 'in_progress' ? '#2e2a1a' : 'var(--bg-card)';

        html += `
          <div class="bracket-match" data-match-id="${m.match_id || ''}" style="background:${statusBg};border:1px solid ${borderColor};border-radius:8px;padding:6px 8px;position:relative;">
            ${isMyMatch ? `<div style="position:absolute;top:-6px;right:4px;font-size:9px;background:var(--gold);color:#000;padding:1px 4px;border-radius:4px;font-weight:700;">${t('common.you')}</div>` : ''}
            <div style="display:flex;justify-content:space-between;align-items:center;padding:3px 0;${m.winner_id === m.player_a_id ? 'font-weight:700;' : ''}">
              <span style="font-size:11px;color:${m.winner_id === m.player_a_id ? 'var(--success)' : 'var(--text-primary)'};max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${m.player_a_name || (m.player_a_id ? '...' : 'BYE')}</span>
              <span style="font-size:10px;color:var(--text-muted);">${m.result ? m.result.split('-')[0] : ''}</span>
            </div>
            <div style="height:1px;background:var(--border);margin:2px 0;"></div>
            <div style="display:flex;justify-content:space-between;align-items:center;padding:3px 0;${m.winner_id === m.player_b_id ? 'font-weight:700;' : ''}">
              <span style="font-size:11px;color:${m.winner_id === m.player_b_id ? 'var(--success)' : 'var(--text-primary)'};max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${m.player_b_name || (m.player_b_id ? '...' : 'TBD')}</span>
              <span style="font-size:10px;color:var(--text-muted);">${m.result ? m.result.split('-')[1] : ''}</span>
            </div>
            ${m.status === 'pending' && isMyMatch && m.player_a_id && m.player_b_id ? `<button class="bracket-play-btn" data-mid="${m.match_id}" style="width:100%;margin-top:4px;padding:4px;background:var(--gold);border:none;border-radius:4px;color:#000;font-weight:700;font-size:10px;cursor:pointer;">${t('common.play')}</button>` : ''}
          </div>
        `;
      });

      html += '</div>';

      if (r > 1) {
        html += `<div style="display:flex;flex-direction:column;justify-content:space-around;width:16px;">`;
        const connectors = Math.ceil(matches.length / 2);
        for (let c = 0; c < connectors; c++) {
          html += `<div style="border-right:2px solid rgba(255,255,255,0.1);border-top:2px solid rgba(255,255,255,0.1);border-bottom:2px solid rgba(255,255,255,0.1);height:${gap + 40}px;border-radius:0 4px 4px 0;"></div>`;
        }
        html += '</div>';
      }
    }

    html += '</div>';
    container.innerHTML = html;

    container.querySelectorAll('.bracket-play-btn').forEach(btn => {
      btn.addEventListener('click', () => {
        audio.play('click');
        scene.push('tournament-detail', { tournamentId });
      });
    });

  } catch (e) {
    el.querySelector('#bracket-container').innerHTML = `<div style="text-align:center;color:var(--error);padding:32px;">${t('tournament.bracket_load_failed')}</div>`;
  }
}

function getRoundLabels(totalRounds) {
  const labels = [];
  for (let r = 1; r <= totalRounds; r++) {
    const remaining = totalRounds - r;
    if (remaining === 0) labels.push(t('tournament.final'));
    else if (remaining === 1) labels.push(t('tournament.semifinal'));
    else if (remaining === 2) labels.push(t('tournament.quarterfinal'));
    else labels.push(t('tournament.round', { n: Math.pow(2, remaining + 1) }));
  }
  return labels;
}
