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');

let currentTarget = 1;
const TOTAL_TARGETS = 5;
const targets = [];

notify('started');

function createTargets() {
  for (let i = 1; i <= TOTAL_TARGETS; i++) {
    const SIZE = 120;
    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 button = document.createElement('button');
    button.className = 'absolute bg-gradient-to-br from-gray-400 to-gray-500 rounded-full shadow-lg transition-all text-white font-bold text-4xl';
    button.style.width = `${SIZE}px`;
    button.style.height = `${SIZE}px`;
    button.style.left = `${x}px`;
    button.style.top = `${y}px`;
    button.textContent = i;
    button.dataset.number = i;
    
    arena.appendChild(button);
    targets.push(button);
    
    button.addEventListener('click', () => handleClick(parseInt(button.dataset.number)));
  }
  
  updateActiveTarget();
}

function updateActiveTarget() {
  targets.forEach((btn) => {
    const num = parseInt(btn.dataset.number);
    if (num === currentTarget) {
      btn.className = 'absolute bg-gradient-to-br from-red-500 to-red-600 rounded-full shadow-2xl text-white font-bold text-4xl pulse-active';
    } else if (num < currentTarget) {
      btn.className = 'absolute bg-gradient-to-br from-green-400 to-green-500 rounded-full shadow-lg text-white font-bold text-4xl opacity-50';
    }
  });
}

function handleClick(num) {
  if (num === currentTarget) {
    notify('running', { step: currentTarget });
    currentTarget++;
    
    if (currentTarget > TOTAL_TARGETS) {
      arena.classList.add('hidden');
      banner.classList.remove('hidden');
      lucide.createIcons();
      notify('success', { score: 100 });
      notify('completed', { score: 100 });
    } else {
      updateActiveTarget();
    }
  }
}

createTargets();
