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

const PLACE_EMOJI = ['🥇', '🥈', '🥉'];
const PLACE_LABEL = ['المركز الأول', 'المركز الثاني', 'المركز الثالث'];
const PLACE_COLOR = ['#FFD700', '#C0C0C0', '#CD7F32'];

export function mountResult(el, params) {
  const { result, place, resigned } = params;
  const isWin = result === 'win';

  let content;
  if (resigned) {
    content = `
      <div style="font-size:64px;animation:float 2s ease-in-out infinite;">${emoji('skull', '💀', 64)}</div>
      <div style="font-size:24px;font-weight:800;color:var(--loss);">انسحبت من المباراة</div>
    `;
  } else if (isWin && place >= 1 && place <= 3) {
    const idx = place - 1;
    content = `
      <div style="font-size:72px;animation:float 2s ease-in-out infinite;">${emoji('medal_' + place, PLACE_EMOJI[idx], 72)}</div>
      <div style="font-size:28px;font-weight:800;color:${PLACE_COLOR[idx]};">${PLACE_LABEL[idx]}</div>
      <div style="font-size:16px;color:#94a3b8;margin-top:4px;">${place === 1 ? 'مبروك! أنت البطل' : 'أحسنت!'}</div>
    `;
  } else {
    content = `
      <div style="font-size:64px;animation:float 2s ease-in-out infinite;">${emoji('skull', '💀', 64)}</div>
      <div style="font-size:28px;font-weight:800;color:var(--loss);">المركز الرابع</div>
      <div style="font-size:16px;color:#94a3b8;margin-top:4px;">حظ أوفر المرة القادمة!</div>
    `;
  }

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;gap:var(--s-6);padding:var(--s-6);">
      ${content}
      <div style="display:flex;gap:var(--s-3);margin-top:var(--s-6);">
        <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>
  `;

  el.querySelector('#btn-again').addEventListener('click', () => {
    audio.play('click');
    scene.replace('ludo-game', { mode: 'bot' });
  });
  el.querySelector('#btn-back').addEventListener('click', () => {
    audio.play('click');
    bus.emit('navigate', { world: 'play', scene: 'play-table' });
  });
}
