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

let activeFilter = 'all';

export async function mountTournamentsHub(el) {
  activeFilter = 'all';

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;height:100%;background:var(--bg-deep);">
      <div style="padding:14px 16px 0;background:var(--bg-panel);">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;">
          <h2 style="font-size:20px;font-weight:800;color:var(--text-primary);">${emoji('tournament_cup', '🏆', 20)} ${t('tournament.hub_title')}</h2>
        </div>
        <div id="tour-filters" style="display:flex;gap:6px;overflow-x:auto;padding-bottom:12px;border-bottom:1px solid var(--border);">
          <button class="tour-filter active" data-filter="all">${t('common.all')}</button>
          <button class="tour-filter" data-filter="my">${t('tournament.my_tournaments')}</button>
          <button class="tour-filter" data-filter="registration">${t('tournament.registration_open')}</button>
          <button class="tour-filter" data-filter="in_progress">${t('tournament.active')}</button>
          <button class="tour-filter" data-filter="completed">${t('tournament.completed')}</button>
        </div>
      </div>
      <div id="tour-hub-content" style="flex:1;overflow-y:auto;padding:14px 16px;"></div>
    </div>
    <style>
      .tour-filter{background:rgba(255,255,255,0.05);border:1px solid var(--border);color:var(--text-secondary);font-size:12px;font-weight:600;padding:7px 14px;border-radius:8px;cursor:pointer;font-family:inherit;transition:all 0.15s;white-space:nowrap;flex-shrink:0;}
      .tour-filter.active{background:var(--gold);border-color:var(--gold);color:#000;}
      .tour-filter:active{transform:scale(0.95);}
      .tour-hub-card{background:var(--bg-card);border-radius:14px;padding:14px;margin-bottom:10px;cursor:pointer;transition:transform 0.1s;border:1px solid var(--border);}
      .tour-hub-card:active{transform:scale(0.98);}
      .tour-hub-card.registered{border-color:rgba(228,172,56,0.3);}
      .tour-hub-card.has-pending{border-color:var(--gold);box-shadow:0 0 12px rgba(228,172,56,0.15);}
      .tour-status-pill{font-size:10px;padding:3px 10px;border-radius:99px;font-weight:700;display:inline-block;}
      .tour-stat{display:flex;flex-direction:column;align-items:center;gap:2px;}
      .tour-stat-val{font-size:16px;font-weight:800;color:var(--text-primary);}
      .tour-stat-label{font-size:10px;color:var(--text-muted);}
    </style>
  `;

  el.querySelectorAll('.tour-filter').forEach(btn => {
    btn.addEventListener('click', () => {
      audio.play('click');
      el.querySelectorAll('.tour-filter').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      activeFilter = btn.dataset.filter;
      loadTournaments(el);
    });
  });

  loadTournaments(el);
}

async function loadTournaments(el) {
  const content = el.querySelector('#tour-hub-content');
  content.innerHTML = `
    <div style="display:flex;flex-direction:column;gap:10px;">
      <div style="height:100px;background:var(--bg-card);border-radius:14px;animation:pulse 1.5s infinite;"></div>
      <div style="height:100px;background:var(--bg-card);border-radius:14px;animation:pulse 1.5s infinite;animation-delay:0.3s;"></div>
    </div>
  `;

  const userId = store.get('auth.userId');

  try {
    const [tourData, pendingData] = await Promise.all([
      net.get('tournaments.php', { action: 'list' }),
      net.get('tournament-match.php', { action: 'my-pending' }).catch(() => ({ pending: [] }))
    ]);

    let tournaments = tourData.tournaments || tourData || [];
    const pending = pendingData.pending || [];
    const pendingTournamentIds = new Set(pending.map(p => p.tournament_id));

    let registrations = [];
    if (activeFilter === 'my' || activeFilter === 'all') {
      try {
        const regData = await net.get('tournaments.php', { action: 'my-registrations' });
        registrations = regData.registrations || [];
      } catch (e) {}
    }
    const registeredIds = new Set(registrations.map(r => r.tournament_id));

    if (activeFilter === 'my') {
      tournaments = tournaments.filter(t => registeredIds.has(t.id));
    } else if (activeFilter === 'registration') {
      tournaments = tournaments.filter(t => t.status === 'registration' || t.status === 'draft');
    } else if (activeFilter !== 'all') {
      tournaments = tournaments.filter(t => t.status === activeFilter);
    }

    if (tournaments.length === 0) {
      const emptyMessages = {
        all: t('tournament.no_tournaments'),
        my: t('tournament.no_my_tournaments'),
        registration: t('tournament.no_open_tournaments'),
        in_progress: t('tournament.no_active_tournaments'),
        completed: t('tournament.no_completed_tournaments')
      };
      content.innerHTML = `
        <div style="text-align:center;padding:48px 20px;">
          <div style="font-size:48px;margin-bottom:12px;opacity:0.4;">${emoji('tournament_cup', '🏆', 48)}</div>
          <div style="font-size:15px;font-weight:600;color:var(--text-primary);margin-bottom:6px;">${emptyMessages[activeFilter] || emptyMessages.all}</div>
          <div style="font-size:12px;color:var(--text-muted);">${t('tournament.new_tournaments_here')}</div>
        </div>
      `;
      return;
    }

    const sortOrder = { in_progress: 0, registration: 1, draft: 2, completed: 3 };
    tournaments.sort((a, b) => (sortOrder[a.status] ?? 9) - (sortOrder[b.status] ?? 9));

    content.innerHTML = tournaments.map(tour => {
      const isRegistered = registeredIds.has(tour.id);
      const hasPending = pendingTournamentIds.has(tour.id);
      const pendingMatch = pending.find(p => p.tournament_id === tour.id);

      return `
        <div class="tour-hub-card ${isRegistered ? 'registered' : ''} ${hasPending ? 'has-pending' : ''}" data-id="${tour.id}">
          <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:10px;">
            <div style="flex:1;min-width:0;">
              <div style="font-size:15px;font-weight:700;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${tour.name || t('tournament.title')}</div>
              <div style="font-size:11px;color:var(--text-muted);margin-top:2px;">${formatGame(tour.game_key)} · ${formatName(tour.format)}</div>
            </div>
            <span class="tour-status-pill" style="background:${getStatusColor(tour.status)};color:${tour.status === 'in_progress' ? '#000' : '#fff'};">${getStatusLabel(tour.status)}</span>
          </div>

          <div style="display:flex;gap:12px;margin-bottom:10px;">
            <div class="tour-stat">
              <span class="tour-stat-val" style="color:var(--blue);">${tour.player_count || 0}<span style="font-size:11px;color:var(--text-muted);">/${tour.max_players || '∞'}</span></span>
              <span class="tour-stat-label">${t('tournament.players_label')}</span>
            </div>
            <div class="tour-stat">
              <span class="tour-stat-val" style="color:var(--gold);">${tour.swiss_rounds || tour.rounds_total || '?'}</span>
              <span class="tour-stat-label">${t('tournament.rounds_label')}</span>
            </div>
            <div class="tour-stat">
              <span class="tour-stat-val" style="color:var(--emerald);">${formatTimeControl(tour.time_control)}</span>
              <span class="tour-stat-label">${t('tournament.time_label')}</span>
            </div>
            ${tour.prize_pool_coins ? `<div class="tour-stat">
              <span class="tour-stat-val" style="color:var(--warning);">${tour.prize_pool_coins}</span>
              <span class="tour-stat-label">${emoji('coin', '🪙', 10)} ${t('tournament.prize')}</span>
            </div>` : ''}
          </div>

          ${tour.starts_at ? `<div style="font-size:11px;color:var(--text-dim);margin-bottom:8px;">${emoji('calendar', '📅', 11)} ${formatDate(tour.starts_at)}</div>` : ''}

          ${hasPending ? `
            <div style="background:rgba(228,172,56,0.1);border:1px solid rgba(228,172,56,0.3);border-radius:10px;padding:10px;display:flex;align-items:center;justify-content:space-between;">
              <div style="font-size:12px;color:var(--gold);font-weight:600;">${emoji('swords', '⚔️', 12)} ${t('tournament.match_ready')} — ${t('tournament.round_short')}${pendingMatch?.round_number || ''} vs ${pendingMatch?.opponent_name || t('tournament.opponent')}</div>
              <button class="play-now-btn" data-tid="${tour.id}" style="background:var(--gold);border:none;border-radius:8px;padding:6px 14px;color:#000;font-weight:700;font-size:11px;cursor:pointer;">${t('common.play')}</button>
            </div>
          ` : isRegistered ? `
            <div style="font-size:11px;color:var(--success);font-weight:600;">${emoji('checkmark', '✓', 11)} ${t('tournament.joined')}</div>
          ` : (tour.status === 'registration' || tour.status === 'draft') ? `
            <button class="register-btn" data-tid="${tour.id}" style="width:100%;background:var(--gold);border:none;border-radius:10px;padding:12px;color:#000;font-weight:700;font-size:13px;cursor:pointer;margin-top:4px;">${emoji('swords', '⚔️', 13)} ${t('tournament.register_now')}${tour.entry_fee_coins ? ' — ' + tour.entry_fee_coins + ' ' + t('common.coins') : ''}</button>
          ` : ''}
        </div>
      `;
    }).join('');

    content.querySelectorAll('.tour-hub-card').forEach(card => {
      card.addEventListener('click', (e) => {
        if (e.target.closest('.register-btn') || e.target.closest('.play-now-btn')) return;
        audio.play('click');
        scene.push('tournament-detail', { tournamentId: card.dataset.id });
      });
    });

    content.querySelectorAll('.register-btn').forEach(btn => {
      btn.addEventListener('click', async (e) => {
        e.stopPropagation();
        audio.play('click');
        btn.disabled = true;
        btn.textContent = t('tournament.registering');
        try {
          await net.post('tournaments.php', { action: 'register', tournament_id: btn.dataset.tid });
          btn.innerHTML = emoji('checkmark', '✓', 12) + ' ' + t('tournament.registered');
          btn.style.background = 'var(--success)';
          btn.closest('.tour-hub-card')?.classList.add('registered');
        } catch (err) {
          btn.textContent = err.message || t('common.failed');
          btn.disabled = false;
          setTimeout(() => { btn.textContent = t('tournament.register_now'); }, 2000);
        }
      });
    });

    content.querySelectorAll('.play-now-btn').forEach(btn => {
      btn.addEventListener('click', async (e) => {
        e.stopPropagation();
        audio.play('click');
        btn.disabled = true;
        btn.textContent = '...';
        try {
          // The server works out which pairing is ours from the tournament's
          // current round, so the client cannot land on the wrong board.
          const data = await net.post('tournament-match.php', {
            action: 'create-or-join',
            tournament_id: btn.dataset.tid
          });
          if (data.error) throw new Error(data.error);
          if (data.bye) { audio.play('reward'); btn.textContent = 'BYE ✓'; return; }
          if (data.waiting) { btn.textContent = t('common.waiting') || '...'; btn.disabled = false; return; }
          scene.push('chess-game', {
            mode: 'live',
            matchId: data.match_id,
            color: data.color,
            timeControl: data.time_control || 'rapid_10_0',
            opponentId: data.opponent_id,
            tournamentId: btn.dataset.tid,
            tournamentRound: data.round_number,
            recovered: !!data.recovered
          });
        } catch (err) {
          btn.textContent = t('common.failed');
          btn.disabled = false;
        }
      });
    });

  } catch (e) {
    content.innerHTML = `
      <div style="text-align:center;padding:32px;color:var(--error);">
        <div style="margin-bottom:8px;">${t('tournament.load_failed')}</div>
        <button class="btn btn-secondary" id="retry-tour" style="font-size:12px;padding:8px 16px;">${t('common.retry')}</button>
      </div>
    `;
    content.querySelector('#retry-tour')?.addEventListener('click', () => loadTournaments(el));
  }
}

function getStatusColor(status) {
  switch (status) {
    case 'registration': case 'draft': return 'var(--success)';
    case 'in_progress': return 'var(--gold)';
    case 'completed': return 'var(--text-muted)';
    default: return 'var(--blue)';
  }
}

function getStatusLabel(status) {
  switch (status) {
    case 'registration': case 'draft': return t('tournament.registration_open');
    case 'in_progress': return t('tournament.active');
    case 'completed': return t('tournament.completed');
    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'), group_stage: t('tournament.format_group_stage') };
  return names[format] || format || '';
}

function formatGame(key) {
  const games = { chess: t('game.chess'), ludo: t('game.ludo'), domino: t('game.domino') };
  return games[key] || key || t('game.chess');
}

function formatTimeControl(tc) {
  if (!tc) return '?';
  const parts = tc.split('_');
  if (parts.length >= 2) return parts[1] + (parts[2] && parts[2] !== '0' ? '+' + parts[2] : '') + t('common.minutes_abbr');
  return tc;
}

function formatDate(dateStr) {
  if (!dateStr) return '';
  const d = new Date(dateStr);
  const now = new Date();
  const diff = d - now;
  if (diff > 0 && diff < 86400000) {
    const hours = Math.floor(diff / 3600000);
    const mins = Math.floor((diff % 3600000) / 60000);
    if (hours > 0) return t('tournament.starts_in_hours', { n: hours });
    return t('tournament.starts_in_minutes', { n: mins });
  }
  if (diff > 0 && diff < 7 * 86400000) {
    const days = Math.ceil(diff / 86400000);
    return t('tournament.in_days', { n: days });
  }
  return d.toLocaleDateString('ar', { day: 'numeric', month: 'short', year: d.getFullYear() !== now.getFullYear() ? 'numeric' : undefined });
}
