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

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

notify('started');

const steps = [
  {
    text: 'Passo 1: Pressione → três vezes',
    hint: 'A seta para direita move o cursor uma letra por vez.',
    action: 'arrow-right',
    count: 3,
  },
  {
    text: 'Passo 2: Pressione ← duas vezes',
    hint: 'A seta para esquerda volta o cursor.',
    action: 'arrow-left',
    count: 2,
  },
  {
    text: 'Passo 3: Pressione Home',
    hint: 'Home vai para o INÍCIO da linha.',
    action: 'home',
    count: 1,
  },
  {
    text: 'Passo 4: Pressione End',
    hint: 'End vai para o FINAL da linha.',
    action: 'end',
    count: 1,
  },
];

let currentStep = 0;
let actionCount = 0;
let locked = false;

const textArea = document.getElementById('textArea');
const stepText = document.getElementById('stepText');
const stepHint = document.getElementById('stepHint');
const feedbackEl = document.getElementById('feedback');
const cursorPos = document.getElementById('cursorPos');
const progressDots = document.getElementById('progressDots');
const successBanner = document.getElementById('successBanner');
const stepBox = document.getElementById('stepBox');

textArea.value = 'Olá mundo!';
textArea.readOnly = false;
textArea.focus();
textArea.setSelectionRange(0, 0);

steps.forEach((_, i) => {
  const dot = document.createElement('div');
  dot.id = `dot-${i}`;
  dot.className = 'w-8 h-8 rounded-full border-2 border-gray-300 bg-gray-100 transition-all';
  progressDots.appendChild(dot);
});

function showStep() {
  const s = steps[currentStep];
  stepText.textContent = s.text;
  stepHint.textContent = s.hint;
  actionCount = 0;
  feedbackEl.classList.add('hidden');
  textArea.focus();
}
showStep();

textArea.addEventListener('keydown', (e) => {
  if (locked) return;
  const s = steps[currentStep];
  const pos = textArea.selectionStart;
  cursorPos.textContent = `Posição do cursor: ${pos}`;

  let matched = false;
  if (s.action === 'arrow-right' && e.key === 'ArrowRight') matched = true;
  if (s.action === 'arrow-left' && e.key === 'ArrowLeft') matched = true;
  if (s.action === 'home' && e.key === 'Home') matched = true;
  if (s.action === 'end' && e.key === 'End') matched = true;

  if (matched) {
    actionCount++;
    feedbackEl.textContent = `${actionCount} de ${s.count}`;
    feedbackEl.className = 'text-2xl font-bold py-1 text-green-600';
    feedbackEl.classList.remove('hidden');

    if (actionCount >= s.count) {
      locked = true;
      const dot = document.getElementById(`dot-${currentStep}`);
      if (dot) dot.className = 'w-8 h-8 rounded-full bg-green-400 border-2 border-green-500 transition-all';
      notify('running', { step: currentStep + 1 });
      currentStep++;
      setTimeout(() => {
        locked = false;
        if (currentStep >= steps.length) {
          stepBox.classList.add('hidden');
          progressDots.classList.add('hidden');
          successBanner.classList.remove('hidden');
          lucide.createIcons();
          notify('success', { score: 100 });
          notify('completed', { score: 100 });
        } else {
          showStep();
        }
      }, 700);
    }
  }
});
