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 { t } from '../../../core/i18n.js';
import { emoji } from '../../../core/theme.js';

let activeTab = 'info';
let tournamentData = null;

export async function mountTournamentDetail(el, params) {
  const { tournamentId } = params;
  activeTab = 'info';

  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 id="tour-title" style="font-size:15px;font-weight:700;color:#f8fafc;flex:1;">بطولة</span>
      </div>
      <!-- Tabs -->
      <div style="display:flex;background:#0f0f1e;border-bottom:1px solid rgba(255,255,255,0.04);padding:0 8px;overflow-x:auto;">
        <button class="tour-tab active" data-tab="info">معلومات</button>
        <button class="tour-tab" data-tab="standings">الترتيب</button>
        <button class="tour-tab" data-tab="rounds">الجولات</button>
        <button class="tour-tab" data-tab="my-games">مبارياتي</button>
        <button class="tour-tab" data-tab="bracket" id="tab-bracket" style="display:none;">الشجرة</button>
        <button class="tour-tab" data-tab="arena" id="tab-arena" style="display:none;">أرينا</button>
      </div>
      <!-- Content -->
      <div id="tour-content" style="flex:1;overflow-y:auto;padding:14px;"></div>
    </div>
    <style>
      .tour-tab { background:none;border:none;color:#64748b;font-size:13px;font-weight:600;padding:10px 14px;cursor:pointer;border-bottom:2px solid transparent;font-family:inherit; }
      .tour-tab.active { color:#E4AC38;border-bottom-color:#E4AC38; }
      .tour-tab:active { opacity:0.7; }
      .standing-row { display:flex;align-items:center;padding:8px 0;border-bottom:1px solid rgba(255,255,255,0.04); }
      .pairing-row { display:flex;align-items:center;justify-content:space-between;padding:10px;background:#1a1a2e;border-radius:8px;margin-bottom:6px; }
    </style>
  `;

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

  // Tab switching
  el.querySelectorAll('.tour-tab').forEach(tab => {
    tab.addEventListener('click', () => {
      audio.play('click');
      el.querySelectorAll('.tour-tab').forEach(t => t.classList.remove('active'));
      tab.classList.add('active');
      activeTab = tab.dataset.tab;
      loadTab(el, tournamentId, activeTab);
    });
  });

  // Load tournament info
  loadTab(el, tournamentId, 'info');
}

async function loadTab(el, tournamentId, tab) {
  // Bracket and Arena push to dedicated scenes
  if (tab === 'bracket') {
    scene.push('tournament-bracket', { tournamentId });
    return;
  }
  if (tab === 'arena') {
    scene.push('tournament-arena', { tournamentId, tournamentName: tournamentData?.name });
    return;
  }

  const content = el.querySelector('#tour-content');
  content.innerHTML = '<div style="text-align:center;color:#64748b;padding:24px;">جاري التحميل...</div>';

  switch (tab) {
    case 'info': await loadInfo(content, tournamentId, el); break;
    case 'standings': await loadStandings(content, tournamentId); break;
    case 'rounds': await loadRounds(content, tournamentId); break;
    case 'my-games': await loadMyGames(content, tournamentId); break;
  }
}

async function loadInfo(content, tournamentId, el) {
  try {
    const data = await net.get('swiss.php', { action: 'tournament', id: tournamentId });
    if (data.error) throw new Error(data.error);
    tournamentData = data;

    el.querySelector('#tour-title').textContent = data.name || 'بطولة';

    // Show format-specific tabs
    const format = data.format || '';
    if (format === 'single_elimination' || format === 'double_elimination' || format === 'group_stage') {
      const bracketTab = el.querySelector('#tab-bracket');
      if (bracketTab) bracketTab.style.display = '';
    }
    if (format === 'arena') {
      const arenaTab = el.querySelector('#tab-arena');
      if (arenaTab) arenaTab.style.display = '';
    }

    const statusColors = { registration: '#34D399', in_progress: '#E4AC38', completed: '#64748b', draft: '#3B82F6' };
    const statusLabels = { registration: 'تسجيل مفتوح', in_progress: 'جارية', completed: 'منتهية', draft: 'قريباً' };

    content.innerHTML = `
      <div style="text-align:center;margin-bottom:16px;">
        <div style="font-size:20px;font-weight:800;color:#f8fafc;margin-bottom:4px;">${data.name || ''}</div>
        <span style="display:inline-block;padding:4px 12px;border-radius:99px;background:${statusColors[data.status] || '#64748b'};color:#000;font-size:11px;font-weight:700;">${statusLabels[data.status] || data.status}</span>
      </div>

      <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:16px;">
        <div style="background:#1a1a2e;border-radius:10px;padding:12px;text-align:center;">
          <div style="font-size:22px;font-weight:800;color:#E4AC38;">${data.player_count || 0}</div>
          <div style="font-size:11px;color:#64748b;">لاعبين</div>
        </div>
        <div style="background:#1a1a2e;border-radius:10px;padding:12px;text-align:center;">
          <div style="font-size:22px;font-weight:800;color:#3B82F6;">${data.rounds_total || data.swiss_rounds || '?'}</div>
          <div style="font-size:11px;color:#64748b;">جولات</div>
        </div>
        <div style="background:#1a1a2e;border-radius:10px;padding:12px;text-align:center;">
          <div style="font-size:22px;font-weight:800;color:#f8fafc;">${data.format || 'swiss'}</div>
          <div style="font-size:11px;color:#64748b;">النظام</div>
        </div>
        <div style="background:#1a1a2e;border-radius:10px;padding:12px;text-align:center;">
          <div style="font-size:22px;font-weight:800;color:#10B981;">${data.time_control || '?'}</div>
          <div style="font-size:11px;color:#64748b;">الوقت</div>
        </div>
      </div>

      ${data.prize_pool_coins ? `<div style="background:#1a1a2e;border-radius:10px;padding:14px;text-align:center;margin-bottom:12px;">
        <div style="font-size:12px;color:#64748b;margin-bottom:4px;">الجوائز</div>
        <div style="font-size:20px;font-weight:800;color:#E4AC38;">${data.prize_pool_coins} ${emoji('coin', '🪙', 20)}</div>
      </div>` : ''}

      ${data.starts_at ? `<div style="text-align:center;color:#94a3b8;font-size:12px;margin-bottom:16px;">
        📅 ${new Date(data.starts_at).toLocaleDateString('ar')} — ${new Date(data.starts_at).toLocaleTimeString('ar', { hour: '2-digit', minute: '2-digit' })}
      </div>` : ''}

      ${data.status === 'registration' ? `
        <button class="btn btn-primary w-full" id="register-btn" style="font-size:16px;padding:16px;">${emoji('swords', '⚔️', 16)} سجّل الآن</button>
      ` : ''}
    `;

    content.querySelector('#register-btn')?.addEventListener('click', async () => {
      const btn = content.querySelector('#register-btn');
      btn.disabled = true;
      btn.textContent = 'جاري التسجيل...';
      try {
        await net.post('tournaments.php', { action: 'register', tournament_id: tournamentId });
        btn.textContent = '✅ تم التسجيل';
        btn.style.background = '#34D399';
      } catch (e) {
        btn.textContent = e.message || 'فشل';
        btn.disabled = false;
      }
    });
  } catch (e) {
    content.innerHTML = `<div style="text-align:center;color:#ef4444;padding:24px;">فشل تحميل البطولة</div>`;
  }
}

async function loadStandings(content, tournamentId) {
  try {
    const data = await net.get('swiss.php', { action: 'standings', tournament_id: tournamentId });
    const standings = data.standings || [];

    if (standings.length === 0) {
      content.innerHTML = '<div style="text-align:center;color:#64748b;padding:32px;">لا توجد نتائج بعد — ستظهر بعد بدء الجولات</div>';
      return;
    }

    content.innerHTML = `
      <div style="display:flex;padding:6px 0;border-bottom:1px solid rgba(255,255,255,0.06);color:#64748b;font-size:11px;font-weight:600;">
        <span style="width:30px;">#</span>
        <span style="flex:1;">اللاعب</span>
        <span style="width:40px;text-align:center;">نقاط</span>
        <span style="width:40px;text-align:center;">بوخ</span>
      </div>
      ${standings.map((p, i) => `
        <div class="standing-row">
          <span style="width:30px;font-weight:700;color:${i < 3 ? '#E4AC38' : '#94a3b8'};font-size:13px;">${i + 1}</span>
          <span style="flex:1;font-size:13px;color:#f8fafc;font-weight:500;">${p.name || p.player_name || 'Player'}</span>
          <span style="width:40px;text-align:center;font-weight:700;color:#f8fafc;font-size:13px;">${p.score ?? p.points ?? '0'}</span>
          <span style="width:40px;text-align:center;font-size:11px;color:#64748b;">${p.buchholz ?? ''}</span>
        </div>
      `).join('')}
    `;
  } catch (e) {
    content.innerHTML = '<div style="text-align:center;color:#ef4444;">فشل تحميل الترتيب</div>';
  }
}

async function loadRounds(content, tournamentId) {
  try {
    const data = await net.get('swiss.php', { action: 'rounds', tournament_id: tournamentId });
    const rounds = data.rounds || [];
    const userId = store.get('auth.userId');

    if (rounds.length === 0) {
      content.innerHTML = '<div style="text-align:center;color:#64748b;padding:32px;">لم تبدأ الجولات بعد</div>';
      return;
    }

    content.innerHTML = rounds.map(r => `
      <div style="margin-bottom:16px;">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
          <span style="font-size:14px;font-weight:700;color:#f8fafc;">الجولة ${r.round_number}</span>
          <span style="font-size:11px;padding:3px 8px;border-radius:99px;background:${r.status === 'completed' ? '#64748b' : r.status === 'in_progress' ? '#E4AC38' : '#3B82F6'};color:#000;font-weight:600;">${r.status === 'completed' ? 'منتهية' : r.status === 'in_progress' ? 'جارية' : 'قادمة'}</span>
        </div>
        <div id="round-pairings-${r.id}" style="font-size:12px;color:#64748b;">اضغط لعرض التقابلات</div>
      </div>
    `).join('');

    rounds.forEach(r => {
      const el = content.querySelector(`#round-pairings-${r.id}`);
      if (el) {
        el.style.cursor = 'pointer';
        el.addEventListener('click', async () => {
          el.textContent = 'جاري التحميل...';
          try {
            const pd = await net.get('swiss.php', { action: 'pairings', round_id: r.id });
            const pairings = pd.pairings || [];
            if (pairings.length === 0) { el.textContent = 'لا توجد تقابلات'; return; }

            el.innerHTML = pairings.map((p, idx) => {
              const playerA = p.player_a || p.white_id || '';
              const playerB = p.player_b || p.black_id || '';
              const isMyPairing = (userId === playerA || userId === playerB);
              const canPlay = isMyPairing && r.status === 'in_progress' && !p.result;

              return `
                <div class="pairing-row" style="${isMyPairing ? 'border:1px solid #E4AC38;' : ''}">
                  <span style="flex:1;font-size:12px;color:#f8fafc;">${p.white_name || p.player_a || '?'}</span>
                  <span style="padding:2px 8px;background:#1e1e3a;border-radius:4px;font-size:11px;font-weight:700;color:#E4AC38;">${p.result || 'vs'}</span>
                  <span style="flex:1;text-align:left;font-size:12px;color:#f8fafc;">${p.black_name || p.player_b || '?'}</span>
                  ${canPlay ? `<button class="play-pairing-btn" data-round-id="${r.id}" data-idx="${idx}" style="margin-right:8px;padding:4px 12px;background:#E4AC38;border:none;border-radius:6px;color:#000;font-weight:700;font-size:11px;cursor:pointer;">العب</button>` : ''}
                </div>
              `;
            }).join('');

            el.querySelectorAll('.play-pairing-btn').forEach(btn => {
              btn.addEventListener('click', (e) => {
                e.stopPropagation();
                audio.play('click');
                launchTournamentMatch(tournamentId, btn.dataset.roundId, parseInt(btn.dataset.idx));
              });
            });
          } catch (e) {
            el.textContent = 'فشل التحميل';
          }
        });
      }
    });
  } catch (e) {
    content.innerHTML = '<div style="text-align:center;color:#ef4444;">فشل تحميل الجولات</div>';
  }
}

async function loadMyGames(content, tournamentId) {
  const userId = store.get('auth.userId');

  try {
    // Fetch both completed games and pending matches
    const [gamesData, pendingData] = await Promise.all([
      net.get('swiss.php', { action: 'my-games', tournament_id: tournamentId }),
      net.get('tournament-match.php', { action: 'my-pending' })
    ]);

    const games = gamesData.games || [];
    const allPending = (pendingData.pending || []).filter(p => p.tournament_id === tournamentId);

    if (games.length === 0 && allPending.length === 0) {
      content.innerHTML = '<div style="text-align:center;color:#64748b;padding:32px;">لم تلعب مباريات في هذه البطولة بعد</div>';
      return;
    }

    let html = '';

    // Pending matches first (with Play button)
    if (allPending.length > 0) {
      html += `<div style="margin-bottom:14px;font-size:13px;font-weight:700;color:#E4AC38;">مباريات جاهزة</div>`;
      html += allPending.map(p => {
        if (p.is_bye) {
          return `<div class="pairing-row" style="border:1px solid #64748b;">
            <span style="font-size:12px;color:#64748b;">ج${p.round_number}</span>
            <span style="font-size:12px;color:#94a3b8;flex:1;margin:0 8px;">إجازة — نقطة كاملة</span>
            <span style="font-size:11px;color:#34D399;">BYE ✓</span>
          </div>`;
        }
        return `<div class="pairing-row" style="border:1px solid #E4AC38;">
          <span style="font-size:12px;color:#64748b;">ج${p.round_number}</span>
          <span style="font-size:12px;color:#f8fafc;flex:1;margin:0 8px;">vs ${p.opponent_name || 'خصم'}</span>
          <button class="play-pending-btn" data-tid="${p.tournament_id}" data-rid="${p.round_id}" data-idx="${p.pairing_index}" style="padding:6px 16px;background:#E4AC38;border:none;border-radius:8px;color:#000;font-weight:700;font-size:12px;cursor:pointer;">العب</button>
        </div>`;
      }).join('');
    }

    // Completed games
    if (games.length > 0) {
      html += `<div style="margin-bottom:8px;margin-top:14px;font-size:13px;font-weight:700;color:#94a3b8;">المباريات السابقة</div>`;
      html += games.map(g => {
        const isWhite = g.white_player_id === userId;
        let resultText = g.status;
        let resultColor = '#94a3b8';
        if (g.result === 'white_wins') { resultText = isWhite ? 'فوز' : 'خسارة'; resultColor = isWhite ? '#34D399' : '#ef4444'; }
        else if (g.result === 'black_wins') { resultText = isWhite ? 'خسارة' : 'فوز'; resultColor = isWhite ? '#ef4444' : '#34D399'; }
        else if (g.result === 'draw') { resultText = 'تعادل'; resultColor = '#E4AC38'; }

        return `<div class="pairing-row">
          <span style="font-size:12px;color:#64748b;">ج${g.tournament_round || '?'}</span>
          <span style="font-size:12px;color:#f8fafc;flex:1;margin:0 8px;">${g.result || g.status}</span>
          <span style="font-size:11px;color:${resultColor};font-weight:600;">${resultText}</span>
        </div>`;
      }).join('');
    }

    content.innerHTML = html;

    // Attach Play button handlers
    content.querySelectorAll('.play-pending-btn').forEach(btn => {
      btn.addEventListener('click', () => {
        audio.play('click');
        launchTournamentMatch(btn.dataset.tid, btn.dataset.rid, parseInt(btn.dataset.idx));
      });
    });
  } catch (e) {
    content.innerHTML = '<div style="text-align:center;color:#ef4444;">فشل التحميل</div>';
  }
}

async function launchTournamentMatch(tournamentId, roundId, pairingIndex) {
  try {
    const data = await net.post('tournament-match.php', {
      action: 'create-or-join',
      tournament_id: tournamentId,
      round_id: roundId,
      pairing_index: pairingIndex
    });

    if (data.error) throw new Error(data.error);
    if (data.bye) { audio.play('reward'); return; }

    const tc = data.time_control || 'rapid_10_0';
    const gameKey = tournamentData?.game_key || 'chess';
    const gameScene = gameKey === 'chess' ? 'chess-game' : gameKey + '-game';

    scene.push(gameScene, {
      mode: 'live',
      matchId: data.match_id,
      color: data.color,
      timeControl: tc,
      opponentId: data.opponent_id,
      tournamentId,
      tournamentRound: pairingIndex,
      recovered: data.already_exists && data.status === 'in_progress'
    });
  } catch (e) {
    console.error('[tournament] launch error:', e);
  }
}
