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';

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:#0a0a1a;">
      <div style="display:flex;align-items:center;gap:12px;padding:10px 14px;background:#0f0f1e;border-bottom:1px solid rgba(255,255,255,0.06);">
        <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:#f8fafc;">الشجرة</span>
      </div>
      <div id="bracket-container" style="flex:1;overflow:auto;padding:12px;">
        <div style="text-align:center;color:#64748b;padding:32px;">جاري التحميل...</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:#64748b;padding:32px;">لا توجد شجرة بعد</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:#64748b;margin-bottom:8px;">${roundLabels[r - 1] || 'دور ' + r}</div>`;

      matches.forEach(m => {
        const isMyMatch = (m.player_a_id === userId || m.player_b_id === userId);
        const borderColor = isMyMatch ? '#E4AC38' : 'rgba(255,255,255,0.06)';
        const statusBg = m.status === 'completed' ? '#1a2e1a' : m.status === 'in_progress' ? '#2e2a1a' : '#1a1a2e';

        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:#E4AC38;color:#000;padding:1px 4px;border-radius:4px;font-weight:700;">أنت</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 ? '#34D399' : '#f8fafc'};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:#64748b;">${m.result ? m.result.split('-')[0] : ''}</span>
            </div>
            <div style="height:1px;background:rgba(255,255,255,0.04);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 ? '#34D399' : '#f8fafc'};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:#64748b;">${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:#E4AC38;border:none;border-radius:4px;color:#000;font-weight:700;font-size:10px;cursor:pointer;">العب</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:#ef4444;padding:32px;">فشل تحميل الشجرة</div>';
  }
}

function getRoundLabels(totalRounds) {
  const labels = [];
  for (let r = 1; r <= totalRounds; r++) {
    const remaining = totalRounds - r;
    if (remaining === 0) labels.push('النهائي');
    else if (remaining === 1) labels.push('نصف النهائي');
    else if (remaining === 2) labels.push('ربع النهائي');
    else labels.push('دور ' + Math.pow(2, remaining + 1));
  }
  return labels;
}
