const channelToken = new URLSearchParams(window.location.hash.slice(1)).get('channelToken');

function notify(type, payload = {}) {
  window.parent.postMessage({ type, token: channelToken, ...payload }, '*');
}

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const banner = document.getElementById('successBanner');

canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;

let drawing = false;
let coverage = 0;
const TARGET_COVERAGE = 60;
const circleSegments = new Set(); // Track which parts of the circle were drawn

notify('started');

// Draw guide path (dotted circle)
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = Math.min(canvas.width, canvas.height) * 0.3;

ctx.setLineDash([10, 10]);
ctx.strokeStyle = '#ef4444';
ctx.lineWidth = 6;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
ctx.stroke();
ctx.setLineDash([]);

// User drawing
let points = [];

canvas.addEventListener('mousedown', (e) => {
  drawing = true;
  const rect = canvas.getBoundingClientRect();
  points = [{ x: e.clientX - rect.left, y: e.clientY - rect.top }];
});

canvas.addEventListener('mousemove', (e) => {
  if (!drawing) return;
  
  const rect = canvas.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;
  
  points.push({ x, y });
  
  // Draw line
  ctx.strokeStyle = '#22c55e';
  ctx.lineWidth = 8;
  ctx.lineCap = 'round';
  ctx.lineJoin = 'round';
  ctx.beginPath();
  ctx.moveTo(points[points.length - 2].x, points[points.length - 2].y);
  ctx.lineTo(x, y);
  ctx.stroke();
  
  // Check if close to guide circle and mark segment as covered
  const dist = Math.sqrt((x - centerX) ** 2 + (y - centerY) ** 2);
  if (Math.abs(dist - radius) < 30) {
    // Calculate angle (0-360) to determine which segment of the circle
    const angle = Math.atan2(y - centerY, x - centerX);
    const degrees = ((angle * 180 / Math.PI) + 360) % 360;
    const segment = Math.floor(degrees / 3); // Divide circle in 120 segments (360/3)
    
    if (!circleSegments.has(segment)) {
      circleSegments.add(segment);
      coverage = (circleSegments.size / 120) * 100;
      notify('running', { coverage: Math.floor(coverage) });
      
      if (coverage >= TARGET_COVERAGE) {
        finishActivity();
      }
    }
  }
});

canvas.addEventListener('mouseup', () => {
  drawing = false;
});

canvas.addEventListener('mouseleave', () => {
  drawing = false;
});

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