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: '#34D399' },
    loss: { icon: emoji('skull', '💀', 72), title: t('game.you_lose'), color: '#F87171' },
    draw: { icon: emoji('handshake', '🤝', 72), title: t('game.draw_result'), color: '#E4AC38' }
  };

  const cfg = resultConfig[result] || resultConfig.loss;
  const reasonText = {
    checkmate: 'كش ملك',
    stalemate: 'بات (جمود)',
    resign: 'استسلام',
    timeout: 'انتهاء الوقت',
    threefold: 'تكرار ثلاثي',
    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:#0a0a1a;">
      <!-- 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:#94a3b8;margin-top:4px;">${reasonText}</div>
        ${moves ? `<div style="font-size:12px;color:#475569;margin-top:2px;">${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:#64748b;">تصنيف</div>
        </div>
        <div style="width:1px;background:rgba(255,255,255,0.06);"></div>
        <div style="text-align:center;">
          <div style="font-size:28px;font-weight:700;color:#E4AC38;font-family:Inter,monospace;">+${coins}</div>
          <div style="font-size:11px;color:#64748b;">عملات</div>
        </div>
        <div style="width:1px;background:rgba(255,255,255,0.06);"></div>
        <div style="text-align:center;">
          <div style="font-size:28px;font-weight:700;color:#00FFFF;font-family:Inter,monospace;">+${xp}</div>
          <div style="font-size:11px;color:#64748b;">خبرة</div>
        </div>
      </div>

      <!-- Move Summary -->
      ${moveHistory.length > 0 ? `
      <div style="background:#1a1a2e;border:1px solid rgba(255,255,255,0.06);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:#94a3b8;">
          ${formatMoveHistory(moveHistory)}
        </div>
      </div>` : ''}

      <!-- Actions -->
      <div style="display:flex;flex-direction:column;gap:8px;width:100%;max-width:280px;margin-top:12px;">
        <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)} تحليل المباراة</button>
        <div style="display:flex;gap:8px;">
          <button class="btn btn-secondary" id="btn-share" style="flex:1;font-size:12px;">${emoji('share', '📤', 12)} مشاركة PGN</button>
          <button class="btn btn-secondary" id="btn-copy-pgn" style="flex:1;font-size:12px;">${emoji('clipboard', '📋', 12)} نسخ</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);

  el.querySelector('#btn-rematch').addEventListener('click', () => {
    audio.play('click');
    juice.hapticLight();
    scene.replace('chess-game', { mode, botId, 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 = '✓ تم النسخ';
      juice.pulseElement(btn, '#34D399');
      setTimeout(() => { btn.innerHTML = `${emoji('clipboard', '📋', 12)} نسخ`; }, 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;
}
