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 contextMenu = document.getElementById('contextMenu');
const banner = document.getElementById('successBanner');

let currentStep = 0;

notify('started');

// Create target icon
const target = document.createElement('div');
target.className = 'flex items-center gap-3 bg-white border-2 border-gray-300 rounded-lg p-6 shadow-lg';
target.innerHTML = `
  <i data-lucide="file" class="w-16 h-16 text-red-500"></i>
  <div>
    <p class="text-2xl font-bold text-gray-800">Documento.txt</p>
    <p class="text-sm text-gray-600">Clique com botão direito aqui</p>
  </div>
`;
arena.appendChild(target);
lucide.createIcons();

target.addEventListener('contextmenu', (e) => {
  e.preventDefault();
  
  if (currentStep === 0) {
    notify('running', { step: 1 });
    currentStep = 1;
  }
  showContextMenu(e.pageX, e.pageY);
});

function showContextMenu(x, y) {
  contextMenu.style.left = `${x - arena.getBoundingClientRect().left}px`;
  contextMenu.style.top = `${y - arena.getBoundingClientRect().top}px`;
  contextMenu.innerHTML = `
    <button class="w-full text-left px-4 py-2 hover:bg-gray-100 rounded flex items-center gap-2" data-action="open">
      <i data-lucide="folder-open" class="w-4 h-4"></i>
      Abrir
    </button>
    <button class="w-full text-left px-4 py-2 hover:bg-gray-100 rounded flex items-center gap-2" data-action="copy">
      <i data-lucide="copy" class="w-4 h-4"></i>
      Copiar
    </button>
    <button class="w-full text-left px-4 py-2 hover:bg-gray-100 rounded flex items-center gap-2" data-action="delete">
      <i data-lucide="trash-2" class="w-4 h-4"></i>
      Excluir
    </button>
  `;
  contextMenu.classList.remove('hidden');
  lucide.createIcons();
  
  contextMenu.querySelectorAll('button').forEach(btn => {
    btn.addEventListener('click', () => {
      contextMenu.classList.add('hidden');
      target.remove();
      arena.classList.add('hidden');
      banner.classList.remove('hidden');
      lucide.createIcons();
      notify('success', { score: 100 });
      notify('completed', { score: 100 });
    });
  });
}

document.addEventListener('click', () => {
  contextMenu.classList.add('hidden');
});
