const channelToken = new URLSearchParams(window.location.hash.slice(1)).get('channelToken');

function notify(type, payload = {}) {
  window.parent.postMessage({ type, token: channelToken, ...payload }, '*');
}

const arena = document.getElementById('arena');
const banner = document.getElementById('successBanner');
const finalScoreEl = document.getElementById('finalScore');

let score = 0;
let timeLeft = 30;
let gameActive = true;

// Criar timer na cena
const timerEl = document.createElement('div');
timerEl.className = 'absolute top-4 left-1/2 -translate-x-1/2 text-4xl font-bold text-red-600 bg-white px-6 py-2 rounded-full shadow-xl';
timerEl.textContent = `${timeLeft}s`;
arena.appendChild(timerEl);

// Criar contador de score na cena
const scoreEl = document.createElement('div');
scoreEl.className = 'absolute top-4 right-4 text-2xl font-bold text-green-600 bg-white px-4 py-2 rounded-full shadow-xl';
scoreEl.textContent = `0 alvos`;
arena.appendChild(scoreEl);

notify('started');

const spawnInterval = setInterval(() => {
  if (gameActive) spawnTarget();
}, 800);

const countdown = setInterval(() => {
  timeLeft--;
  timerEl.textContent = `${timeLeft}s`;
  
  if (timeLeft <= 0) {
    endGame();
  }
}, 1000);

function spawnTarget() {
  const SIZE = 100;
  const maxX = arena.clientWidth - SIZE - 20;
  const maxY = arena.clientHeight - SIZE - 20;
  const x = Math.floor(Math.random() * maxX) + 10;
  const y = Math.floor(Math.random() * maxY) + 10;
  
  const target = document.createElement('button');
  target.className = 'absolute bg-gradient-to-br from-red-500 to-red-600 rounded-full shadow-2xl fading';
  target.style.width = `${SIZE}px`;
  target.style.height = `${SIZE}px`;
  target.style.left = `${x}px`;
  target.style.top = `${y}px`;
  
  arena.appendChild(target);
  
  target.addEventListener('click', () => {
    target.remove();
    score++;
    scoreEl.textContent = `${score} alvos`;
    notify('running', { score });
  });
  
  setTimeout(() => target.remove(), 1500);
}

function endGame() {
  gameActive = false;
  clearInterval(spawnInterval);
  clearInterval(countdown);
  
  arena.classList.add('hidden');
  finalScoreEl.textContent = `Você clicou ${score} alvos em 30 segundos!`;
  banner.classList.remove('hidden');
  lucide.createIcons();
  
  notify('success', { score });
  notify('completed', { score });
}
