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 * as net from '../../../core/net.js';
import * as store from '../../../core/store.js';
import { t } from '../../../core/i18n.js';
import { emoji } from '../../../core/theme.js';

export function mountResult(el, params) {
  const { result, myScore = 0, oppScore = 0, rounds = 1, mode = 'bot', resigned = false, matchId, reason } = params;
  const isWin = result === 'win';
  const isDraw = result === 'draw';

  const icon = isWin ? `${emoji('crown', '👑', 32)}<br>${emoji('trophy', '🏆', 56)}` : isDraw ? emoji('handshake', '🤝', 56) : emoji('skull', '💀', 56);
  const title = resigned ? t('game.resigned') : reason === 'resign' ? t('game.opponent_resigned') : reason === 'abandon' ? t('game.opponent_abandoned') : isWin ? t('game.win') : isDraw ? t('game.draw_game') : t('game.loss');
  const titleColor = isWin ? 'var(--green-light)' : isDraw ? 'var(--amber)' : 'var(--red-soft)';

  el.innerHTML = `
    <div id="result-wrap" style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;gap:16px;padding:24px;background:linear-gradient(180deg,#070d14 0%,var(--bg-inset) 40%,#0d1a2a 100%);">
      <div id="result-icon" style="font-size:56px;animation:bounceIn 0.5s cubic-bezier(0.34,1.56,0.64,1);">${icon}</div>
      <div style="font-size:28px;font-weight:800;color:${titleColor};animation:fadeSlideUp 0.4s ease 0.2s both;">${title}</div>

      <!-- Score summary -->
      <div style="display:flex;gap:20px;align-items:center;animation:fadeSlideUp 0.4s ease 0.3s both;">
        <div style="text-align:center;">
          <div style="font-size:32px;font-weight:800;color:var(--green-light);" id="score-me">0</div>
          <div style="font-size:11px;color:#86efac;">${t('common.you')}</div>
        </div>
        <div style="font-size:18px;color:var(--text-dim);">—</div>
        <div style="text-align:center;">
          <div style="font-size:32px;font-weight:800;color:var(--red-soft);" id="score-opp">0</div>
          <div style="font-size:11px;color:var(--red-soft);">${t('common.opponent')}</div>
        </div>
      </div>

      <div style="font-size:12px;color:var(--text-muted);animation:fadeSlideUp 0.4s ease 0.35s both;">${rounds === 1 ? t('game.rounds_count', { n: rounds }) : t('game.rounds_count_plural', { n: rounds })}</div>

      <!-- Rewards (populated after server response) -->
      <div id="rewards-section" style="display:flex;gap:12px;margin-top:8px;animation:fadeSlideUp 0.4s ease 0.5s both;">
        <div style="display:flex;align-items:center;gap:4px;padding:8px 14px;background:rgba(251,191,36,0.1);border:1px solid rgba(251,191,36,0.2);border-radius:10px;">
          <span style="font-size:16px;">${emoji('coin', '🪙', 16)}</span>
          <span style="font-size:14px;font-weight:700;color:var(--amber);" id="coins-earned">...</span>
        </div>
        <div style="display:flex;align-items:center;gap:4px;padding:8px 14px;background:rgba(139,92,246,0.1);border:1px solid rgba(139,92,246,0.2);border-radius:10px;">
          <span style="font-size:16px;">${emoji('star', '⭐', 16)}</span>
          <span style="font-size:14px;font-weight:700;color:var(--purple-light);" id="xp-earned">...</span>
        </div>
      </div>

      <!-- Rating change -->
      <div id="rating-section" style="font-size:14px;font-weight:600;color:var(--text-secondary);animation:fadeSlideUp 0.4s ease 0.6s both;">${t('game.rating')}: ...</div>

      <!-- Actions -->
      <div style="display:flex;gap:10px;margin-top:16px;width:100%;max-width:300px;animation:fadeSlideUp 0.4s ease 0.7s both;">
        <button class="btn btn-primary" id="btn-rematch" style="flex:1;min-height:48px;border-radius:14px;font-size:15px;font-weight:700;background:linear-gradient(135deg,var(--emerald),var(--cyan));">${t('result.rematch')}</button>
        <button class="btn btn-secondary" id="btn-back" style="flex:1;min-height:48px;border-radius:14px;font-size:15px;font-weight:700;background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.1);color:var(--text-light);">${t('common.back')}</button>
      </div>
    </div>
    <style>
      @keyframes bounceIn { 0%{transform:scale(0);opacity:0} 60%{transform:scale(1.2)} 100%{transform:scale(1);opacity:1} }
      @keyframes fadeSlideUp { from{transform:translateY(12px);opacity:0} to{transform:translateY(0);opacity:1} }
    </style>
  `;

  animateCounter(el.querySelector('#score-me'), 0, myScore, 800);
  animateCounter(el.querySelector('#score-opp'), 0, oppScore, 800);

  if (isWin) {
    audio.play('win', 'reward');
    juice.hapticSuccess?.();
    juice.screenFlash?.('#4ade80', 300);

    setTimeout(() => {
      const iconEl = el.querySelector('#result-icon');
      if (iconEl) {
        const rect = iconEl.getBoundingClientRect();
        juice.confetti?.(rect.left + rect.width / 2, rect.top + rect.height / 2, 60);
        juice.starBurst?.(rect.left + rect.width / 2, rect.top - 20, 15);
      }
    }, 300);

    setTimeout(() => {
      const cx = window.innerWidth / 2;
      juice.confetti?.(cx - 60, 80, 30);
      juice.confetti?.(cx + 60, 80, 30);
    }, 900);

    setTimeout(() => {
      juice.confetti?.(window.innerWidth / 2, window.innerHeight / 3, 40);
      juice.starBurst?.(window.innerWidth / 2, window.innerHeight / 4, 12);
      juice.hapticMedium?.();
    }, 1500);

    setTimeout(() => {
      const scoreEl = el.querySelector('#score-me');
      if (scoreEl) juice.pulseElement?.(scoreEl, '#fbbf24', 800);
    }, 800);
  } else if (!isDraw) {
    audio.play('lose', 'game');
    juice.shake?.(el.querySelector('#result-wrap'), 4);
  }

  completeOnServer(el, matchId, result, mode);

  el.querySelector('#btn-rematch').addEventListener('click', () => {
    audio.play('click');
    scene.replace('domino-game', { mode });
  });

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

async function completeOnServer(el, matchId, result, mode) {
  const fallbackCoins = result === 'win' ? 50 : result === 'draw' ? 20 : 10;
  const fallbackXp = 15;
  const fallbackRating = result === 'win' ? 12 : result === 'draw' ? 1 : -8;

  let coins = fallbackCoins;
  let xp = fallbackXp;
  let ratingChange = fallbackRating;

  // For bot games, call complete with rewards; live games already called complete in game.js
  if (matchId && mode === 'bot') {
    try {
      const data = await net.post('domino-match.php', {
        action: 'complete',
        match_id: matchId,
        winners: result === 'win' ? [store.get('auth.userId')] : [],
        reason: result === 'draw' ? 'draw' : 'normal'
      });

      if (data && !data.error) {
        coins = data.coins_earned ?? fallbackCoins;
        xp = data.xp_earned ?? fallbackXp;
        ratingChange = data.rating_change ?? fallbackRating;
      }
    } catch (e) {}
  }

  const coinsEl = el.querySelector('#coins-earned');
  const xpEl = el.querySelector('#xp-earned');
  const ratingEl = el.querySelector('#rating-section');

  if (coinsEl) coinsEl.textContent = `+${coins}`;
  if (xpEl) xpEl.textContent = `+${xp} XP`;
  if (ratingEl) {
    const sign = ratingChange >= 0 ? '+' : '';
    const color = ratingChange > 0 ? 'var(--green-light)' : ratingChange === 0 ? 'var(--amber)' : 'var(--red-soft)';
    ratingEl.innerHTML = `${t('game.rating')}: <span style="color:${color};font-weight:700;">${sign}${ratingChange}</span>`;
  }

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

function animateCounter(el, from, to, duration) {
  if (!el || from === to) { if (el) el.textContent = to; return; }
  const start = performance.now();
  function frame(now) {
    const progress = Math.min((now - start) / duration, 1);
    const eased = 1 - Math.pow(1 - progress, 3);
    el.textContent = Math.round(from + (to - from) * eased);
    if (progress < 1) requestAnimationFrame(frame);
  }
  requestAnimationFrame(frame);
}
