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

let confettiRaf = null;

export function mountResult(el, params) {
  const { winner = 'you', scores = [0, 0], matchLength = 3, mode = 'bot', reason = '' } = params || {};
  const didWin = winner === 'you';

  audio.play(didWin ? 'sfx_bg_win_match' : 'lose', 'game');

  el.innerHTML = `
    <div class="bgr-wrap">
      <canvas class="bgr-confetti" id="confetti-canvas"></canvas>
      <div class="bgr-content">
        <div class="bgr-hero">
          <div class="bgr-trophy-ring ${didWin ? 'bgr-win-ring' : 'bgr-lose-ring'}">
            <div class="bgr-trophy">${didWin ? emoji('trophy', '🏆', 56) : emoji('pensive', '😔', 56)}</div>
          </div>
          <h1 class="bgr-title">${didWin ? 'مبروك! فزت بالماتش!' : 'خسرت هالمرة...'}</h1>
          <p class="bgr-subtitle">${reason === 'abandon' ? 'الخصم انسحب من اللعبة' : didWin ? 'أداء ممتاز!' : 'حاول مرة ثانية!'}</p>
        </div>

        <div class="bgr-scoreboard">
          <div class="bgr-score-col">
            <div class="bgr-score-val ${didWin ? 'bgr-val-win' : ''}">${scores[0]}</div>
            <div class="bgr-score-label">أنت</div>
          </div>
          <div class="bgr-score-vs">
            <div class="bgr-vs-line"></div>
            <span class="bgr-vs-text">من ${matchLength}</span>
            <div class="bgr-vs-line"></div>
          </div>
          <div class="bgr-score-col">
            <div class="bgr-score-val ${!didWin ? 'bgr-val-win' : ''}">${scores[1]}</div>
            <div class="bgr-score-label">الخصم</div>
          </div>
        </div>

        <div class="bgr-rewards" style="display:flex;gap:10px;margin-bottom:20px;flex-wrap:wrap;justify-content:center;">
          <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;">+${didWin ? 50 : 10}</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;">+15 XP</span>
          </div>
        </div>

        <div class="bgr-buttons">
          <button class="bgr-btn bgr-btn-primary" id="btn-rematch">
            ${emoji('fire', '🔥', 18)} العب مرة ثانية
          </button>
          <button class="bgr-btn bgr-btn-secondary" id="btn-exit">
            رجوع للقائمة
          </button>
        </div>
      </div>
    </div>
    ${getResultStyles()}
  `;

  el.querySelector('#btn-rematch').onclick = () => {
    audio.play('click');
    stopConfetti();
    scene.replace('backgammon-room', { mode: 'menu' });
  };
  el.querySelector('#btn-exit').onclick = () => {
    audio.play('click');
    stopConfetti();
    scene.exitGameMode();
    bus.emit('navigate', { world: 'play', scene: 'play-table' });
  };

  if (didWin) startConfetti(el.querySelector('#confetti-canvas'));

  bus.emit('coins:earned', { amount: didWin ? 50 : 10 });
  bus.emit('xp:earned', { amount: 15 });
}

function startConfetti(canvas) {
  if (!canvas) return;
  const ctx = canvas.getContext('2d');
  const w = canvas.parentElement.clientWidth;
  const h = canvas.parentElement.clientHeight;
  canvas.width = w;
  canvas.height = h;

  const colors = ['#FFD700', '#FF6347', '#10B981', '#8B5CF6', '#06B6D4', '#F59E0B', '#EC4899'];
  const confetti = [];

  for (let i = 0; i < 80; i++) {
    confetti.push({
      x: Math.random() * w,
      y: -20 - Math.random() * h * 0.5,
      vx: (Math.random() - 0.5) * 3,
      vy: 1.5 + Math.random() * 3,
      size: 4 + Math.random() * 6,
      color: colors[Math.floor(Math.random() * colors.length)],
      rot: Math.random() * Math.PI * 2,
      vr: (Math.random() - 0.5) * 0.15,
      shape: Math.random() > 0.5 ? 'rect' : 'circle'
    });
  }

  function draw() {
    ctx.clearRect(0, 0, w, h);
    for (const c of confetti) {
      c.x += c.vx;
      c.y += c.vy;
      c.rot += c.vr;
      c.vx += (Math.random() - 0.5) * 0.1;
      if (c.y > h + 20) { c.y = -20; c.x = Math.random() * w; }

      ctx.save();
      ctx.translate(c.x, c.y);
      ctx.rotate(c.rot);
      ctx.fillStyle = c.color;
      if (c.shape === 'rect') {
        ctx.fillRect(-c.size / 2, -c.size / 4, c.size, c.size / 2);
      } else {
        ctx.beginPath();
        ctx.arc(0, 0, c.size / 2, 0, Math.PI * 2);
        ctx.fill();
      }
      ctx.restore();
    }
    confettiRaf = requestAnimationFrame(draw);
  }
  draw();
}

function stopConfetti() {
  if (confettiRaf) { cancelAnimationFrame(confettiRaf); confettiRaf = null; }
}

function getResultStyles() {
  return `<style>
.bgr-wrap {
  position:relative;display:flex;align-items:center;justify-content:center;
  height:100%;
  background:linear-gradient(180deg,#060A10 0%,#0A1020 50%,#101828 100%);
  overflow:hidden;
}
.bgr-confetti {
  position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:0;
}
.bgr-content {
  position:relative;z-index:1;
  display:flex;flex-direction:column;align-items:center;padding:24px;width:100%;
}
.bgr-hero { text-align:center;margin-bottom:28px; }
.bgr-trophy-ring {
  width:90px;height:90px;border-radius:50%;margin:0 auto 16px;
  display:flex;align-items:center;justify-content:center;
  animation:trophyFloat 3s ease-in-out infinite;
}
.bgr-win-ring {
  background:conic-gradient(from 0deg,rgba(212,148,10,0.3),rgba(255,215,0,0.1),rgba(212,148,10,0.3));
  box-shadow:0 0 40px rgba(212,148,10,0.2);
}
.bgr-lose-ring {
  background:conic-gradient(from 0deg,rgba(100,100,100,0.2),rgba(60,60,60,0.1),rgba(100,100,100,0.2));
}
.bgr-trophy { font-size:56px; }
.bgr-title { font-size:22px;font-weight:800;color:#f8fafc;margin:0; }
.bgr-subtitle { font-size:13px;color:#64748b;margin:8px 0 0; }
@keyframes trophyFloat { 0%,100%{transform:translateY(0)} 50%{transform:translateY(-8px)} }

.bgr-scoreboard {
  display:flex;align-items:center;gap:20px;
  padding:24px 36px;border-radius:20px;
  background:rgba(255,255,255,0.02);border:1px solid rgba(255,255,255,0.05);
  backdrop-filter:blur(8px);margin-bottom:32px;
}
.bgr-score-col { display:flex;flex-direction:column;align-items:center;gap:6px; }
.bgr-score-val { font-size:36px;font-weight:900;color:#64748b;line-height:1; }
.bgr-val-win { color:#d4940a;text-shadow:0 0 20px rgba(212,148,10,0.4); }
.bgr-score-label { font-size:12px;color:#475569;font-weight:600; }
.bgr-score-vs { display:flex;align-items:center;gap:8px; }
.bgr-vs-line { width:20px;height:1px;background:rgba(255,255,255,0.08); }
.bgr-vs-text { font-size:11px;color:#475569;white-space:nowrap; }

.bgr-buttons { display:flex;flex-direction:column;gap:12px;width:100%;max-width:280px; }
.bgr-btn {
  padding:15px 24px;border-radius:14px;border:none;
  font-size:15px;font-weight:700;cursor:pointer;text-align:center;
  transition:transform 0.15s cubic-bezier(0.34,1.56,0.64,1);
}
.bgr-btn:active { transform:scale(0.93); }
.bgr-btn-primary {
  background:linear-gradient(135deg,#d4940a,#8B4513);color:#fff;
  box-shadow:0 6px 20px rgba(212,148,10,0.35);
}
.bgr-btn-secondary {
  background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.08);color:#94a3b8;
}
</style>`;
}
