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

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

const regions = [
  {
    id: 'letras',
    label: 'Letras (A–Z)',
    color: 'bg-blue-400',
    textColor: 'text-white',
    title: 'Região das Letras',
    desc: 'Aqui ficam todas as 26 letras do alfabeto. São as teclas mais usadas para escrever palavras.',
    keys: ['Q','W','E','R','T','Y','U','I','O','P','A','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M'],
  },
  {
    id: 'numeros',
    label: 'Números (0–9)',
    color: 'bg-green-400',
    textColor: 'text-white',
    title: 'Região dos Números',
    desc: 'A linha superior tem os números de 1 a 0. Também há símbolos quando você usa o Shift.',
    keys: ['1','2','3','4','5','6','7','8','9','0'],
  },
  {
    id: 'especiais',
    label: 'Teclas Especiais',
    color: 'bg-orange-400',
    textColor: 'text-white',
    title: 'Teclas Especiais',
    desc: 'Enter, Backspace, Shift, Caps Lock, Esc, Tab — cada uma tem uma função importante!',
    keys: ['Enter','Backspace','Shift','Caps Lock','Esc','Tab'],
  },
  {
    id: 'setas',
    label: 'Setas de Navegação',
    color: 'bg-purple-400',
    textColor: 'text-white',
    title: 'Setas de Navegação',
    desc: 'As quatro setas movem o cursor no texto sem apagar nada. Home e End vão para início/fim da linha.',
    keys: ['←','↑','↓','→','Home','End'],
  },
];

const visitedRegions = new Set();
notify('started');

const keyboard = document.getElementById('keyboard');
const infoBox = document.getElementById('infoBox');
const infoTitle = document.getElementById('infoTitle');
const infoDesc = document.getElementById('infoDesc');
const progressArea = document.getElementById('progressArea');
const instruction = document.getElementById('instruction');
const hint = document.getElementById('hint');
const successBanner = document.getElementById('successBanner');
let isCompleted = false;

// Build visual keyboard rows
const rows = [
  ['Esc','1','2','3','4','5','6','7','8','9','0','Backspace'],
  ['Tab','Q','W','E','R','T','Y','U','I','O','P'],
  ['Caps Lock','A','S','D','F','G','H','J','K','L','Enter'],
  ['Shift','Z','X','C','V','B','N','M','Shift'],
  ['←','↑','↓','→','Home','End'],
];

rows.forEach(row => {
  const rowEl = document.createElement('div');
  rowEl.className = 'flex gap-1 justify-center';
  row.forEach(key => {
    const region = regions.find(r => r.keys.includes(key));
    const keyEl = document.createElement('div');
    const isWide = ['Backspace','Tab','Caps Lock','Enter','Shift'].includes(key);
    keyEl.className = `key px-2 py-2 rounded-md text-sm font-bold shadow flex items-center justify-center min-w-[2.2rem] ${isWide ? 'px-3 min-w-[4rem]' : ''} ${region ? region.color + ' ' + region.textColor : 'bg-gray-200 text-gray-700'}`;
    keyEl.textContent = key;
    if (region) {
      keyEl.addEventListener('click', () => handleRegionClick(region));
    }
    rowEl.appendChild(keyEl);
  });
  keyboard.appendChild(rowEl);
});

function normalizeKey(event) {
  const key = event.key;

  if (key.length === 1) {
    return key.toUpperCase();
  }

  const aliases = {
    ArrowLeft: '←',
    ArrowUp: '↑',
    ArrowDown: '↓',
    ArrowRight: '→',
    Escape: 'Esc',
    CapsLock: 'Caps Lock',
    ' ': 'Space',
  };

  return aliases[key] ?? key;
}

function findRegionByKey(keyLabel) {
  return regions.find((region) => region.keys.includes(keyLabel));
}

function handleRegionClick(region) {
  if (isCompleted) return;

  // Highlight all keys of this region
  document.querySelectorAll('.key').forEach(k => {
    k.classList.remove('ring-4','ring-yellow-400');
    if (region.keys.includes(k.textContent.trim())) {
      k.classList.add('ring-4','ring-yellow-400');
    }
  });

  infoTitle.textContent = region.title;
  infoDesc.textContent = region.desc;
  infoBox.classList.remove('hidden');

  if (!visitedRegions.has(region.id)) {
    visitedRegions.add(region.id);
    notify('running', { step: visitedRegions.size });
  }

  if (visitedRegions.size >= regions.length) {
    isCompleted = true;
    setTimeout(() => {
      keyboard.classList.add('hidden');
      infoBox.classList.add('hidden');
      successBanner.classList.remove('hidden');
      lucide.createIcons();
      notify('success', { score: 100 });
      notify('completed', { score: 100 });
    }, 1000);
  }
}

document.addEventListener('keydown', (event) => {
  if (isCompleted) return;

  const normalizedKey = normalizeKey(event);
  const region = findRegionByKey(normalizedKey);
  if (!region) return;

  handleRegionClick(region);
});
