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

const width = arena.clientWidth;
const height = arena.clientHeight;
svg.setAttribute('viewBox', `0 0 ${width} ${height}`);

let started = false;
let onPath = true;
let progress = 0;
const TARGET_PROGRESS = 90;

notify('started');

// 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.classList.add('pulse-circle');
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
const animatePulseRing = () => {
  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" />';
};
animatePulseRing();

// 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.classList.remove('pulse-circle');
    pulseRing.remove(); // Remove o anel pulsante
    startText.remove(); // Remove o texto
    notify('running', { progress: 0 });
  }
});

// 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; // Só processa se a atividade foi iniciada
  
  const rect = svg.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;
  
  // Check if on path (simplified: check distance from 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);
      notify('running', { progress: Math.floor(progress) });
      
      if (progress >= TARGET_PROGRESS) {
        finishActivity();
      }
    }
  }
});

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