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

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

// Map: symbol → key hint
const sequence = [
  { symbol: '!', hint: 'Shift + 1', key: '!' },
  { symbol: '@', hint: 'Shift + 2', key: '@' },
  { symbol: '#', hint: 'Shift + 3', key: '#' },
  { symbol: '$', hint: 'Shift + 4', key: '$' },
  { symbol: '%', hint: 'Shift + 5', key: '%' },
  { symbol: '&', hint: 'Shift + 7', key: '&' },
  { symbol: '*', hint: 'Shift + 8', key: '*' },
  { symbol: '(', hint: 'Shift + 9', key: '(' },
];

let currentIdx = 0;
let locked = false;
notify('started');

const targetEl = document.getElementById('target');
const targetHintEl = document.getElementById('targetHint');
const feedbackEl = document.getElementById('feedback');
const progressDots = document.getElementById('progressDots');
const successBanner = document.getElementById('successBanner');

sequence.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 showTarget() {
  const s = sequence[currentIdx];
  targetEl.textContent = s.symbol;
  targetHintEl.textContent = `Pressione: ${s.hint}`;
  feedbackEl.classList.add('hidden');
}
showTarget();

document.addEventListener('keydown', (e) => {
  if (locked) return;
  const s = sequence[currentIdx];
  if (e.key === s.key) {
    locked = true;
    feedbackEl.textContent = 'Isso!';
    feedbackEl.className = 'text-2xl font-bold py-1 text-green-600';
    feedbackEl.classList.remove('hidden');
    const dot = document.getElementById(`dot-${currentIdx}`);
    if (dot) dot.className = 'w-8 h-8 rounded-full bg-green-400 border-2 border-green-500 transition-all';
    notify('running', { step: currentIdx + 1 });
    currentIdx++;
    setTimeout(() => {
      locked = false;
      if (currentIdx >= sequence.length) {
        targetEl.parentElement.classList.add('hidden');
        progressDots.classList.add('hidden');
        successBanner.classList.remove('hidden');
        lucide.createIcons();
        notify('success', { score: 100 });
        notify('completed', { score: 100 });
      } else {
        showTarget();
      }
    }, 800);
  } else if (e.key !== 'Shift') {
    feedbackEl.textContent = `Não é esse. Tente: ${s.hint}`;
    feedbackEl.className = 'text-2xl font-bold py-1 text-red-500';
    feedbackEl.classList.remove('hidden');
  }
});
