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

let currentChallenge = 0;
const challenges = [
  { name: 'Fase 1: Cliques Precisos', task: precisionChallenge },
  { name: 'Fase 2: Sequência Rápida', task: sequenceSpeedChallenge },
  { name: 'Fase 3: Seguir Trilha', task: pathFollowChallenge },
  { name: 'Fase 4: Múltiplos Alvos', task: multiTargetChallenge },
  { name: 'Fase 5: Menu de Contexto', task: contextMenuChallenge },
  { name: 'Fase 6: Organizar Arquivos', task: fileOrganizerChallenge },
  { name: 'Fase 7: Desenhar Círculo', task: drawCircleChallenge },
  { name: 'Fase 8: Desafio Final', task: finalBossChallenge },
];

notify('started');

function nextChallenge() {
  if (currentChallenge >= challenges.length) {
    finishActivity();
    return;
  }
  
  arena.innerHTML = '';
  const challenge = challenges[currentChallenge];
  instrEl.textContent = challenge.name;
  notify('running', { step: currentChallenge + 1 });
  challenge.task();
}

// Fase 1: Cliques em alvos progressivamente menores (precisão)
function precisionChallenge() {
  let targets = 0;
  const sizes = [80, 60, 45, 35];
  
  function createTarget() {
    if (targets >= sizes.length) {
      currentChallenge++;
      setTimeout(nextChallenge, 800);
      return;
    }
    
    const target = document.createElement('button');
    const size = sizes[targets];
    const maxX = arena.clientWidth - size - 20;
    const maxY = arena.clientHeight - size - 20;
    
    target.className = 'absolute bg-gradient-to-br from-red-500 to-red-600 rounded-full shadow-xl hover:scale-110 transition-transform';
    target.style.width = `${size}px`;
    target.style.height = `${size}px`;
    target.style.left = `${20 + Math.random() * maxX}px`;
    target.style.top = `${20 + Math.random() * maxY}px`;
    target.innerHTML = `<span class="text-white text-xl font-bold">${targets + 1}</span>`;
    
    target.addEventListener('click', () => {
      target.remove();
      targets++;
      createTarget();
    });
    
    arena.appendChild(target);
  }
  
  createTarget();
}

// Fase 2: Clicar números 1-5 o mais rápido possível
function sequenceSpeedChallenge() {
  const startTime = Date.now();
  let current = 1;
  const total = 5;
  
  for (let i = 1; i <= total; i++) {
    const btn = document.createElement('button');
    btn.className = 'absolute w-20 h-20 bg-red-500 text-white text-2xl font-bold rounded-full shadow-lg hover:scale-110 transition-transform';
    btn.textContent = i;
    btn.style.left = `${Math.random() * (arena.clientWidth - 100)}px`;
    btn.style.top = `${Math.random() * (arena.clientHeight - 100)}px`;
    
    btn.addEventListener('click', () => {
      if (i === current) {
        btn.classList.remove('bg-red-500', 'to-red-600');
        btn.classList.add('bg-green-400', 'to-green-500', 'opacity-50');
        // btn.style.background = '#10b981';
        btn.disabled = true;
        current++;
        
        if (current > total) {
          const time = ((Date.now() - startTime) / 1000).toFixed(1);
          setTimeout(() => {
            instrEl.textContent = `Fase 2: Concluída em ${time}s!`;
            currentChallenge++;
            setTimeout(nextChallenge, 1500);
          }, 300);
        }
      } else {
        btn.classList.add('animate-bounce');
        setTimeout(() => btn.classList.remove('animate-bounce'), 500);
      }
    });
    
    arena.appendChild(btn);
  }
}

// Fase 3: Seguir caminho sem sair (CÓPIA EXATA da atividade mouse-controle)
function pathFollowChallenge() {
  const width = arena.clientWidth;
  const height = arena.clientHeight;
  
  // Criar SVG
  const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  svg.setAttribute('width', width);
  svg.setAttribute('height', height);
  svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
  svg.className = 'absolute inset-0';
  arena.appendChild(svg);
  
  let started = false;
  let progress = 0;
  let completed = false; // Flag para evitar múltiplas conclusões
  const TARGET_PROGRESS = 90;
  
  // Create curved path
  const pathData = `M 50,${height/2} 
    Q ${width/4},${height/4} ${width/2},${height/2}
    T ${width-50},${height/2}`;
  
  // Background path (wider, gray)
  const bgPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
  bgPath.setAttribute('d', pathData);
  bgPath.setAttribute('stroke', '#e5e7eb');
  bgPath.setAttribute('stroke-width', '120');
  bgPath.setAttribute('fill', 'none');
  bgPath.setAttribute('stroke-linecap', 'round');
  svg.appendChild(bgPath);
  
  // Progress path (green)
  const progressPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
  progressPath.setAttribute('d', pathData);
  progressPath.setAttribute('stroke', '#22c55e');
  progressPath.setAttribute('stroke-width', '100');
  progressPath.setAttribute('fill', 'none');
  progressPath.setAttribute('stroke-linecap', 'round');
  progressPath.setAttribute('stroke-dasharray', '1000');
  progressPath.setAttribute('stroke-dashoffset', '1000');
  svg.appendChild(progressPath);
  
  // Start point with pulse animation
  const startCircle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
  startCircle.setAttribute('cx', '50');
  startCircle.setAttribute('cy', height/2);
  startCircle.setAttribute('r', '30');
  startCircle.setAttribute('fill', '#ef4444');
  startCircle.setAttribute('cursor', 'pointer');
  startCircle.style.animation = 'pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite';
  svg.appendChild(startCircle);
  
  // Pulse ring for extra visibility
  const pulseRing = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
  pulseRing.setAttribute('cx', '50');
  pulseRing.setAttribute('cy', height/2);
  pulseRing.setAttribute('r', '30');
  pulseRing.setAttribute('fill', 'none');
  pulseRing.setAttribute('stroke', '#ef4444');
  pulseRing.setAttribute('stroke-width', '3');
  svg.appendChild(pulseRing);
  
  // Animate pulse ring
  pulseRing.innerHTML = '<animate attributeName="r" from="30" to="50" dur="1.5s" repeatCount="indefinite" /><animate attributeName="opacity" from="0.8" to="0" dur="1.5s" repeatCount="indefinite" />';
  
  // Add "Click here" text
  const startText = document.createElementNS('http://www.w3.org/2000/svg', 'text');
  startText.setAttribute('x', '50');
  startText.setAttribute('y', height/2 + 60);
  startText.setAttribute('text-anchor', 'middle');
  startText.setAttribute('fill', '#ef4444');
  startText.setAttribute('font-size', '16');
  startText.setAttribute('font-weight', 'bold');
  startText.textContent = 'Clique aqui';
  svg.appendChild(startText);
  
  // Add click to start
  startCircle.addEventListener('click', () => {
    if (!started) {
      started = true;
      startCircle.setAttribute('fill', '#22c55e');
      startCircle.style.animation = '';
      pulseRing.remove();
      startText.remove();
    }
  });
  
  // End point
  const endCircle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
  endCircle.setAttribute('cx', width - 50);
  endCircle.setAttribute('cy', height/2);
  endCircle.setAttribute('r', '30');
  endCircle.setAttribute('fill', '#22c55e');
  svg.appendChild(endCircle);
  
  // Track mouse movement
  svg.addEventListener('mousemove', (e) => {
    if (!started) return;
    
    const rect = svg.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    // Check if on path
    const pathLength = bgPath.getTotalLength();
    let minDist = Infinity;
    
    for (let i = 0; i < pathLength; i += 10) {
      const point = bgPath.getPointAtLength(i);
      const dist = Math.sqrt((x - point.x) ** 2 + (y - point.y) ** 2);
      if (dist < minDist) minDist = dist;
    }
    
    if (minDist < 60) {
      // On path
      const progressPercent = (x / width) * 100;
      if (progressPercent > progress) {
        progress = progressPercent;
        const offset = 1000 - (progress / 100) * 1000;
        progressPath.setAttribute('stroke-dashoffset', offset);
        
        if (progress >= TARGET_PROGRESS && !completed) {
          // Avança para a próxima fase do desafio completo
          completed = true;
          currentChallenge++;
          setTimeout(nextChallenge, 800);
        }
      }
    }
  });
}

// Fase 4: Clicar 8 alvos simultâneos
function multiTargetChallenge() {
  let remaining = 8;
  
  for (let i = 0; i < remaining; i++) {
    const target = document.createElement('button');
    target.className = 'absolute w-16 h-16 bg-gradient-to-br from-red-500 to-red-600 rounded-full shadow-lg hover:scale-110 transition-transform';
    target.style.left = `${50 + Math.random() * (arena.clientWidth - 150)}px`;
    target.style.top = `${50 + Math.random() * (arena.clientHeight - 150)}px`;
    
    const bullseye = document.createElement('div');
    bullseye.className = 'absolute inset-0 flex items-center justify-center';
    bullseye.innerHTML = '<div class="w-6 h-6 bg-white rounded-full"></div>';
    target.appendChild(bullseye);
    

    target.addEventListener('click', () => {
      target.remove();
      remaining--;
      
      if (remaining === 0) {
        currentChallenge++;
        setTimeout(nextChallenge, 800);
      }
    });
    
    arena.appendChild(target);
  }
  
  lucide.createIcons();
}

// Fase 5: Menu de contexto e seleção correta
function contextMenuChallenge() {
  const file = document.createElement('div');
  file.className = 'absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-32 h-32 bg-white border-2 border-gray-300 rounded-lg flex flex-col items-center justify-center gap-2 cursor-pointer';
  file.innerHTML = '<i data-lucide="file-text" class="w-16 h-16 text-blue-500"></i><span class="text-sm font-semibold">arquivo.txt</span>';
  arena.appendChild(file);
  
  const menu = document.createElement('div');
  menu.className = 'absolute hidden bg-white rounded-lg shadow-2xl border border-gray-200 py-2 min-w-[180px]';
  menu.innerHTML = `
    <button class="w-full px-4 py-2 text-left hover:bg-gray-100 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 px-4 py-2 text-left hover:bg-gray-100 flex items-center gap-2" data-action="copy">
      <i data-lucide="copy" class="w-4 h-4"></i>Copiar
    </button>
    <button class="w-full px-4 py-2 text-left hover:bg-gray-100 flex items-center gap-2" data-action="delete">
      <i data-lucide="trash-2" class="w-4 h-4 text-red-500"></i>Excluir
    </button>
    <button class="w-full px-4 py-2 text-left hover:bg-green-100 text-green-700 font-semibold flex items-center gap-2" data-action="properties">
      <i data-lucide="info" class="w-4 h-4"></i>Propriedades ✓
    </button>    
  `;
  arena.appendChild(menu);
  lucide.createIcons();
  
  file.addEventListener('contextmenu', (e) => {
    e.preventDefault();
    menu.classList.remove('hidden');
    menu.style.left = `${e.clientX - arena.getBoundingClientRect().left}px`;
    menu.style.top = `${e.clientY - arena.getBoundingClientRect().top}px`;
  });
  
  menu.querySelectorAll('button').forEach(btn => {
    btn.addEventListener('click', () => {
      if (btn.dataset.action === 'properties') {
        currentChallenge++;
        setTimeout(nextChallenge, 800);
      } else {
        menu.classList.add('hidden');
        btn.classList.add('bg-red-100');
        setTimeout(() => {
          btn.classList.remove('bg-red-100');
          menu.classList.add('hidden');
        }, 500);
      }
    });
  });
  
  arena.addEventListener('click', () => {
    menu.classList.add('hidden');
  });
}

// Fase 6: Arrastar 5 itens para pastas corretas
function fileOrganizerChallenge() {
  const files = [
    { name: 'foto.jpg', type: 'image', icon: 'image', folder: 'images' },
    { name: 'musica.mp3', type: 'music', icon: 'music', folder: 'music' },
    { name: 'video.mp4', type: 'video', icon: 'video', folder: 'videos' },
    { name: 'doc.pdf', type: 'document', icon: 'file-text', folder: 'documents' },
    { name: 'code.js', type: 'code', icon: 'code', folder: 'code' },
  ];
  
  const folders = [
    { id: 'images', label: 'Imagens', color: 'blue' },
    { id: 'music', label: 'Músicas', color: 'purple' },
    { id: 'videos', label: 'Vídeos', color: 'red' },
    { id: 'documents', label: 'Documentos', color: 'yellow' },
    { id: 'code', label: 'Código', color: 'green' },
  ];
  
  let completed = 0;
  
  // Criar pastas
  folders.forEach((folder, i) => {
    const div = document.createElement('div');
    div.className = `absolute w-28 h-28 border-4 border-dashed border-${folder.color}-400 bg-${folder.color}-50 rounded-xl flex flex-col items-center justify-center gap-1`;
    div.style.left = `${50 + i * 140}px`;
    div.style.bottom = '30px';
    div.innerHTML = `<i data-lucide="folder" class="w-8 h-8 text-${folder.color}-600"></i><span class="text-xs font-semibold text-${folder.color}-700">${folder.label}</span>`;
    div.dataset.folderId = folder.id;
    arena.appendChild(div);
    
    div.addEventListener('dragover', (e) => {
      e.preventDefault();
      div.classList.add('scale-110', 'shadow-xl');
    });
    
    div.addEventListener('dragleave', () => {
      div.classList.remove('scale-110', 'shadow-xl');
    });
    
    div.addEventListener('drop', (e) => {
      e.preventDefault();
      div.classList.remove('scale-110', 'shadow-xl');
      
      const fileId = e.dataTransfer.getData('text/plain');
      const file = files.find(f => f.name === fileId);
      
      if (file && file.folder === folder.id) {
        const dragged = document.querySelector(`[data-file="${fileId}"]`);
        if (dragged) {
          dragged.remove();
          completed++;
          
          if (completed === files.length) {
            currentChallenge++;
            setTimeout(nextChallenge, 800);
          }
        }
      } else {
        div.classList.add('animate-bounce');
        setTimeout(() => div.classList.remove('animate-bounce'), 500);
      }
    });
  });
  
  // Criar arquivos
  files.forEach((file, i) => {
    const div = document.createElement('div');
    div.className = 'absolute w-20 h-20 bg-white border-2 border-gray-300 rounded-lg cursor-grab flex flex-col items-center justify-center gap-1 hover:shadow-lg transition-shadow';
    div.style.left = `${100 + i * 100}px`;
    div.style.top = '80px';
    div.innerHTML = `<i data-lucide="${file.icon}" class="w-8 h-8 text-gray-700"></i><span class="text-xs font-medium truncate">${file.name}</span>`;
    div.draggable = true;
    div.dataset.file = file.name;
    
    div.addEventListener('dragstart', (e) => {
      e.dataTransfer.setData('text/plain', file.name);
      div.classList.add('opacity-50');
    });
    
    div.addEventListener('dragend', () => {
      div.classList.remove('opacity-50');
    });
    
    arena.appendChild(div);
  });
  
  lucide.createIcons();
}

// Fase 7: Desenhar círculo com 60% de cobertura
function drawCircleChallenge() {
  const canvas = document.createElement('canvas');
  canvas.width = arena.clientWidth;
  canvas.height = arena.clientHeight;
  canvas.className = 'absolute inset-0';
  arena.appendChild(canvas);
  
  const ctx = canvas.getContext('2d');
  const centerX = canvas.width / 2;
  const centerY = canvas.height / 2;
  const radius = 120;
  
  // Desenha círculo guia pontilhado
  ctx.setLineDash([10, 10]);
  ctx.strokeStyle = '#9ca3af';
  ctx.lineWidth = 3;
  ctx.beginPath();
  ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
  ctx.stroke();
  ctx.setLineDash([]);
  
  // Texto instrução
  ctx.fillStyle = '#6b7280';
  ctx.font = 'bold 16px sans-serif';
  ctx.textAlign = 'center';
  ctx.fillText('Desenhe sobre o círculo (60% mínimo)', centerX, centerY - radius - 30);
  
  let isDrawing = false;
  const segments = new Set();
  const totalSegments = 120;
  
  canvas.addEventListener('mousedown', () => {
    isDrawing = true;
  });
  
  canvas.addEventListener('mousemove', (e) => {
    if (!isDrawing) return;
    
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    const dist = Math.hypot(x - centerX, y - centerY);
    
    if (Math.abs(dist - radius) < 25) {
      const angle = Math.atan2(y - centerY, x - centerX);
      const segmentId = Math.floor(((angle + Math.PI) / (2 * Math.PI)) * totalSegments);
      segments.add(segmentId);
      
      // Desenha ponto
      ctx.fillStyle = '#ef4444';
      ctx.beginPath();
      ctx.arc(x, y, 4, 0, Math.PI * 2);
      ctx.fill();
      
      const coverage = (segments.size / totalSegments) * 100;
      
      if (coverage >= 60) {
        isDrawing = false;
        setTimeout(() => {
          currentChallenge++;
          nextChallenge();
        }, 500);
      }
    }
  });
  
  canvas.addEventListener('mouseup', () => {
    isDrawing = false;
  });
}

// Fase 8: Desafio final - alvos móveis com tempo limitado
function finalBossChallenge() {
  let score = 0;
  let timeLeft = 20;
  const targetCount = 25;
  
  const timer = document.createElement('div');
  timer.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';
  arena.appendChild(timer);
  
  const scoreDisplay = document.createElement('div');
  scoreDisplay.className = 'absolute top-4 right-4 text-2xl font-bold text-green-600 bg-white px-4 py-2 rounded-full shadow-xl';
  arena.appendChild(scoreDisplay);
  
  function updateDisplay() {
    timer.textContent = `${timeLeft}s`;
    scoreDisplay.textContent = `${score}/${targetCount}`;
  }
  
  function createMovingTarget() {
    const target = document.createElement('button');
    const size = 40 + Math.random() * 30;
    target.className = 'absolute bg-gradient-to-br from-red-500 to-orange-500 rounded-full shadow-xl hover:scale-125 transition-transform';
    target.style.width = `${size}px`;
    target.style.height = `${size}px`;
    
    let x = Math.random() * (arena.clientWidth - size);
    let y = Math.random() * (arena.clientHeight - size);
    let vx = (Math.random() - 0.5) * 3;
    let vy = (Math.random() - 0.5) * 3;
    
    target.style.left = `${x}px`;
    target.style.top = `${y}px`;
    
    const moveInterval = setInterval(() => {
      x += vx;
      y += vy;
      
      if (x < 0 || x > arena.clientWidth - size) vx *= -1;
      if (y < 0 || y > arena.clientHeight - size) vy *= -1;
      
      target.style.left = `${x}px`;
      target.style.top = `${y}px`;
    }, 20);
    
    target.addEventListener('click', () => {
      clearInterval(moveInterval);
      target.remove();
      score++;
      updateDisplay();
      
      if (score >= targetCount) {
        clearInterval(gameInterval);
        setTimeout(() => {
          currentChallenge++;
          nextChallenge();
        }, 500);
      } else {
        createMovingTarget();
      }
    });
    
    arena.appendChild(target);
  }
  
  // Criar alvos iniciais
  for (let i = 0; i < 5; i++) {
    createMovingTarget();
  }
  
  updateDisplay();
  
  const gameInterval = setInterval(() => {
    timeLeft--;
    updateDisplay();
    
    if (timeLeft <= 0) {
      clearInterval(gameInterval);
      if (score >= targetCount * 0.7) {
        alert(`Bom trabalho! ${score}/${targetCount} alvos`);
        currentChallenge++;
        nextChallenge();
      } else {
        alert(`Tempo esgotado! Você acertou ${score}/${targetCount}. Tente novamente!`);
        finalBossChallenge();
      }
    }
  }, 1000);
}

function finishActivity() {
  arena.classList.add('hidden');
  banner.classList.remove('hidden');
  lucide.createIcons();
  notify('success', { score: 100 });
  notify('completed', { score: 100 });
}

nextChallenge();
