import * as net from '../../../core/net.js';
import * as scene from '../../../core/scene.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';

export async function mountTournaments(el) {
  el.innerHTML = `
    <div style="padding:16px;display:flex;flex-direction:column;gap:16px;">
      <div style="display:flex;align-items:center;gap:12px;">
        <button class="btn btn-secondary" id="back-btn" style="width:36px;height:36px;padding:0;">←</button>
        <h2 style="font-size:18px;font-weight:700;">${t('rank.tournaments')}</h2>
      </div>
      <div id="tournament-list">
        <div class="skeleton" style="height:100px;margin-bottom:12px;"></div>
        <div class="skeleton" style="height:100px;"></div>
      </div>
    </div>
  `;

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

  try {
    const data = await net.get('tournaments.php', { action: 'list' });
    const tournaments = data.tournaments || data || [];
    renderTournaments(el, tournaments);
  } catch (e) {
    el.querySelector('#tournament-list').innerHTML = `<p style="color:var(--text-secondary);text-align:center;">${t('common.empty')}</p>`;
  }
}

function renderTournaments(el, tournaments) {
  const list = el.querySelector('#tournament-list');
  if (tournaments.length === 0) {
    list.innerHTML = `<p style="color:var(--text-secondary);text-align:center;padding:32px;">${t('tournament.no_tournaments')}</p>`;
    return;
  }

  list.innerHTML = tournaments.map(tour => `
    <div class="card tournament-card" data-id="${tour.id}" style="padding:16px;margin-bottom:12px;cursor:pointer;">
      <div style="display:flex;justify-content:space-between;align-items:start;">
        <div>
          <div style="font-size:15px;font-weight:700;">${tour.name || t('tournament.title')}</div>
          <div style="font-size:12px;color:var(--text-secondary);margin-top:2px;">${tour.game_key || 'chess'} · ${formatName(tour.format)}</div>
          <div style="font-size:11px;color:var(--text-muted);margin-top:4px;">${tour.starts_at ? new Date(tour.starts_at).toLocaleDateString('ar') : ''}</div>
        </div>
        <span style="font-size:var(--fs-xs);padding:3px 8px;border-radius:9999px;background:${getStatusColor(tour.status)};color:white;font-weight:600;">${getStatusLabel(tour.status)}</span>
      </div>
      <div style="display:flex;gap:16px;margin-top:12px;padding-top:8px;border-top:1px solid rgba(255,255,255,0.05);">
        <span style="font-size:11px;color:var(--text-secondary);">${emoji('people', '👥', 11)} ${tour.player_count || 0}/${tour.max_players || 32}</span>
        <span style="font-size:11px;color:var(--gold);">${emoji('tournament_cup', '🏆', 11)} ${tour.prize_pool_coins ? tour.prize_pool_coins + ' ' + t('common.coins') : 'N/A'}</span>
        ${tour.entry_fee_coins ? `<span style="font-size:11px;color:var(--red-light);">${emoji('money_bag', '💰', 11)} ${tour.entry_fee_coins}</span>` : ''}
      </div>
      ${tour.status === 'registration' ? `<button class="btn btn-primary w-full register-btn" data-tid="${tour.id}" style="margin-top:12px;font-size:13px;">${t('tournament.register_now')}</button>` : ''}
    </div>
  `).join('');

  // Register button handlers
  list.querySelectorAll('.register-btn').forEach(btn => {
    btn.addEventListener('click', async (e) => {
      e.stopPropagation();
      audio.play('click');
      const tid = btn.dataset.tid;
      btn.disabled = true;
      btn.textContent = t('tournament.registering');
      try {
        await net.post('tournaments.php', { action: 'register', tournament_id: tid });
        btn.textContent = '✅ ' + t('tournament.registered');
        btn.style.background = 'var(--success)';
      } catch (err) {
        btn.textContent = err.message || t('tournament.register_failed');
        btn.disabled = false;
      }
    });
  });

  // Card click → detail
  list.querySelectorAll('.tournament-card').forEach(card => {
    card.addEventListener('click', () => {
      audio.play('click');
      scene.push('tournament-detail', { tournamentId: card.dataset.id });
    });
  });
}

async function showTournamentDetail(el, tournamentId, tour) {
  const list = el.querySelector('#tournament-list');
  list.innerHTML = `
    <div style="margin-bottom:16px;">
      <button class="btn btn-secondary" id="detail-back" style="font-size:12px;min-height:var(--tap-min);padding:4px 12px;">← ${t('tournament.back_to_list')}</button>
    </div>
    <div class="card" style="padding:16px;">
      <div style="font-size:18px;font-weight:700;margin-bottom:4px;">${tour?.name || t('tournament.title')}</div>
      <div style="font-size:12px;color:var(--text-secondary);margin-bottom:12px;">${formatName(tour?.format)} · ${tour?.game_key || 'chess'}</div>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:16px;">
        <div style="background:#1a2440;padding:8px;border-radius:8px;text-align:center;">
          <div style="font-size:16px;font-weight:700;color:var(--gold);">${tour?.player_count || 0}</div>
          <div style="font-size:var(--fs-xs);color:var(--text-muted);">${t('tournament.players_label')}</div>
        </div>
        <div style="background:#1a2440;padding:8px;border-radius:8px;text-align:center;">
          <div style="font-size:16px;font-weight:700;color:#00FFFF;">${tour?.rounds_total || tour?.swiss_rounds || '?'}</div>
          <div style="font-size:var(--fs-xs);color:var(--text-muted);">${t('tournament.rounds_label')}</div>
        </div>
      </div>
    </div>
    <div id="bracket-area" style="margin-top:12px;">
      <div class="skeleton" style="height:200px;border-radius:8px;"></div>
    </div>
  `;

  el.querySelector('#detail-back').addEventListener('click', () => {
    audio.play('click');
    mountTournaments(el);
  });

  // Load bracket/standings
  try {
    const data = await net.get('tournaments.php', { action: 'detail', id: tournamentId });
    renderBracketOrStandings(el, data, tour?.format);
  } catch (e) {
    el.querySelector('#bracket-area').innerHTML = `<p style="color:var(--text-muted);text-align:center;">${t('tournament.no_results_yet')}</p>`;
  }
}

function renderBracketOrStandings(el, data, format) {
  const area = el.querySelector('#bracket-area');
  if (!data || (!data.rounds && !data.brackets)) {
    area.innerHTML = `<p style="color:var(--text-muted);text-align:center;padding:16px;">${t('tournament.no_results_yet')}</p>`;
    return;
  }
  area.innerHTML = `
    <div class="card" style="padding:12px;">
      <div style="font-size:14px;font-weight:600;margin-bottom:8px;">${t('tournament.results')}</div>
      <div style="font-size:12px;color:var(--text-secondary);">${t('tournament.data_available_later')}</div>
    </div>
  `;
}

function getStatusColor(status) {
  switch (status) {
    case 'registration': return 'var(--success)';
    case 'in_progress': return '#E84D1E';
    case 'completed': return 'var(--text-muted)';
    default: return '#2082F0';
  }
}

function getStatusLabel(status) {
  switch (status) {
    case 'registration': return t('tournament.registration_open');
    case 'in_progress': return t('tournament.active');
    case 'completed': return t('tournament.completed');
    case 'draft': return t('tournament.coming_soon');
    default: return status || t('tournament.upcoming');
  }
}

function formatName(format) {
  const names = { swiss: t('tournament.format_swiss'), round_robin: t('tournament.format_round_robin'), single_elimination: t('tournament.format_single_elim'), double_elimination: t('tournament.format_double_elim'), arena: t('tournament.format_arena') };
  return names[format] || format || '';
}
