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

let activeTab = 'info';

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 12px;">
        <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>
      </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) {
  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);

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

    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 || [];

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

    // Make rounds expandable
    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 => `
              <div class="pairing-row">
                <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>
              </div>
            `).join('');
          } catch (e) {
            el.textContent = 'فشل التحميل';
          }
        });
      }
    });
  } catch (e) {
    content.innerHTML = '<div style="text-align:center;color:#ef4444;">فشل تحميل الجولات</div>';
  }
}

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

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

    content.innerHTML = games.map(g => {
      const resultColors = { white_wins: '#34D399', black_wins: '#34D399', draw: '#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:${resultColors[g.result] || '#94a3b8'};">${g.result === 'white_wins' || g.result === 'black_wins' ? 'فوز' : g.result === 'draw' ? 'تعادل' : g.status}</span>
        </div>
      `;
    }).join('');
  } catch (e) {
    content.innerHTML = '<div style="text-align:center;color:#ef4444;">فشل التحميل</div>';
  }
}
