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 remaining = 10;

notify('started');

function createTargets() {
  for (let i = 0; i < 10; i++) {
    const SIZE = 80;
    const maxX = arena.clientWidth - SIZE - 20;
    const maxY = arena.clientHeight - SIZE - 20;
    
    let x, y, overlapping;
    do {
      overlapping = false;
      x = Math.floor(Math.random() * maxX) + 10;
      y = Math.floor(Math.random() * maxY) + 10;
      
      document.querySelectorAll('.target').forEach(existing => {
        const ex = parseInt(existing.style.left);
        const ey = parseInt(existing.style.top);
        const dist = Math.sqrt((x - ex) ** 2 + (y - ey) ** 2);
        if (dist < SIZE + 20) overlapping = true;
      });
    } while (overlapping);
    
    const target = document.createElement('button');
    target.className = 'target absolute bg-gradient-to-br from-red-500 to-red-600 rounded-full shadow-lg hover:scale-110 transition-transform';
    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.classList.remove('from-red-500', 'to-red-600');
      target.classList.add('from-green-400', 'to-green-500', 'opacity-50');
      target.disabled = true;
      
      remaining--;
      notify('running', { remaining });
      
      if (remaining === 0) {
        setTimeout(() => {
          arena.classList.add('hidden');
          banner.classList.remove('hidden');
          lucide.createIcons();
          notify('success', { score: 100 });
          notify('completed', { score: 100 });
        }, 500);
      }
    });
  }
}

createTargets();
