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

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

const DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
const STEP_SIZES = [2, 4, 6, 8, 10];
const TOTAL_STEPS = STEP_SIZES.length;

function shuffle(list) {
  const copy = [...list];
  for (let i = copy.length - 1; i > 0; i -= 1) {
    const j = Math.floor(Math.random() * (i + 1));
    [copy[i], copy[j]] = [copy[j], copy[i]];
  }
  return copy;
}

function init() {
  const queryEls = () => ({
    instruction: document.getElementById('instruction'),
    hint: document.getElementById('hint'),
    arena: document.getElementById('arena'),
    successBanner: document.getElementById('successBanner'),
    successMsg: document.getElementById('successMsg'),
  });

  let { instruction, hint, arena, successBanner, successMsg } = queryEls();

  const required = { instruction, hint, arena, successBanner, successMsg };
  const missing = Object.entries(required)
    .filter(([, value]) => !value)
    .map(([name]) => name);

  if (missing.length > 0) {
    console.warn(`[teclado-numeros] Layout incompleto. Aplicando fallback para: ${missing.join(', ')}`);
    document.body.innerHTML = `
      <div class="min-h-screen w-full bg-gradient-to-br from-sky-50 via-white to-indigo-50 p-4 flex items-center justify-center">
        <div class="w-full max-w-5xl bg-white rounded-xl shadow-xl border border-slate-200 p-5 flex flex-col gap-4">
          <div>
            <h2 id="instruction" class="text-2xl font-bold text-slate-800">Números do Teclado</h2>
            <p id="hint" class="text-slate-600"></p>
          </div>
          <div id="arena"></div>
          <div id="successBanner" class="hidden rounded-xl border-2 border-emerald-300 bg-emerald-50 p-6 text-center">
            <h2 class="text-2xl font-bold text-emerald-700">Muito bem!</h2>
            <p id="successMsg" class="text-slate-700"></p>
          </div>
        </div>
      </div>
    `;

    ({ instruction, hint, arena, successBanner, successMsg } = queryEls());
  }

  notify('started');

  let step = 1;
  let sequence = [];
  let index = 0;
  let done = false;

  function generateSequence(size) {
    if (size <= DIGITS.length) {
      return shuffle(DIGITS).slice(0, size);
    }

    const base = shuffle(DIGITS);
    const extra = DIGITS[Math.floor(Math.random() * DIGITS.length)];
    return [...base, extra];
  }

  function markSequence(indexToMark, state) {
    const chip = document.getElementById(`seq-chip-${indexToMark}`);
    if (!chip) return;

    if (state === 'done') {
      chip.className = 'h-11 w-11 rounded-lg border-2 border-emerald-300 bg-emerald-100 text-emerald-700 font-black text-xl flex items-center justify-center transition-all';
      return;
    }

    if (state === 'error') {
      chip.className = 'h-11 w-11 rounded-lg border-2 border-rose-300 bg-rose-100 text-rose-700 font-black text-xl flex items-center justify-center transition-all';
      window.setTimeout(() => {
        if (index === indexToMark) {
          chip.className = 'h-11 w-11 rounded-lg border-2 border-brand-300 bg-brand-100 text-brand-700 font-black text-xl flex items-center justify-center transition-all';
        }
      }, 220);
      return;
    }

    chip.className = 'h-11 w-11 rounded-lg border-2 border-brand-300 bg-brand-100 text-brand-700 font-black text-xl flex items-center justify-center transition-all';
  }

  function setFeedback(ok, typed, expected) {
    const status = document.getElementById('statusFeedback');
    if (!status) return;

    if (ok) {
      status.className = 'mt-4 rounded-xl border border-emerald-300 bg-emerald-50 px-4 py-3 text-emerald-700 font-semibold';
      status.textContent = `Correto: ${typed}`;
      return;
    }

    status.className = 'mt-4 rounded-xl border border-rose-300 bg-rose-50 px-4 py-3 text-rose-700 font-semibold';
    status.textContent = `Ops: você digitou ${typed}. Próximo esperado: ${expected}`;
  }

  function renderSequenceChips() {
    const container = document.getElementById('sequenceChips');
    if (!container) return;

    container.innerHTML = '';
    sequence.forEach((digit, i) => {
      const chip = document.createElement('div');
      chip.id = `seq-chip-${i}`;
      chip.className = 'h-11 w-11 rounded-lg border-2 border-slate-300 bg-white text-slate-700 font-black text-xl flex items-center justify-center transition-all';
      chip.textContent = digit;
      container.appendChild(chip);
    });

    markSequence(0, 'current');
  }

  function renderStep() {
    sequence = generateSequence(STEP_SIZES[step - 1]);
    index = 0;
    hint.textContent = `Digite ${sequence.length} número(s) na ordem mostrada.`;

    arena.innerHTML = `
      <div class="mx-auto w-full max-w-5xl rounded-2xl bg-brand-50 border-2 border-brand-200 p-6 text-center">
        <p class="text-base text-slate-700 font-semibold">Sequência da vez</p>
        <div class="mt-3 overflow-x-auto pb-1">
          <div id="sequenceChips" class="mx-auto flex w-fit min-w-full flex-nowrap items-center justify-center gap-2"></div>
        </div>
        <p class="mt-4 text-sm text-slate-500">Acertos na rodada: <span id="seqState">0</span>/${sequence.length}</p>
        <p id="statusFeedback" class="mt-4 rounded-xl border border-slate-200 bg-white px-4 py-3 text-slate-600 font-medium">Digite o primeiro número destacado.</p>
      </div>
    `;

    renderSequenceChips();
  }

  function flashKey(digit, ok) {
    const el = document.getElementById(`kbd-${digit}`);
    if (!el) return;
    el.className = ok
      ? 'w-12 h-12 rounded-lg border-2 border-emerald-300 bg-emerald-100 flex items-center justify-center font-bold text-emerald-700'
      : 'w-12 h-12 rounded-lg border-2 border-rose-300 bg-rose-100 flex items-center justify-center font-bold text-rose-700';
    setTimeout(() => {
      el.className = 'w-12 h-12 rounded-lg border-2 border-slate-300 bg-white flex items-center justify-center font-bold text-slate-700';
    }, 180);
  }

  function handleDigit(digit) {
    if (done) return;
    const expected = sequence[index];
    const ok = digit === expected;
    flashKey(digit, ok);
    if (!ok) {
      markSequence(index, 'error');
      setFeedback(false, digit, expected);
      return;
    }

    markSequence(index, 'done');
    setFeedback(true, digit, expected);
    index += 1;
    const seqState = document.getElementById('seqState');
    if (seqState) seqState.textContent = String(index);

    if (index < sequence.length) {
      markSequence(index, 'current');
    }

    if (index >= sequence.length) {
      notify('running', { step });
      if (step >= TOTAL_STEPS) {
        done = true;
        arena.classList.add('hidden');
        successBanner.classList.remove('hidden');
        successMsg.textContent = 'Você agora sabe onde estão os números no teclado!';
        lucide.createIcons();
        notify('success', { score: 100 });
        notify('completed', { score: 100 });
        return;
      }

      step += 1;
      renderStep();
    }
  }

  document.addEventListener('keydown', (event) => {
    if (!/^Digit[0-9]$/.test(event.code)) return;
    handleDigit(event.code.replace('Digit', ''));
  });

  renderStep();
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', init, { once: true });
} else {
  init();
}
