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

const PLACE_EMOJI = [emoji('medal_1', '🥇', 18), emoji('medal_2', '🥈', 18), emoji('medal_3', '🥉', 18), '4️⃣'];
const PLACE_LABEL = [t('ludo.place_first'), t('ludo.place_second'), t('ludo.place_third'), t('ludo.place_fourth')];
const PLACE_COLOR = ['var(--gold-soft)', '#C0C0C0', '#CD7F32', 'var(--text-muted)'];

export function mountResult(el, params) {
  const { result, place, resigned, rewards, winners = [], playerNames = [], playerColors = [] } = params;
  const numPlayers = params.numPlayers || params.playerCount || 4;
  const isWin = result === 'win';

  const coins = rewards?.coins_earned ?? (isWin ? 50 : place === 2 ? 25 : place === 3 ? 15 : 10);
  const xp = rewards?.xp_earned ?? (isWin ? 30 : 15);
  const ratingChange = rewards?.rating_change ?? (isWin ? 12 : place === 2 ? 3 : place === 3 ? -3 : -8);

  // Build leaderboard: winners array has player indices in finish order
  const leaderboard = [];
  if (!resigned && winners.length > 0) {
    for (let rank = 0; rank < winners.length; rank++) {
      const pIdx = winners[rank];
      leaderboard.push({
        rank: rank + 1,
        name: playerNames[pIdx] || `${t('common.player')} ${pIdx + 1}`,
        color: playerColors[pIdx] || 'var(--text-secondary)',
        isMe: pIdx === 0,
      });
    }
    // Add any unfinished players (not in winners)
    for (let i = 0; i < numPlayers; i++) {
      if (!winners.includes(i)) {
        leaderboard.push({
          rank: leaderboard.length + 1,
          name: playerNames[i] || `${t('common.player')} ${i + 1}`,
          color: playerColors[i] || 'var(--text-secondary)',
          isMe: i === 0,
        });
      }
    }
  }

  const heroIcon = resigned
    ? emoji('skull', '💀', 64)
    : place === 1 ? emoji('trophy', '🏆', 64)
    : place === 2 ? emoji('medal_2', '🥈', 64)
    : place === 3 ? emoji('medal_3', '🥉', 64)
    : emoji('skull', '💀', 64);

  const heroTitle = resigned ? t('game.withdrew')
    : place === 1 ? t('game.congrats')
    : place === 2 ? t('game.second_place')
    : place === 3 ? t('game.third_place')
    : t('game.fourth_place');

  const heroColor = resigned ? 'var(--error)'
    : place === 1 ? 'var(--gold-soft)'
    : place === 2 ? '#C0C0C0'
    : place === 3 ? '#CD7F32'
    : 'var(--error)';

  el.innerHTML = `
    <div class="lr-result-wrap">
      <!-- Hero -->
      <div class="lr-hero-section">
        <div class="lr-hero-icon">${heroIcon}</div>
        <div class="lr-hero-title" style="color:${heroColor};">${heroTitle}</div>
      </div>

      <!-- Leaderboard -->
      ${leaderboard.length > 0 ? `
      <div class="lr-leaderboard">
        <div class="lr-lb-title">${t('game.player_ranking')}</div>
        ${leaderboard.map(p => `
          <div class="lr-lb-row ${p.isMe ? 'lr-lb-me' : ''}" style="--pc:${p.color};">
            <div class="lr-lb-rank" style="color:${PLACE_COLOR[p.rank - 1] || 'var(--text-muted)'};">
              ${p.rank <= 3 ? PLACE_EMOJI[p.rank - 1] : p.rank}
            </div>
            <div class="lr-lb-color" style="background:${p.color};"></div>
            <div class="lr-lb-name">${p.name}${p.isMe ? ` (${t('common.you')})` : ''}</div>
            <div class="lr-lb-place">${PLACE_LABEL[p.rank - 1] || ''}</div>
          </div>
        `).join('')}
      </div>` : ''}

      <!-- Rewards -->
      <div class="lr-rewards">
        <div class="lr-reward-pill lr-reward-coins">
          <span>${emoji('coin', '🪙', 16)}</span>
          <span>+${coins}</span>
        </div>
        <div class="lr-reward-pill lr-reward-xp">
          <span>${emoji('star', '⭐', 16)}</span>
          <span>+${xp} XP</span>
        </div>
        ${ratingChange ? `
        <div class="lr-reward-pill" style="color:${ratingChange > 0 ? 'var(--green-light)' : 'var(--red-soft)'};border-color:${ratingChange > 0 ? 'rgba(74,222,128,0.2)' : 'rgba(252,165,165,0.2)'};">
          <span>${emoji('chart_up', '📈', 16)}</span>
          <span>${ratingChange > 0 ? '+' : ''}${ratingChange}</span>
        </div>` : ''}
      </div>

      <!-- Actions -->
      <div class="lr-actions">
        <button class="btn btn-primary" id="btn-again">${t('game.rematch')}</button>
        <button class="btn btn-secondary" id="btn-back">${t('game.back')}</button>
      </div>
    </div>
    ${getResultStyles()}
  `;

  if (isWin) {
    juice.hapticSuccess?.();
    setTimeout(() => juice.confetti?.(window.innerWidth / 2, window.innerHeight / 3, 40), 300);
  }

  bus.emit('coins:earned', { amount: coins });
  bus.emit('xp:earned', { amount: xp });

  el.querySelector('#btn-again').addEventListener('click', () => {
    audio.play('click');
    if (params.mode === 'live') {
      scene.replace('play-queue', { game: 'ludo', mode: 'human', playerCount: numPlayers, seats: params.seats });
    } else {
      scene.replace('ludo-game', {
        mode: params.mode || 'bot',
        numPlayers: params.numPlayers,
        playerCount: params.playerCount,
        seats: params.seats,
        humanCount: params.humanCount,
        difficulty: params.difficulty,
      });
    }
  });
  el.querySelector('#btn-back').addEventListener('click', () => {
    audio.play('click');
    bus.emit('navigate', { world: 'play', scene: 'play-table' });
  });
}

function getResultStyles() {
  return `<style>
.lr-result-wrap {
  display:flex;flex-direction:column;align-items:center;justify-content:center;
  height:100%;gap:20px;padding:24px;
  background:linear-gradient(180deg,#070d14 0%,var(--bg-inset) 40%,var(--bg-inset) 100%);
}
.lr-hero-section { text-align:center; }
.lr-hero-icon { font-size:64px;animation:lrFloat 2.5s ease-in-out infinite; }
.lr-hero-title { font-size:22px;font-weight:800;margin-top:8px; }
@keyframes lrFloat { 0%,100%{transform:translateY(0)} 50%{transform:translateY(-6px)} }

.lr-leaderboard {
  width:100%;max-width:320px;
  background:rgba(255,255,255,0.02);border:1px solid var(--border);
  border-radius:16px;padding:14px;
}
.lr-lb-title {
  font-size:12px;font-weight:700;color:var(--text-muted);text-align:center;
  margin-bottom:10px;text-transform:uppercase;letter-spacing:0.05em;
}
.lr-lb-row {
  display:flex;align-items:center;gap:10px;
  padding:10px 12px;border-radius:10px;
  transition:background 0.2s;
}
.lr-lb-me {
  background:rgba(228,172,56,0.08);border:1px solid rgba(228,172,56,0.2);
}
.lr-lb-rank { font-size:18px;min-width:28px;text-align:center; }
.lr-lb-color { width:12px;height:12px;border-radius:50%;flex-shrink:0; }
.lr-lb-name { flex:1;font-size:14px;font-weight:600;color:var(--text-primary); }
.lr-lb-place { font-size:11px;color:var(--text-muted);font-weight:500; }

.lr-rewards { display:flex;gap:10px;flex-wrap:wrap;justify-content:center; }
.lr-reward-pill {
  display:flex;align-items:center;gap:4px;
  padding:8px 14px;border-radius:10px;
  font-size:14px;font-weight:700;
  border:1px solid transparent;
}
.lr-reward-coins { color:var(--amber);background:rgba(251,191,36,0.1);border-color:rgba(251,191,36,0.2); }
.lr-reward-xp { color:var(--purple-light);background:rgba(139,92,246,0.1);border-color:rgba(139,92,246,0.2); }

.lr-actions { display:flex;gap:10px;width:100%;max-width:300px; }
.lr-actions .btn { flex:1;min-height:48px;border-radius:14px;font-size:15px;font-weight:700; }
</style>`;
}
