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: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 id="tour-title" style="font-size:15px;font-weight:700;color:var(--text-primary);flex:1;">${t('tournament.title')}</span>
      </div>
      <!-- Tabs -->
      <div style="display:flex;background:var(--bg-panel);border-bottom:1px solid var(--border);padding:0 8px;overflow-x:auto;">
        <button class="tour-tab active" data-tab="info">${t('tournament.tab_info')}</button>
        <button class="tour-tab" data-tab="standings">${t('tournament.tab_standings')}</button>
        <button class="tour-tab" data-tab="rounds">${t('tournament.tab_rounds')}</button>
        <button class="tour-tab" data-tab="my-games">${t('tournament.tab_my_games')}</button>
        <button class="tour-tab" data-tab="bracket" id="tab-bracket" style="display:none;">${t('tournament.tab_bracket')}</button>
        <button class="tour-tab" data-tab="arena" id="tab-arena" style="display:none;">${t('tournament.tab_arena')}</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:var(--text-muted);font-size:13px;font-weight:600;padding:10px 14px;cursor:pointer;border-bottom:2px solid transparent;font-family:inherit; }
      .tour-tab.active { color:var(--gold);border-bottom-color:var(--gold); }
      .tour-tab:active { opacity:0.7; }
      .standing-row { display:flex;align-items:center;padding:8px 0;border-bottom:1px solid var(--border); }
      .pairing-row { display:flex;align-items:center;justify-content:space-between;padding:10px;background:var(--bg-card);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:var(--text-muted);padding:24px;">${t('common.loading')}</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 || t('tournament.title');

    // 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: 'var(--success)', in_progress: 'var(--gold)', completed: 'var(--text-muted)', draft: 'var(--blue)' };
    const statusLabels = { registration: t('tournament.registration_open'), in_progress: t('tournament.active'), completed: t('tournament.completed'), draft: t('tournament.coming_soon') };

    content.innerHTML = `
      <div style="text-align:center;margin-bottom:16px;">
        <div style="font-size:20px;font-weight:800;color:var(--text-primary);margin-bottom:4px;">${data.name || ''}</div>
        <span style="display:inline-block;padding:4px 12px;border-radius:99px;background:${statusColors[data.status] || 'var(--text-muted)'};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:var(--bg-card);border-radius:10px;padding:12px;text-align:center;">
          <div style="font-size:22px;font-weight:800;color:var(--gold);">${data.player_count || 0}</div>
          <div style="font-size:11px;color:var(--text-muted);">${t('tournament.players')}</div>
        </div>
        <div style="background:var(--bg-card);border-radius:10px;padding:12px;text-align:center;">
          <div style="font-size:22px;font-weight:800;color:var(--blue);">${data.rounds_total || data.swiss_rounds || '?'}</div>
          <div style="font-size:11px;color:var(--text-muted);">${t('tournament.tab_rounds')}</div>
        </div>
        <div style="background:var(--bg-card);border-radius:10px;padding:12px;text-align:center;">
          <div style="font-size:22px;font-weight:800;color:var(--text-primary);">${data.format || 'swiss'}</div>
          <div style="font-size:11px;color:var(--text-muted);">${t('tournament.format')}</div>
        </div>
        <div style="background:var(--bg-card);border-radius:10px;padding:12px;text-align:center;">
          <div style="font-size:22px;font-weight:800;color:var(--emerald);">${data.time_control || '?'}</div>
          <div style="font-size:11px;color:var(--text-muted);">${t('tournament.time_control')}</div>
        </div>
      </div>

      ${data.prize_pool_coins ? `<div style="background:var(--bg-card);border-radius:10px;padding:14px;text-align:center;margin-bottom:12px;">
        <div style="font-size:12px;color:var(--text-muted);margin-bottom:4px;">${t('tournament.prizes')}</div>
        <div style="font-size:20px;font-weight:800;color:var(--gold);">${data.prize_pool_coins} ${emoji('coin', '🪙', 20)}</div>
      </div>` : ''}

      ${data.starts_at ? `<div style="text-align:center;color:var(--text-secondary);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)} ${t('tournament.register_now')}</button>
      ` : ''}
    `;

    content.querySelector('#register-btn')?.addEventListener('click', async () => {
      const btn = content.querySelector('#register-btn');
      btn.disabled = true;
      btn.textContent = t('tournament.registering');
      try {
        await net.post('tournaments.php', { action: 'register', tournament_id: tournamentId });
        btn.textContent = t('tournament.registered');
        btn.style.background = 'var(--success)';
      } catch (e) {
        btn.textContent = e.message || t('common.failed');
        btn.disabled = false;
      }
    });
  } catch (e) {
    content.innerHTML = `<div style="text-align:center;color:var(--error);padding:24px;">${t('common.error_load')}</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:var(--text-muted);padding:32px;">${t('tournament.no_results')}</div>`;
      return;
    }

    content.innerHTML = `
      <div style="display:flex;padding:6px 0;border-bottom:1px solid var(--border);color:var(--text-muted);font-size:11px;font-weight:600;">
        <span style="width:30px;">#</span>
        <span style="flex:1;">${t('tournament.player_col')}</span>
        <span style="width:40px;text-align:center;">${t('tournament.points_col')}</span>
        <span style="width:40px;text-align:center;">${t('tournament.buchholz_col')}</span>
      </div>
      ${standings.map((p, i) => `
        <div class="standing-row">
          <span style="width:30px;font-weight:700;color:${i < 3 ? 'var(--gold)' : 'var(--text-secondary)'};font-size:13px;">${i + 1}</span>
          <span style="flex:1;font-size:13px;color:var(--text-primary);font-weight:500;">${p.name || p.player_name || 'Player'}</span>
          <span style="width:40px;text-align:center;font-weight:700;color:var(--text-primary);font-size:13px;">${p.score ?? p.points ?? '0'}</span>
          <span style="width:40px;text-align:center;font-size:11px;color:var(--text-muted);">${p.buchholz ?? ''}</span>
        </div>
      `).join('')}
    `;
  } catch (e) {
    content.innerHTML = `<div style="text-align:center;color:var(--error);">${t('common.error_load')}</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:var(--text-muted);padding:32px;">${t('tournament.rounds_not_started')}</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:var(--text-primary);">${t('tournament.round', { n: r.round_number })}</span>
          <span style="font-size:11px;padding:3px 8px;border-radius:99px;background:${r.status === 'completed' ? 'var(--text-muted)' : r.status === 'in_progress' ? 'var(--gold)' : 'var(--blue)'};color:#000;font-weight:600;">${r.status === 'completed' ? t('tournament.completed') : r.status === 'in_progress' ? t('tournament.active') : t('tournament.upcoming')}</span>
        </div>
        <div id="round-pairings-${r.id}" style="font-size:12px;color:var(--text-muted);">${t('tournament.tap_to_expand')}</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 = t('common.loading');
          try {
            const pd = await net.get('swiss.php', { action: 'pairings', round_id: r.id });
            const pairings = pd.pairings || [];
            if (pairings.length === 0) { el.textContent = t('tournament.no_pairings'); 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 var(--gold);' : ''}">
                  <span style="flex:1;font-size:12px;color:var(--text-primary);">${p.white_name || p.player_a || '?'}</span>
                  <span style="padding:2px 8px;background:var(--bg-elevated);border-radius:4px;font-size:11px;font-weight:700;color:var(--gold);">${p.result || 'vs'}</span>
                  <span style="flex:1;text-align:left;font-size:12px;color:var(--text-primary);">${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:var(--gold);border:none;border-radius:6px;color:#000;font-weight:700;font-size:11px;cursor:pointer;">${t('tournament.play_btn')}</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 = t('common.error_load');
          }
        });
      }
    });
  } catch (e) {
    content.innerHTML = `<div style="text-align:center;color:var(--error);">${t('common.error_load')}</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:var(--text-muted);padding:32px;">${t('tournament.no_games_yet')}</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:var(--gold);">${t('tournament.ready_matches')}</div>`;
      html += allPending.map(p => {
        if (p.is_bye) {
          return `<div class="pairing-row" style="border:1px solid var(--text-muted);">
            <span style="font-size:12px;color:var(--text-muted);">${t('tournament.round_short', { n: p.round_number })}</span>
            <span style="font-size:12px;color:var(--text-secondary);flex:1;margin:0 8px;">${t('tournament.bye_point')}</span>
            <span style="font-size:11px;color:var(--success);">BYE ✓</span>
          </div>`;
        }
        return `<div class="pairing-row" style="border:1px solid var(--gold);">
          <span style="font-size:12px;color:var(--text-muted);">${t('tournament.round_short', { n: p.round_number })}</span>
          <span style="font-size:12px;color:var(--text-primary);flex:1;margin:0 8px;">vs ${p.opponent_name || t('common.opponent')}</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:var(--gold);border:none;border-radius:8px;color:#000;font-weight:700;font-size:12px;cursor:pointer;">${t('tournament.play_btn')}</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:var(--text-secondary);">${t('tournament.prev_matches')}</div>`;
      html += games.map(g => {
        const isWhite = g.white_player_id === userId;
        let resultText = g.status;
        let resultColor = 'var(--text-secondary)';
        if (g.result === 'white_wins') { resultText = isWhite ? t('history.win') : t('history.loss'); resultColor = isWhite ? 'var(--success)' : 'var(--error)'; }
        else if (g.result === 'black_wins') { resultText = isWhite ? t('history.loss') : t('history.win'); resultColor = isWhite ? 'var(--error)' : 'var(--success)'; }
        else if (g.result === 'draw') { resultText = t('history.draw'); resultColor = 'var(--gold)'; }

        return `<div class="pairing-row">
          <span style="font-size:12px;color:var(--text-muted);">${t('tournament.round_short', { n: g.tournament_round || '?' })}</span>
          <span style="font-size:12px;color:var(--text-primary);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:var(--error);">${t('common.error_load')}</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);
  }
}
