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

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

const LEVELS = [
  [
    '#######',
    '#S...E#',
    '#.###.#',
    '#.....#',
    '#######',
  ],
  [
    '########',
    '#S....k#',
    '#.##D###',
    '#..#..E#',
    '########',
  ],
  [
    '#########',
    '#S......#',
    '#.###D###',
    '#...#...#',
    '#.#.###.#',
    '#..k#..E#',
    '#########',
  ],
  [
    '##########',
    '#S..#....#',
    '#.#.#.##D#',
    '#.#...#..#',
    '#.#####.##',
    '#.....#..#',
    '#.###k#E.#',
    '##########',
  ],
  [
    '###########',
    '#S...#...E#',
    '#.#.#.#.###',
    '#.#...#...#',
    '#.#####.#.#',
    '#.....#.#.#',
    '###.#.###.#',
    '#k..#.D...#',
    '###########',
  ],
];

let levelIndex = 0;
let grid = [];
let pr = 0;
let pc = 0;
let hasKey = false;
let openedDoors = 0;
let levelHasDoor = false;
let done = false;

notify('started');

const mazeEl = document.getElementById('maze');
const feedbackEl = document.getElementById('feedback');
const successBanner = document.getElementById('successBanner');
const mazeInfo = document.getElementById('mazeInfo');

function loadLevel(index) {
  grid = LEVELS[index].map((row) => row.split(''));
  levelHasDoor = false;
  for (let r = 0; r < grid.length; r += 1) {
    for (let c = 0; c < grid[r].length; c += 1) {
      if (grid[r][c] === 'S') {
        pr = r;
        pc = c;
      }
      if (grid[r][c] === 'D') {
        levelHasDoor = true;
      }
    }
  }
  hasKey = false;
  openedDoors = 0;
  feedbackEl.classList.add('hidden');
  mazeInfo.textContent = 'Use as setas para chegar à saída';
}

function buildMaze() {
  mazeEl.innerHTML = '';
  grid.forEach((row, r) => {
    const rowEl = document.createElement('div');
    rowEl.style.display = 'flex';
    row.forEach((cell, c) => {
      const el = document.createElement('div');
      el.className = 'cell';
      if (r === pr && c === pc) {
        el.innerHTML = '<div style="width:36px;height:36px;border-radius:50%;background:#14b8a6;display:flex;align-items:center;justify-content:center;color:white;font-weight:900;font-size:1rem;">P</div>';
        el.style.background = '#ecfdf5';
      } else if (cell === '#') {
        el.style.background = '#374151';
      } else if (cell === 'E') {
        el.innerHTML = '<div style="width:36px;height:36px;border-radius:8px;background:#22c55e;display:flex;align-items:center;justify-content:center;color:white;font-weight:900;font-size:1rem;">S</div>';
        el.style.background = '#fef9c3';
      } else if (cell === 'k') {
        el.innerHTML = '<div style="width:32px;height:32px;border-radius:8px;background:#fef9c3;border:1px solid #fcd34d;display:flex;align-items:center;justify-content:center;"><i data-lucide="key-round" style="width:18px;height:18px;color:#a16207"></i></div>';
        el.style.background = '#fffbeb';
      } else if (cell === 'D') {
        el.innerHTML = '<div style="width:32px;height:32px;border-radius:8px;background:#ffedd5;border:1px solid #fdba74;display:flex;align-items:center;justify-content:center;"><i data-lucide="lock" style="width:18px;height:18px;color:#b45309"></i></div>';
        el.style.background = '#fffbeb';
      } else {
        el.style.background = '#f9fafb';
      }
      rowEl.appendChild(el);
    });
    mazeEl.appendChild(rowEl);
  });
  lucide.createIcons();
}
loadLevel(levelIndex);
buildMaze();

document.addEventListener('keydown', (e) => {
  if (done) return;
  const moves = { ArrowUp: [-1,0], ArrowDown: [1,0], ArrowLeft: [0,-1], ArrowRight: [0,1] };
  if (!moves[e.key]) return;
  e.preventDefault();
  const [dr, dc] = moves[e.key];
  const nr = pr + dr, nc = pc + dc;
  if (nr < 0 || nr >= grid.length || nc < 0 || nc >= grid[0].length) return;
  const cell = grid[nr][nc];
  if (cell === '#') {
    feedbackEl.textContent = 'Parede! Escolha outra direção.';
    feedbackEl.className = 'text-xl font-bold py-1 text-center text-orange-500';
    feedbackEl.classList.remove('hidden');
    return;
  }
  if (cell === 'D' && !hasKey) {
    feedbackEl.textContent = 'Porta trancada! Encontre a chave.';
    feedbackEl.className = 'text-xl font-bold py-1 text-center text-amber-600';
    feedbackEl.classList.remove('hidden');
    return;
  }

  feedbackEl.classList.add('hidden');
  if (cell === 'k') {
    hasKey = true;
    mazeInfo.textContent = 'Chave coletada! Agora abra a porta.';
    grid[nr][nc] = '.';
  }
  if (cell === 'D' && hasKey) {
    openedDoors += 1;
    grid[nr][nc] = '.';
    mazeInfo.textContent = 'Porta desbloqueada! Siga até a saída.';
  }

  if (cell === 'E' && levelHasDoor && openedDoors === 0) {
    feedbackEl.textContent = 'A saída está bloqueada. Abra a porta primeiro.';
    feedbackEl.className = 'text-xl font-bold py-1 text-center text-amber-600';
    feedbackEl.classList.remove('hidden');
    return;
  }

  pr = nr; pc = nc;
  buildMaze();
  notify('running', { step: levelIndex + 1 });

  if (cell === 'E') {
    if (levelIndex === LEVELS.length - 1) {
      done = true;
      mazeEl.classList.add('hidden');
      successBanner.classList.remove('hidden');
      lucide.createIcons();
      notify('success', { score: 100 });
      notify('completed', { score: 100 });
      return;
    }

    levelIndex += 1;
    feedbackEl.textContent = `Fase ${levelIndex} concluída!`; 
    feedbackEl.className = 'text-xl font-bold py-1 text-center text-green-600';
    feedbackEl.classList.remove('hidden');
    notify('running', { step: levelIndex + 1 });
    setTimeout(() => {
      loadLevel(levelIndex);
      buildMaze();
    }, 700);
  }
});
