/** Loads the popup application only after a server-backed entitlement exists. */
(() => {
  'use strict';

  function send(type) {
    return new Promise((resolve, reject) => {
      chrome.runtime.sendMessage({ type }, response => {
        if (chrome.runtime.lastError) reject(new Error(chrome.runtime.lastError.message));
        else if (response?.transportError) reject(new Error(response.transportError));
        else resolve(response?.result || null);
      });
    });
  }

  function getMachineCode() {
    return new Promise(resolve => {
      chrome.runtime.sendMessage({ action: 'getMachineCode' }, response => {
        if (chrome.runtime.lastError) return resolve('');
        resolve(String(response?.installationCode || response?.machineId || '').trim());
      });
    });
  }

  async function loadApplication() {
    // The legacy popup reads this localStorage key synchronously during its
    // first render. Prime it with the canonical device id from the current
    // licensing service so an obsolete FH-INST-* value is never displayed.
    const machineCode = await getMachineCode();
    if (machineCode) localStorage.setItem('flowhats_inst_code', machineCode);
    else localStorage.removeItem('flowhats_inst_code');
    const script = document.createElement('script');
    script.src = chrome.runtime.getURL('popup.bundle.js');
    script.defer = true;
    script.addEventListener('load', () => {
      const normalizeLicenseInput = () => {
        const field = document.querySelector('textarea.license-input');
        if (!field || field.dataset.wfNormalized === 'true') return;
        field.dataset.wfNormalized = 'true';
        field.rows = 1;
        field.wrap = 'off';
        field.setAttribute('aria-label', 'Chave de licença');
        field.addEventListener('keydown', event => {
          if (event.key === 'Enter') event.preventDefault();
        });
      };
      normalizeLicenseInput();
      new MutationObserver(normalizeLicenseInput).observe(document.getElementById('root'), {
        childList: true,
        subtree: true
      });
    }, { once: true });
    document.head.appendChild(script);
  }

  function showLocked(message) {
    const root = document.getElementById('root');
    if (!root) return;
    root.innerHTML = '';
    
    // Use the packaged Montserrat font; no remote font/CSP dependency.
    if (!document.getElementById('wf-font-montserrat')) {
      const style = document.createElement('style');
      style.id = 'wf-font-montserrat';
      style.textContent = `@font-face{font-family:Montserrat;src:url('${chrome.runtime.getURL('fonts/Montserrat-Variable.ttf')}') format('truetype');font-weight:300 800;font-display:swap}`;
      (document.head || document.documentElement).appendChild(style);
    }
    
    const panel = document.createElement('main');
    panel.style.cssText = 'width:360px;min-height:260px;padding:28px;box-sizing:border-box;background:#0f172a;color:#f1f5f9;font-family:Montserrat,system-ui,sans-serif;text-align:center;display:grid;place-content:center;gap:14px';
    const icon = document.createElement('img');
    icon.src = chrome.runtime.getURL('icons/flowhatsapp-mark.svg');
    icon.alt = 'FLOWhatsapp';
    icon.width = 58; icon.height = 58; icon.style.cssText = 'display:block;margin:0 auto;border-radius:14px';
    const title = document.createElement('strong');
    title.textContent = 'Ativação necessária'; title.style.cssText = 'font-size:18px';
    const text = document.createElement('p');
    text.textContent = message || 'Abra o WhatsApp Web para iniciar seu teste de 7 dias ou ativar uma licença.';
    text.style.cssText = 'margin:0;color:#e2e8f0;font-size:13px;line-height:1.55';
    const button = document.createElement('button');
    button.type = 'button'; button.textContent = 'Abrir WhatsApp Web';
    button.style.cssText = 'border:0;border-radius:10px;padding:11px 16px;background:#7C3AED;color:white;font-weight:700;cursor:pointer;box-shadow:0 8px 22px #7C3AED55';
    button.addEventListener('click', () => chrome.tabs.create({ url: 'https://web.whatsapp.com/' }));
    panel.append(icon, title, text, button); root.appendChild(panel);
  }

  document.addEventListener('DOMContentLoaded', async () => {
    try {
      const state = await send('FLOWHATSAPP_LICENSE_GET_STATE');
      if (state?.valid === true) loadApplication();
      else showLocked(state?.message);
    } catch (_) {
      showLocked('Não foi possível validar a licença. Verifique sua conexão e tente novamente.');
    }
  }, { once: true });
})();
