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 messageArea = document.getElementById('messageArea');
const confirmBtn = document.getElementById('confirmBtn');
const successBanner = document.getElementById('successBanner');
const messagePreview = document.getElementById('messagePreview');
const reqWords = document.getElementById('req-words');
const reqUpper = document.getElementById('req-upper');
const reqPeriod = document.getElementById('req-period');

messageArea.focus();

function setReq(el, ok) {
  el.className = ok
    ? 'px-4 py-2 rounded-full border-2 border-green-400 text-sm font-bold text-green-700 bg-green-50 transition-all'
    : 'px-4 py-2 rounded-full border-2 border-gray-300 text-sm font-bold text-gray-600 transition-all';
}

messageArea.addEventListener('input', () => {
  const v = messageArea.value.trim();
  const words = v.split(/\s+/).filter(w => w.length > 0);
  const hasWords = words.length >= 3;
  const hasUpper = v.length > 0 && v[0] === v[0].toUpperCase() && /[A-Za-zÀ-ú]/.test(v[0]);
  const hasPeriod = v.endsWith('.');

  setReq(reqWords, hasWords);
  setReq(reqUpper, hasUpper);
  setReq(reqPeriod, hasPeriod);

  if (hasWords && hasUpper && hasPeriod) {
    confirmBtn.classList.remove('hidden');
    notify('running', { step: 1 });
  } else {
    confirmBtn.classList.add('hidden');
  }
});

confirmBtn.addEventListener('click', () => {
  const v = messageArea.value.trim();
  messagePreview.textContent = `"${v}"`;
  messageArea.parentElement.classList.add('hidden');
  document.getElementById('reqChecklist').classList.add('hidden');
  confirmBtn.classList.add('hidden');
  successBanner.classList.remove('hidden');
  lucide.createIcons();
  notify('success', { score: 100 });
  notify('completed', { score: 100 });
});
