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

export function mountResult(el, params) {
  const { result, reason, coins = 0, xp = 0, moves = 0, mode, botId, pgn, moveHistory = [] } = params;

  const isWin = result === 'win';
  const isDraw = result === 'draw';

  const ratingChange = params.ratingChange || (isWin ? 12 : isDraw ? 1 : -8);
  const ratingStr = ratingChange >= 0 ? `+${ratingChange}` : `${ratingChange}`;

  const resultConfig = {
    win: { icon: emoji('trophy', '🏆', 72), title: t('game.you_win'), color: 'var(--success)' },
    loss: { icon: emoji('skull', '💀', 72), title: t('game.you_lose'), color: 'var(--red-light)' },
    draw: { icon: emoji('handshake', '🤝', 72), title: t('game.draw_result'), color: 'var(--gold)' }
  };

  const cfg = resultConfig[result] || resultConfig.loss;
  const reasonText = {
    checkmate: t('game.checkmate'),
    stalemate: t('game.stalemate'),
    resign: t('game.resign'),
    timeout: t('game.timeout'),
    threefold: t('game.threefold'),
    insufficient: t('game.insufficient')
  }[reason] || reason;

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;gap:20px;padding:24px;background:var(--bg-deep);">
      <!-- Result Icon -->
      <div style="font-size:72px;${isWin ? 'animation:float 2s ease-in-out infinite;' : ''}">${cfg.icon}</div>

      <!-- Title & Reason -->
      <div style="text-align:center;">
        <div style="font-size:32px;font-weight:800;color:${cfg.color};">${cfg.title}</div>
        <div style="font-size:14px;color:var(--text-secondary);margin-top:4px;">${reasonText}</div>
        ${moves ? `<div style="font-size:12px;color:var(--text-dim);margin-top:2px;">${t('game.moves_count', { n: moves })}</div>` : ''}
      </div>

      <!-- Stats Row -->
      <div style="display:flex;gap:24px;margin-top:8px;">
        <div style="text-align:center;">
          <div style="font-size:28px;font-weight:700;color:${cfg.color};font-family:Inter,monospace;">${ratingStr}</div>
          <div style="font-size:11px;color:var(--text-muted);">${t('game.rating')}</div>
        </div>
        <div style="width:1px;background:var(--border);"></div>
        <div style="text-align:center;">
          <div style="font-size:28px;font-weight:700;color:var(--gold);font-family:Inter,monospace;">+${coins}</div>
          <div style="font-size:11px;color:var(--text-muted);">${t('game.coins')}</div>
        </div>
        <div style="width:1px;background:var(--border);"></div>
        <div style="text-align:center;">
          <div style="font-size:28px;font-weight:700;color:var(--cyan);font-family:Inter,monospace;">+${xp}</div>
          <div style="font-size:11px;color:var(--text-muted);">${t('game.xp')}</div>
        </div>
      </div>

      <!-- Move Summary -->
      ${moveHistory.length > 0 ? `
      <div style="background:var(--bg-card);border:1px solid var(--border);border-radius:8px;padding:8px 12px;max-width:300px;width:100%;max-height:60px;overflow-x:auto;white-space:nowrap;">
        <div style="font-family:Inter,monospace;font-size:11px;color:var(--text-secondary);">
          ${formatMoveHistory(moveHistory)}
        </div>
      </div>` : ''}

      <!-- Actions -->
      <div style="display:flex;flex-direction:column;gap:8px;width:100%;max-width:280px;margin-top:12px;">
        ${params.tournamentId
          ? `<button class="btn btn-primary w-full" id="btn-back-tournament" style="font-size:15px;">${emoji('trophy', '🏆', 15)} ${t('tournament.back_to')}</button>`
          : `<button class="btn btn-primary w-full" id="btn-rematch" style="font-size:15px;">${t('game.rematch')}</button>`
        }
        <button class="btn btn-secondary w-full" id="btn-analyze" style="font-size:13px;">${emoji('chart', '📊', 13)} ${t('result.analyze')}</button>
        <div style="display:flex;gap:8px;">
          <button class="btn btn-secondary" id="btn-share" style="flex:1;font-size:12px;">${emoji('share', '📤', 12)} ${t('result.share_pgn')}</button>
          <button class="btn btn-secondary" id="btn-copy-pgn" style="flex:1;font-size:12px;">${emoji('clipboard', '📋', 12)} ${t('result.copy_pgn')}</button>
        </div>
        <button class="btn btn-secondary w-full" id="btn-back" style="font-size:13px;">${t('game.back')}</button>
      </div>
    </div>
  `;

  // JUICE: Result screen effects
  setTimeout(() => {
    // Flash on entry
    juice.flash(isWin ? '#34D39944' : '#EF444444', 200);

    // Icon slams in
    const icon = el.querySelector('[style*="font-size:72px"]');
    if (icon) juice.slamIn(icon, { scale: 1.8, duration: 500 });

    // Rating counter ticks
    setTimeout(() => {
      const ratingEl = el.querySelector('[style*="font-size:28px"]');
      if (ratingEl && ratingChange) juice.countTo(ratingEl, ratingChange, { duration: 800, prefix: ratingChange >= 0 ? '+' : '', color: cfg.color });
    }, 400);

    // Confetti on win
    if (isWin) {
      setTimeout(() => juice.confetti(window.innerWidth / 2, window.innerHeight / 3, 40), 300);
      juice.hapticSuccess();
    } else {
      juice.shake(el, 3, 200);
      juice.hapticError();
    }

    // Coins fly to HUD
    if (coins > 0) {
      setTimeout(() => {
        const rect = el.getBoundingClientRect();
        juice.coinFlyTo(rect.width / 2, rect.height / 2, '#hud-coins', Math.min(coins / 10, 8));
      }, 800);
    }

    // Stagger buttons
    const buttons = el.querySelectorAll('.btn');
    juice.stagger(Array.from(buttons), juice.slideUpBounce, 600, 80);
  }, 100);

  if (params.tournamentId) {
    el.querySelector('#btn-back-tournament')?.addEventListener('click', () => {
      audio.play('click');
      juice.hapticLight();
      scene.replace('tournament-detail', { tournamentId: params.tournamentId });
    });
  } else {
    el.querySelector('#btn-rematch')?.addEventListener('click', () => {
      audio.play('click');
      juice.hapticLight();
      scene.replace('chess-game', { mode, botId, timeControl: params.timeControl || 'rapid_10_0' });
    });
  }

  el.querySelector('#btn-analyze').addEventListener('click', () => {
    audio.play('click');
    juice.hapticLight();
    scene.push('chess-review', { moveHistory, playerColor: params.playerColor || 'w', botId, result });
  });

  el.querySelector('#btn-back').addEventListener('click', () => {
    audio.play('click');
    juice.hapticLight();
    bus.emit('navigate', { world: 'play', scene: 'play-table' });
  });

  el.querySelector('#btn-share')?.addEventListener('click', () => {
    const pgnText = pgn || formatMoveHistory(moveHistory);
    if (navigator.share) {
      navigator.share({ title: 'EL3AB Chess Game', text: pgnText });
    } else {
      navigator.clipboard?.writeText(pgnText);
      juice.pulseElement(el.querySelector('#btn-share'));
    }
  });

  el.querySelector('#btn-copy-pgn')?.addEventListener('click', () => {
    const pgnText = pgn || formatMoveHistory(moveHistory);
    navigator.clipboard?.writeText(pgnText).then(() => {
      const btn = el.querySelector('#btn-copy-pgn');
      btn.textContent = t('result.copied');
      juice.pulseElement(btn, '#34D399');
      setTimeout(() => { btn.innerHTML = `${emoji('clipboard', '📋', 12)} ${t('result.copy_pgn')}`; }, 2000);
    });
  });

  const player = store.get('player');
  if (player && coins > 0) {
    store.set('player', { ...player, coins: (player.coins || 0) + coins, xp: (player.xp || 0) + xp });
  }
}

function formatMoveHistory(history) {
  let html = '';
  for (let i = 0; i < Math.min(history.length, 30); i += 2) {
    const num = Math.floor(i / 2) + 1;
    html += `${num}.${history[i]?.san || ''} ${history[i+1]?.san || ''} `;
  }
  if (history.length > 30) html += '...';
  return html;
}
