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 ? 'استسلمت' : reason === 'resign' ? 'الخصم استسلم!' : reason === 'abandon' ? 'الخصم انقطع' : isWin ? 'فوز!' : isDraw ? 'تعادل' : 'خسارة';
  const titleColor = isWin ? '#4ade80' : isDraw ? '#fbbf24' : '#fca5a5';

  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%,#0a1420 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:#4ade80;" id="score-me">0</div>
          <div style="font-size:11px;color:#86efac;">أنت</div>
        </div>
        <div style="font-size:18px;color:#475569;">—</div>
        <div style="text-align:center;">
          <div style="font-size:32px;font-weight:800;color:#fca5a5;" id="score-opp">0</div>
          <div style="font-size:11px;color:#fca5a5;">خصم</div>
        </div>
      </div>

      <div style="font-size:12px;color:#64748b;animation:fadeSlideUp 0.4s ease 0.35s both;">${rounds} ${rounds === 1 ? 'جولة' : 'جولات'}</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:#fbbf24;" 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:#a78bfa;" id="xp-earned">...</span>
        </div>
      </div>

      <!-- Rating change -->
      <div id="rating-section" style="font-size:14px;font-weight:600;color:#94a3b8;animation:fadeSlideUp 0.4s ease 0.6s both;">التصنيف: ...</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,#10b981,#06b6d4);">إعادة</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:#e2e8f0;">رجوع</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 ? '#4ade80' : ratingChange === 0 ? '#fbbf24' : '#fca5a5';
    ratingEl.innerHTML = `التصنيف: <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);
}
