/** Entitlement gate for internal extension pages such as Kanban and Flow Builder. */
(() => {
  'use strict';
  function appendWhenDocumentReady(node) {
    const target = document.head || document.documentElement;
    if (target) {
      target.appendChild(node);
      return;
    }
    document.addEventListener('DOMContentLoaded', () => {
      const readyTarget = document.head || document.documentElement;
      if (readyTarget && !node.isConnected) readyTarget.appendChild(node);
    }, { once: true });
  }
  const bundle = document.documentElement.dataset.flowhatsappBundle;
  if (!/^[a-zA-Z0-9._-]+\.bundle\.js$/.test(bundle || '')) return;

  chrome.runtime.sendMessage({ type: 'FLOWHATSAPP_LICENSE_GET_STATE' }, response => {
    const state = response?.result;
    if (!chrome.runtime.lastError && !response?.transportError && state?.valid === true) {
      const script = document.createElement('script');
      script.src = chrome.runtime.getURL(bundle);
      script.defer = true;
      appendWhenDocumentReady(script);
      return;
    }
    const root = document.getElementById('root') || document.body;
    root.textContent = '';
    
    // Inject Montserrat font via local @font-face (no external 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}`;
      appendWhenDocumentReady(style);
    }
    
    const message = document.createElement('div');
    message.textContent = 'Licença ou período de teste válido necessário.';
    message.style.cssText = 'min-height:100vh;display:grid;place-content:center;background:#0f172a;color:#f1f5f9;font:600 16px Montserrat,system-ui,sans-serif;text-align:center;padding:24px;box-sizing:border-box';
    root.appendChild(message);
  });
})();
