/**
 * FLOWhatsapp v2.2 — License UI Overlay
 * Injeta a interface de ativação de licença no WhatsApp Web
 */
(async () => {
  'use strict';

  // Content scripts registered at document_start must tolerate a document that
  // has not attached <html>/<head> yet.
  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 });
  }

  function whenBodyReady() {
    if (document.body) return Promise.resolve(document.body);
    return new Promise(resolve => document.addEventListener('DOMContentLoaded', () => resolve(document.body), { once: true }));
  }

  const escapeHtml = (value) => String(value ?? '').replace(/[&<>'"]/g, char => ({
    '&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#39;', '"': '&quot;'
  })[char]);
  const safeColor = (value) => /^#[0-9a-f]{6}$/i.test(String(value || '')) ? String(value) : '#7C3AED';
  const packagedMarkUrl = chrome.runtime.getURL('icons/flowhatsapp-mark.svg');
  const safeHttpsUrl = (value) => {
    try { const url = new URL(String(value || '')); return url.protocol === 'https:' ? url.href : ''; }
    catch (_) { return ''; }
  };
  const safePortalUrl = (value) => {
    try {
      const url = new URL(String(value || ''));
      const local = ['localhost', '127.0.0.1', '::1'].includes(url.hostname);
      return url.protocol === 'https:' || (local && url.protocol === 'http:') ? url.href : '';
    } catch (_) { return ''; }
  };
  const safeBrandUrl = (value) => {
    try {
      const url = new URL(String(value || ''));
      const local = ['localhost', '127.0.0.1', '::1'].includes(url.hostname);
      const packaged = url.protocol === 'chrome-extension:' && url.hostname === chrome.runtime.id;
      return url.protocol === 'https:' || (local && url.protocol === 'http:') || packaged ? url.href : '';
    } catch (_) { return ''; }
  };
  const compareVersions = (left, right) => {
    const normalize = value => String(value || '').split(/[+-]/, 1)[0].split('.').map(part => Number.parseInt(part, 10) || 0);
    const a = normalize(left);
    const b = normalize(right);
    for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
      if ((a[index] || 0) !== (b[index] || 0)) return (a[index] || 0) > (b[index] || 0) ? 1 : -1;
    }
    return 0;
  };
  const sanitizeRichText = (value) => {
    const template = document.createElement('template');
    template.innerHTML = String(value || '');
    template.content.querySelectorAll('script,style,iframe,object,embed,link,meta,form').forEach(node => node.remove());
    template.content.querySelectorAll('*').forEach(node => {
      [...node.attributes].forEach(attribute => {
        const name = attribute.name.toLowerCase();
        if (name.startsWith('on') || name === 'style' || name === 'srcdoc') node.removeAttribute(attribute.name);
        if ((name === 'href' || name === 'src') && !safeHttpsUrl(attribute.value)) node.removeAttribute(attribute.name);
      });
    });
    return template.innerHTML;
  };

  // Aguarda o FLOWhatsappLicense estar disponível
  async function waitForLicense(timeout = 8000) {
    const start = Date.now();
    while (!self.FLOWhatsappLicense) {
      if (Date.now() - start > timeout) return null;
      await new Promise(r => setTimeout(r, 100));
    }
    return self.FLOWhatsappLicense;
  }

  const License = await waitForLicense();
  if (!License) return;

  async function showUpdateAvailable(remoteVersion, portalUrl) {
    const installedVersion = chrome.runtime.getManifest().version;
    if (compareVersions(remoteVersion, installedVersion) <= 0 || !portalUrl) return;
    const dismissed = await new Promise(resolve => {
      chrome.storage.local.get(['wf_dismissed_update'], data => resolve(data?.wf_dismissed_update || ''));
    });
    if (dismissed === remoteVersion || document.getElementById('wf-update-available')) return;
    if (!document.body) {
      window.addEventListener('DOMContentLoaded', () => showUpdateAvailable(remoteVersion, portalUrl), { once: true });
      return;
    }

    const notice = document.createElement('aside');
    notice.id = 'wf-update-available';
    notice.setAttribute('role', 'status');
    const brandColor = safeColor(self.FLOWHATSAPP_LICENSE_CONFIG?.brandColor);
    notice.style.cssText = `position:fixed;right:18px;top:72px;z-index:999990;width:min(360px,calc(100vw - 36px));padding:16px 46px 16px 16px;border:1px solid ${brandColor}66;border-radius:16px;background:#0f172af2;color:#f8fafc;box-shadow:0 18px 55px #0008;font-family:Montserrat,system-ui,sans-serif;backdrop-filter:blur(14px);box-sizing:border-box`;
    notice.innerHTML = `
      <button type="button" aria-label="Fechar aviso" data-close style="position:absolute;right:10px;top:9px;width:30px;height:30px;border:0;border-radius:8px;background:transparent;color:#94a3b8;font-size:20px;cursor:pointer">×</button>
      <div style="font-size:11px;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:#c4b5fd">Atualização disponível</div>
      <div style="margin-top:6px;font-size:14px;line-height:1.5;color:#cbd5e1">Versão <strong style="color:#fff">${escapeHtml(remoteVersion)}</strong> pronta para sua extensão.</div>
      <button type="button" data-update style="margin-top:12px;width:100%;padding:11px 14px;border:0;border-radius:10px;background:${brandColor};color:#fff;font:700 13px Montserrat,system-ui,sans-serif;cursor:pointer">Abrir central de atualização</button>`;
    notice.querySelector('[data-update]').addEventListener('click', () => window.open(portalUrl, '_blank', 'noopener,noreferrer'));
    notice.querySelector('[data-close]').addEventListener('click', () => {
      chrome.storage.local.set({ wf_dismissed_update: remoteVersion });
      notice.remove();
    });
    document.body.appendChild(notice);
  }

  async function syncPublicBranding() {
    try {
      const remote = await License.getPublicConfig();
      if (!remote?.success) return false;
      const config = self.FLOWHATSAPP_LICENSE_CONFIG || (self.FLOWHATSAPP_LICENSE_CONFIG = {});
      const remoteName = String(remote.appName || '').trim();
      if (remoteName.length >= 2 && remoteName.length <= 60) config.appName = remoteName;
      config.brandColor = safeColor(remote.brandColor);
      config.brandLogoUrl = safeBrandUrl(remote.brandLogoUrl) || packagedMarkUrl;
      config.supportPhone = String(remote.supportPhone || '').replace(/\D/g, '').slice(0, 20);
      config.tutorialUrl = safeHttpsUrl(remote.tutorialUrl);
      config.contactUrl = safeHttpsUrl(remote.contactUrl);
      config.siteUrl = safeHttpsUrl(remote.siteUrl);
      config.extensionVersion = String(remote.extensionVersion || '').trim();
      config.portalUrl = safePortalUrl(remote.portalUrl);
      config.checkoutUrl = safePortalUrl(remote.checkoutUrl);
      config.tenantSlug = String(remote.tenantSlug || '').trim();
      refreshRuntimeBranding();
      showUpdateAvailable(config.extensionVersion, config.portalUrl).catch(() => {});
      return true;
    } catch (_) {
      return false;
    }
  }

  // Every installed extension refreshes its runtime identity from the backend.
  // Static package values remain only as an offline fallback.
  const initialBrandingSync = syncPublicBranding();
  setInterval(() => syncPublicBranding(), 15 * 60 * 1000);

  async function checkAndShowAnnouncements() {
    try {
      const state = await License.getState();
      if (!state || !Array.isArray(state.announcements) || state.announcements.length === 0) return;

      chrome.storage.local.get(['wf_announcement_views', 'dismissed_announcements'], (store) => {
        const views = store.wf_announcement_views || {};
        const dismissed = store.dismissed_announcements || [];
        let updated = false;

        for (const ann of state.announcements) {
          const id = ann.id || '';
          if (!id) continue;
          if (dismissed.includes(id)) continue;

          const maxViews = Number(ann.maxViews || 5);
          const seenCount = Number(views[id] || 0);

          if (seenCount < maxViews) {
            views[id] = seenCount + 1;
            updated = true;

            // Render announcement modal
            self.FLOWhatsappShowAnnouncement(ann.title, ann.message, id, 'once');
            break; // Show one modal at a time
          }
        }

        if (updated) {
          chrome.storage.local.set({ wf_announcement_views: views });
        }
      });
    } catch (_) {}
  }

  // Check announcements on startup and listen to updates
  setTimeout(() => checkAndShowAnnouncements().catch(() => {}), 3000);
  chrome.storage.onChanged.addListener((changes, area) => {
    if (area === 'local' && (changes.flowhatsapp_license_session || changes.dismissed_announcements)) {
      checkAndShowAnnouncements().catch(() => {});
    }
  });

  // Use a packaged font: no Google Fonts outage/CSP can break the extension.
  // documentElement is available at document_start even before head/body exist.
  if (!document.getElementById('wf-font-montserrat')) {
    const style = document.createElement('style');
    style.id = 'wf-font-montserrat';
    const fontUrl = chrome.runtime.getURL('fonts/Montserrat-Variable.ttf');
    style.textContent = `@font-face{font-family:'Montserrat';src:url('${fontUrl}') format('truetype');font-style:normal;font-weight:300 800;font-display:swap}`;
    appendWhenDocumentReady(style);
  }

  // Inject CSS override for toggle switches and license info dialog grid adjustments
  if (!document.getElementById('wf-custom-extension-styles')) {
    const style = document.createElement('style');
    style.id = 'wf-custom-extension-styles';
    style.textContent = `
      .fv-toggle-slider,
      .wa-ai-toggle,
      .wa-settings-toggle,
      .crm-toggle-slider,
      .wa-signature-toggle {
        background-color: #4b5563 !important;
        transition: background-color 0.2s ease !important;
      }
      .fv-toggle input:checked + .fv-toggle-slider,
      .wa-ai-toggle.active,
      .wa-settings-toggle.active,
      .crm-toggle-switch input:checked + .crm-toggle-slider,
      .wa-signature-toggle.active {
        background-color: #10b981 !important;
      }
      .wa-info-grid {
        grid-template-columns: repeat(3, 1fr) !important;
        gap: 12px !important;
      }
      #wf-buy-license-card {
        background: #1e293b !important;
        border: 1.5px solid #334155 !important;
        border-radius: 10px !important;
        padding: 12px !important;
        cursor: pointer !important;
        transition: all 0.2s ease !important;
        display: flex !important;
        flex-direction: column !important;
        justify-content: center !important;
      }

      /* === PROFILE DROPDOWN CONTRAST FIXES === */
      
      /* Dark Theme (WhatsApp dark theme or extension lion-dark class) */
      .theme-dark .wa-profile-dropdown,
      body.theme-dark .wa-profile-dropdown,
      .wa-profile-dropdown.lion-dark,
      [data-theme="dark"] .wa-profile-dropdown {
        background: #111b21 !important;
        border-color: #222e35 !important;
        box-shadow: 0 12px 32px rgba(0, 0, 0, 0.4) !important;
      }
      .theme-dark .wa-profile-dropdown .wa-dropdown-divider,
      body.theme-dark .wa-profile-dropdown .wa-dropdown-divider,
      .wa-profile-dropdown.lion-dark .wa-dropdown-divider,
      [data-theme="dark"] .wa-profile-dropdown .wa-dropdown-divider {
        background: #222e35 !important;
      }
      .theme-dark .wa-profile-dropdown .wa-menu-item,
      body.theme-dark .wa-profile-dropdown .wa-menu-item,
      .wa-profile-dropdown.lion-dark .wa-menu-item,
      [data-theme="dark"] .wa-profile-dropdown .wa-menu-item {
        color: #e9edef !important;
        background: transparent !important;
      }
      .theme-dark .wa-profile-dropdown .wa-menu-item:hover,
      body.theme-dark .wa-profile-dropdown .wa-menu-item:hover,
      .wa-profile-dropdown.lion-dark .wa-menu-item:hover,
      [data-theme="dark"] .wa-profile-dropdown .wa-menu-item:hover {
        background: #202c33 !important;
        color: #ffffff !important;
      }
      .theme-dark .wa-profile-dropdown .wa-menu-item svg,
      body.theme-dark .wa-profile-dropdown .wa-menu-item svg,
      .wa-profile-dropdown.lion-dark .wa-menu-item svg,
      [data-theme="dark"] .wa-profile-dropdown .wa-menu-item svg {
        color: #8696a0 !important;
      }
      .theme-dark .wa-profile-dropdown .wa-menu-item:hover svg,
      body.theme-dark .wa-profile-dropdown .wa-menu-item:hover svg,
      .wa-profile-dropdown.lion-dark .wa-menu-item:hover svg,
      [data-theme="dark"] .wa-profile-dropdown .wa-menu-item:hover svg {
        color: #ffffff !important;
      }
      .theme-dark .wa-profile-dropdown .wa-profile-info,
      body.theme-dark .wa-profile-dropdown .wa-profile-info,
      .wa-profile-dropdown.lion-dark .wa-profile-info,
      [data-theme="dark"] .wa-profile-dropdown .wa-profile-info {
        color: #e9edef !important;
      }
      .theme-dark .wa-profile-dropdown .wa-device-name,
      body.theme-dark .wa-profile-dropdown .wa-device-name,
      .wa-profile-dropdown.lion-dark .wa-device-name,
      [data-theme="dark"] .wa-profile-dropdown .wa-device-name {
        color: #ffffff !important;
      }
      .theme-dark .wa-profile-dropdown .wa-signature-name,
      body.theme-dark .wa-profile-dropdown .wa-signature-name,
      .wa-profile-dropdown.lion-dark .wa-signature-name,
      [data-theme="dark"] .wa-profile-dropdown .wa-signature-name {
        color: #8696a0 !important;
      }
      .theme-dark .wa-profile-dropdown .wa-expiry-date,
      body.theme-dark .wa-profile-dropdown .wa-expiry-date,
      .wa-profile-dropdown.lion-dark .wa-expiry-date,
      [data-theme="dark"] .wa-profile-dropdown .wa-expiry-date {
        color: #8696a0 !important;
      }

      /* Light Theme (when not in any dark mode context) */
      body:not(.theme-dark) .wa-profile-dropdown:not(.lion-dark) {
        background: #ffffff !important;
        border-color: #e9edef !important;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12) !important;
      }
      body:not(.theme-dark) .wa-profile-dropdown:not(.lion-dark) .wa-dropdown-divider {
        background: #e9edef !important;
      }
      body:not(.theme-dark) .wa-profile-dropdown:not(.lion-dark) .wa-menu-item {
        color: #1f2937 !important;
        background: transparent !important;
      }
      body:not(.theme-dark) .wa-profile-dropdown:not(.lion-dark) .wa-menu-item:hover {
        background: #f7f8fa !important;
        color: #1f2937 !important;
      }
      body:not(.theme-dark) .wa-profile-dropdown:not(.lion-dark) .wa-menu-item svg {
        color: #334155 !important;
      }

      /* Readability baseline: secondary copy stays readable instead of using
         low-contrast gray/blue text on dark cards. Inline legacy colors are
         deliberately overridden inside FLOWhatsapp-owned surfaces only. */
      #flowhatsapp-license-overlay [style*="color:#94a3b8"],
      #flowhatsapp-license-overlay [style*="color: #94a3b8"],
      #flowhatsapp-license-overlay [style*="color:#64748b"],
      #flowhatsapp-license-overlay [style*="color: #64748b"],
      .wa-info-grid [style*="color:#64748b"],
      .wa-info-grid [style*="color: #64748b"],
      .wa-info-grid [style*="color:#475569"],
      .wa-info-grid [style*="color: #475569"] {
        color: #e2e8f0 !important;
      }
    `;
    appendWhenDocumentReady(style);
  }

  // ─── Verificar se precisa mostrar tela de ativação ───────────────────────────
  async function shouldShowActivation() {
    const state = await License.getState();
    // O servidor cria o teste de 7 dias; fora dele é obrigatória uma licença.
    if (!state) return false;
    if (state.valid === false) return true; // Licença inválida/expirada
    return false;
  }

  function ensureActivationLauncherStyles() {
    if (document.getElementById('wf-license-launcher-styles')) return;
    const style = document.createElement('style');
    style.id = 'wf-license-launcher-styles';
    style.textContent = `
      #wf-license-launcher {
        position: relative; isolation: isolate; flex: 0 0 auto;
        display: inline-flex; align-items: center; justify-content: center; gap: 7px;
        min-width: 34px; height: 34px; padding: 6px 10px;
        border: 1px solid var(--wf-license-brand, #7c3aed); border-radius: 10px;
        background: #111c31; color: #f8fafc; font: 700 12px 'Montserrat', sans-serif;
        cursor: pointer; white-space: nowrap; box-shadow: 0 3px 12px rgba(0,0,0,.34);
        transition: transform .18s ease, background .18s ease, box-shadow .18s ease;
      }
      #wf-license-launcher::before {
        content: ''; position: absolute; inset: -3px; z-index: -1; border-radius: 12px;
        background: var(--wf-license-brand, #7c3aed); opacity: .26; filter: blur(8px);
        animation: wf-license-neon 2.8s ease-in-out infinite;
      }
      #wf-license-launcher:hover { background: #172554; transform: translateY(-1px); box-shadow: 0 6px 16px rgba(0,0,0,.4); }
      #wf-license-launcher:focus-visible { outline: 3px solid #f8fafc; outline-offset: 2px; }
      #wf-license-launcher img { width: 18px; height: 18px; border-radius: 5px; display: block; }
      @keyframes wf-license-neon { 0%, 100% { opacity: .16; transform: scale(.98); } 50% { opacity: .38; transform: scale(1.02); } }
      @media (max-width: 1100px) { #wf-license-launcher .wf-license-launcher-label { display: none; } #wf-license-launcher { padding: 6px; } }
      @media (prefers-reduced-motion: reduce) { #wf-license-launcher::before { animation: none; opacity: .2; } #wf-license-launcher { transition: none; } }
    `;
    appendWhenDocumentReady(style);
  }

  function findActivationLauncherAnchor() {
    const menuSelectors = [
      '#side header [aria-label="Mais opções"]',
      '#side header [aria-label="More options"]',
      '#side header [aria-label="Más opciones"]',
      '#side header [aria-haspopup="menu"]',
      '#pane-side header [aria-label="Mais opções"]',
      '#pane-side [aria-label*="Menu"]',
      '#pane-side [data-testid*="menu"]',
      '[data-testid="chat-list-header"] button[aria-label*="Menu"]',
      '[data-testid="chat-list-header"] [role="button"][aria-label*="Menu"]',
      '[data-testid="chat-list-header"] [data-testid*="menu"]'
    ];
    for (const selector of menuSelectors) {
      const anchor = document.querySelector(selector);
      if (anchor?.parentElement) return anchor;
    }
    return null;
  }

  let activationLauncherObserver = null;
  let activationLauncherMountTimer = 0;

  function watchActivationLauncher() {
    if (activationLauncherObserver || !document.documentElement) return;
    activationLauncherObserver = new MutationObserver(() => {
      clearTimeout(activationLauncherMountTimer);
      activationLauncherMountTimer = setTimeout(() => {
        const launcher = document.getElementById('wf-license-launcher');
        if (launcher) mountActivationLauncher(launcher);
      }, 180);
    });
    activationLauncherObserver.observe(document.documentElement, { childList: true, subtree: true });
  }

  function refreshRuntimeBranding() {
    const launcher = document.getElementById('wf-license-launcher');
    if (!launcher) return;
    const config = self.FLOWHATSAPP_LICENSE_CONFIG || {};
    const appName = String(config.appName || 'FLOWhatsapp').trim().slice(0, 60) || 'FLOWhatsapp';
    launcher.style.setProperty('--wf-license-brand', safeColor(config.brandColor));
    launcher.setAttribute('aria-label', `Abrir ativação do ${appName}`);
    launcher.title = `Ativar ${appName}`;
  }

  function mountActivationLauncher(launcher) {
    const anchor = findActivationLauncherAnchor();
    if (!anchor?.parentElement) return false;
    const host = anchor.parentElement;
    // The native chat-list header is deliberately used instead of the message
    // composer, so activation can never cover WhatsApp's send button.
    if (launcher.parentElement !== host || launcher.nextSibling !== anchor) {
      host.insertBefore(launcher, anchor);
    }
    return true;
  }

  function ensureActivationLauncher() {
    let launcher = document.getElementById('wf-license-launcher');
    if (launcher) {
      mountActivationLauncher(launcher);
      watchActivationLauncher();
      return;
    }
    const config = self.FLOWHATSAPP_LICENSE_CONFIG || {};
    const brandColor = safeColor(config.brandColor);
    ensureActivationLauncherStyles();
    launcher = document.createElement('button');
    launcher.id = 'wf-license-launcher';
    launcher.type = 'button';
    const appName = String(config.appName || 'FLOWhatsapp').trim().slice(0, 60) || 'FLOWhatsapp';
    launcher.setAttribute('aria-label', `Abrir ativação do ${appName}`);
    launcher.title = `Ativar ${appName}`;
    launcher.style.setProperty('--wf-license-brand', brandColor);
    launcher.innerHTML = `<img src="${packagedMarkUrl}" alt=""><span class="wf-license-launcher-label">Ativar</span>`;
    launcher.addEventListener('click', () => openActivationUI());
    mountActivationLauncher(launcher);
    // WhatsApp rebuilds its header during navigation and account switches.
    // Keep one lightweight observer so the same launcher is restored safely.
    watchActivationLauncher();
  }

  function closeActivationUI() {
    const overlay = document.getElementById('flowhatsapp-license-overlay');
    if (overlay?._wfKeyHandler) document.removeEventListener('keydown', overlay._wfKeyHandler);
    overlay?.remove();
    ensureActivationLauncher();
  }

  // ─── Interface de Ativação ────────────────────────────────────────────────────
  function createActivationUI() {
    const config = self.FLOWHATSAPP_LICENSE_CONFIG || {};
    const appName = escapeHtml(config.appName || "FLOWhatsapp");
    const brandColor = safeColor(config.brandColor);
    const brandLogoUrl = safeBrandUrl(config.brandLogoUrl) || packagedMarkUrl;
    const isDark = window.matchMedia?.('(prefers-color-scheme: dark)').matches;

    const overlay = document.createElement('div');
    overlay.id = 'flowhatsapp-license-overlay';
    overlay.style.cssText = `
      position: fixed; inset: 0; z-index: 999999;
      background: rgba(0,0,0,0.85);
      display: flex; align-items: center; justify-content: center;
      font-family: 'Montserrat', -apple-system, sans-serif;
      backdrop-filter: blur(8px);
      padding: max(12px, env(safe-area-inset-top)) max(12px, env(safe-area-inset-right)) max(12px, env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left));
      overflow: hidden;
      overscroll-behavior: contain;
      box-sizing: border-box;
    `;

    // Render logo HTML
    const logoHtml = `<img id="wf-brand-logo" src="${brandLogoUrl}" style="width:54px;height:54px;object-fit:contain;border-radius:14px;flex:0 0 auto;filter:drop-shadow(0 10px 22px ${brandColor}4d)" />
      <img id="wf-logo-fallback" src="${packagedMarkUrl}" alt="" style="display:none;width:54px;height:54px;border-radius:14px;flex:0 0 auto" />`;

    overlay.innerHTML = `
      <div id="wf-license-dialog" role="dialog" aria-modal="true" aria-labelledby="wf-license-title" style="
        background: #0f172a; border: 1px solid #1e293b;
        border-radius: 20px; padding: 24px; width: 720px; max-width: 100%;
        max-height: calc(100dvh - 24px); overflow: hidden;
        box-shadow: 0 25px 60px rgba(0,0,0,0.6);
        animation: flowhatsapp-fadein 0.4s ease;
        position:relative;
      ">
        <style>
          @keyframes flowhatsapp-fadein { from { opacity:0; transform:translateY(20px); } to { opacity:1; transform:none; } }
          #flowhatsapp-license-overlay * { box-sizing: border-box; }
          #flowhatsapp-license-overlay .wf-license-header {
            display:flex; align-items:center; justify-content:center; gap:14px;
            margin:0 42px 16px; text-align:left;
          }
          #flowhatsapp-license-overlay .wf-license-tabs {
            display:grid; grid-template-columns:1fr 1fr; gap:8px; margin:14px 0;
            padding:5px; border:1px solid #334155; border-radius:12px; background:#0b1220;
          }
          #flowhatsapp-license-overlay .wf-license-tab {
            min-height:40px; padding:9px 14px; border:1px solid transparent; border-radius:8px;
            background:transparent; color:#cbd5e1; font:700 13px inherit; cursor:pointer;
          }
          #flowhatsapp-license-overlay .wf-license-tab[aria-selected="true"] {
            background:${brandColor}; color:#fff; box-shadow:0 8px 20px ${brandColor}33;
          }
          #flowhatsapp-license-overlay .wf-license-tab:focus-visible {
            outline:3px solid #f8fafc; outline-offset:2px;
          }
          #flowhatsapp-license-overlay .wf-license-panel[hidden] { display:none !important; }
          #flowhatsapp-license-overlay .wf-license-panel { min-height:154px; }
          #flowhatsapp-license-overlay .wf-trial-grid {
            display:grid; grid-template-columns:1fr 1fr; gap:12px;
          }
          #flowhatsapp-license-overlay .wf-input {
            width: 100%; padding: 12px 16px; background: #1e293b;
            border: 1.5px solid #334155; border-radius: 10px; color: #f1f5f9;
            font-size: 14px; outline: none; transition: border-color 0.2s;
            font-family: monospace; letter-spacing: 1px;
          }
          #flowhatsapp-license-overlay .wf-input:focus { border-color: ${brandColor}; box-shadow: 0 0 0 3px ${brandColor}33; }
          #flowhatsapp-license-overlay .wf-btn {
            padding: 13px 24px; border-radius: 10px; border: none;
            font-size: 14px; font-weight: 600; cursor: pointer; transition: all 0.2s;
          }
          #flowhatsapp-license-overlay .wf-btn-primary {
            background: ${brandColor}; color: white; width: 100%;
          }
          #flowhatsapp-license-overlay .wf-btn-primary:hover { opacity: 0.9; }
          #flowhatsapp-license-overlay .wf-btn-primary:disabled { background: #334155; cursor: not-allowed; }
          #flowhatsapp-license-overlay .wf-btn-secondary {
            width:100%; margin-top:10px; background:transparent; color:#cbd5e1;
            border:1px solid #334155;
          }
          #flowhatsapp-license-overlay .wf-btn-secondary:hover { border-color:${brandColor}; color:#fff; }
          #flowhatsapp-license-overlay .wf-close {
            position:absolute; right:14px; top:14px; width:34px; height:34px;
            display:grid; place-items:center; border:1px solid #334155; border-radius:9px;
            background:#111c31; color:#cbd5e1; font-size:21px; line-height:1; cursor:pointer;
          }
          #flowhatsapp-license-overlay .wf-close:hover { color:#fff; border-color:${brandColor}; }
          #flowhatsapp-license-overlay .wf-machine-box {
            background: #1e293b; border: 1px solid ${brandColor}33;
            border-radius: 10px; padding: 12px 16px;
            display: flex; align-items: center; justify-content: space-between; gap: 8px;
          }
          #flowhatsapp-license-overlay .wf-machine-id {
            font-family: monospace; font-size: 12px; color: #60a5fa;
            word-break: break-all; flex: 1;
          }
          #flowhatsapp-license-overlay .wf-copy-btn {
            background: ${brandColor}26; border: 1px solid ${brandColor}4d;
            border-radius: 8px; padding: 6px 10px; color: #60a5fa;
            cursor: pointer; font-size: 11px; font-weight: 600; flex-shrink: 0;
            white-space: nowrap; transition: all 0.15s;
          }
          #flowhatsapp-license-overlay .wf-copy-btn:hover { background: ${brandColor}40; }
          #flowhatsapp-license-overlay .wf-copy-btn:focus-visible,
          #flowhatsapp-license-overlay .wf-btn:focus-visible,
          #flowhatsapp-license-overlay .wf-close:focus-visible {
            outline: 3px solid #f8fafc; outline-offset: 2px;
          }
          #flowhatsapp-license-overlay .wf-alert {
            padding: 10px 14px; border-radius: 8px; font-size: 13px;
            margin-top: 12px; display: none;
          }
          #flowhatsapp-license-overlay .wf-alert.error { background: rgba(239,68,68,0.15); border: 1px solid rgba(239,68,68,0.3); color: #fca5a5; }
          #flowhatsapp-license-overlay .wf-alert.success { background: rgba(34,197,94,0.15); border: 1px solid rgba(34,197,94,0.3); color: #86efac; }
          @media (max-width: 620px) {
            #flowhatsapp-license-overlay #wf-license-dialog { border-radius:16px; padding:18px; }
            #flowhatsapp-license-overlay .wf-license-header { justify-content:flex-start; margin:0 38px 12px 0; }
            #flowhatsapp-license-overlay .wf-license-header img { width:46px !important; height:46px !important; }
            #flowhatsapp-license-overlay .wf-trial-grid { grid-template-columns:1fr; gap:8px; }
            #flowhatsapp-license-overlay .wf-license-panel { min-height:0; }
          }
          @media (max-height: 680px) {
            #flowhatsapp-license-overlay #wf-license-dialog { padding:14px 18px; }
            #flowhatsapp-license-overlay .wf-license-header { margin-bottom:8px; }
            #flowhatsapp-license-overlay .wf-license-header img { width:42px !important; height:42px !important; }
            #flowhatsapp-license-overlay .wf-machine-help,
            #flowhatsapp-license-overlay .wf-license-credit { display:none; }
            #flowhatsapp-license-overlay .wf-license-tabs { margin:9px 0; }
          }
        </style>

        <button class="wf-close" id="wf-license-close" type="button" aria-label="Fechar ativação">×</button>

        <!-- Logo + Header -->
        <div class="wf-license-header">
          ${logoHtml}
          <div>
            <h2 id="wf-license-title" style="margin:0; font-size:22px; font-weight:700; color:#f1f5f9;">${appName}</h2>
            <p style="margin:4px 0 0; color:#cbd5e1; font-size:13px;">Ative sua licença ou use seu teste gratuito de 7 dias</p>
          </div>
        </div>

        <!-- Machine ID -->
        <div style="margin-bottom:10px;">
          <label style="display:block; font-size:12px; font-weight:600; color:#94a3b8; text-transform:uppercase; letter-spacing:0.5px; margin-bottom:8px;">
            Código da sua máquina
          </label>
          <div class="wf-machine-box">
            <span class="wf-machine-id" id="wf-machine-id">Carregando...</span>
            <button class="wf-copy-btn" id="wf-copy-btn" type="button">Copiar</button>
          </div>
          <p class="wf-machine-help" style="margin:5px 0 0; font-size:11px; color:#cbd5e1;">
            Informe este código ao solicitar sua licença.
          </p>
        </div>

        <div class="wf-license-tabs" role="tablist" aria-label="Escolha como continuar">
          <button class="wf-license-tab" id="wf-tab-activate" type="button" role="tab" aria-selected="true" aria-controls="wf-panel-activate">Ativar licença</button>
          <button class="wf-license-tab" id="wf-tab-trial" type="button" role="tab" aria-selected="false" aria-controls="wf-panel-trial">Teste grátis de 7 dias</button>
        </div>

        <section class="wf-license-panel" id="wf-panel-activate" role="tabpanel" aria-labelledby="wf-tab-activate">
          <div style="margin-bottom:12px;">
            <label for="wf-license-key" style="display:block; font-size:12px; font-weight:600; color:#cbd5e1; text-transform:uppercase; letter-spacing:0.5px; margin-bottom:7px;">Chave de Licença</label>
            <input type="text" id="wf-license-key" class="wf-input" placeholder="FLOWHATSAPP-XXXX-XXXX-XXXX-XXXX" autocomplete="off" spellcheck="false" />
          </div>
          <button class="wf-btn wf-btn-primary" id="wf-activate-btn" type="button">Ativar Licença</button>
        </section>

        <section class="wf-license-panel" id="wf-panel-trial" role="tabpanel" aria-labelledby="wf-tab-trial" hidden>
          <div class="wf-trial-grid" id="wf-trial-lead-fields">
            <div>
              <label for="wf-trial-name" style="display:block; font-size:11px; font-weight:600; color:#cbd5e1; text-transform:uppercase; letter-spacing:0.5px; margin-bottom:6px;">Seu nome</label>
              <input type="text" id="wf-trial-name" class="wf-input" placeholder="João Silva" autocomplete="given-name" style="font-family:inherit; font-size:14px;" />
            </div>
            <div>
              <label for="wf-trial-contact" style="display:block; font-size:11px; font-weight:600; color:#cbd5e1; text-transform:uppercase; letter-spacing:0.5px; margin-bottom:6px;">Seu WhatsApp / E-mail</label>
              <input type="text" id="wf-trial-contact" class="wf-input" placeholder="(11) 99999-9999 ou email@exemplo.com" autocomplete="email" style="font-family:inherit; font-size:14px;" />
            </div>
          </div>
          <button class="wf-btn wf-btn-secondary" id="wf-trial-btn" type="button" style="margin-top:12px; border-color:${brandColor}88; color:#f8fafc;">Iniciar teste grátis de 7 dias</button>
        </section>

        <div class="wf-alert" id="wf-alert" role="status" aria-live="polite"></div>

        <!-- Check for Updates section -->
        <div style="margin-top:12px; text-align:center; display:flex; flex-direction:column; align-items:center; gap:6px;">
          <div style="display: flex; align-items: center; gap: 6px; font-size: 11px; color: #cbd5e1;">
            <span>Versão da extensão: <strong>v${escapeHtml(config.appVersion || '2.4.5')}</strong></span>
            <button id="wf-btn-check-update" type="button" style="background: transparent; border: 0; padding: 2px 6px; color: ${brandColor}; font-size: 11px; font-weight: bold; cursor: pointer; text-decoration: underline;">Verificar Atualizacoes</button>
          </div>
          <div id="wf-update-status" style="font-size: 11px; display: none; padding: 6px 12px; border-radius: 8px; line-height: 1.4;"></div>
        </div>

        <!-- Discreet Credit Footer -->
        <div class="wf-license-credit" style="margin-top:10px; text-align:center; border-top:1px solid #1e293b; padding-top:9px;">
          <span style="font-size: 10px; color: #94a3b8; letter-spacing: 0.5px;">Ambiente protegido • Licença verificada</span>
        </div>
      </div>
    `;

    overlay.querySelector('#wf-copy-btn')?.addEventListener('click', async event => {
      const value = overlay.querySelector('#wf-machine-id')?.textContent || '';
      await navigator.clipboard.writeText(value);
      event.currentTarget.textContent = 'Copiado ✓';
      setTimeout(() => { event.currentTarget.textContent = 'Copiar'; }, 2000);
    });
    overlay.querySelector('#wf-brand-logo')?.addEventListener('error', event => {
      event.currentTarget.style.display = 'none';
      const fallback = overlay.querySelector('#wf-logo-fallback');
      if (fallback) fallback.style.display = 'block';
    }, { once: true });
    const selectLicenseTab = tabName => {
      const activateSelected = tabName !== 'trial';
      const activateTab = overlay.querySelector('#wf-tab-activate');
      const trialTab = overlay.querySelector('#wf-tab-trial');
      const activatePanel = overlay.querySelector('#wf-panel-activate');
      const trialPanel = overlay.querySelector('#wf-panel-trial');
      activateTab?.setAttribute('aria-selected', String(activateSelected));
      trialTab?.setAttribute('aria-selected', String(!activateSelected));
      if (activatePanel) activatePanel.hidden = !activateSelected;
      if (trialPanel) trialPanel.hidden = activateSelected;
      hideAlert();
      requestAnimationFrame(() => {
        overlay.querySelector(activateSelected ? '#wf-license-key' : '#wf-trial-name')?.focus();
      });
    };
    overlay.querySelector('#wf-tab-activate')?.addEventListener('click', () => selectLicenseTab('activate'));
    overlay.querySelector('#wf-tab-trial')?.addEventListener('click', () => selectLicenseTab('trial'));
    overlay.querySelector('#wf-activate-btn')?.addEventListener('click', () => self.FLOWhatsappActivate());
    overlay.querySelector('#wf-trial-btn')?.addEventListener('click', () => self.FLOWhatsappStartTrial());
    overlay.querySelector('#wf-license-close')?.addEventListener('click', closeActivationUI);
    overlay.querySelector('#wf-btn-check-update')?.addEventListener('click', async event => {
      const btn = event.currentTarget;
      const statusDiv = overlay.querySelector('#wf-update-status');
      
      btn.disabled = true;
      btn.textContent = 'Verificando...';
      if (statusDiv) {
        statusDiv.style.display = 'none';
        statusDiv.style.background = 'transparent';
        statusDiv.style.color = '#fff';
        statusDiv.textContent = '';
      }
      
      try {
        await syncPublicBranding();
        
        const installedVersion = chrome.runtime.getManifest().version;
        const remoteVersion = self.FLOWHATSAPP_LICENSE_CONFIG?.extensionVersion || '2.4.5';
        const portalUrl = self.FLOWHATSAPP_LICENSE_CONFIG?.portalUrl;
        
        if (compareVersions(remoteVersion, installedVersion) > 0) {
          if (statusDiv) {
            statusDiv.style.display = 'block';
            statusDiv.style.background = 'rgba(245,158,11,0.15)';
            statusDiv.style.border = '1px solid rgba(245,158,11,0.3)';
            statusDiv.style.color = '#fcd34d';
            const safeRemoteVersion = escapeHtml(remoteVersion);
            const safeUpdateUrl = escapeHtml(safePortalUrl(portalUrl));
            statusDiv.innerHTML = `Nova versão <strong>v${safeRemoteVersion}</strong> disponível!<br><a href="${safeUpdateUrl}" target="_blank" rel="noopener noreferrer" style="color:#f8fafc;font-weight:bold;text-decoration:underline;">Clique aqui para baixar</a>`;
          }
        } else {
          if (statusDiv) {
            statusDiv.style.display = 'block';
            statusDiv.style.background = 'rgba(34,197,94,0.15)';
            statusDiv.style.border = '1px solid rgba(34,197,94,0.3)';
            statusDiv.style.color = '#86efac';
            statusDiv.textContent = 'Voce ja possui a versao mais recente instalada (v' + installedVersion + ').';
          }
        }
      } catch (e) {
        if (statusDiv) {
          statusDiv.style.display = 'block';
          statusDiv.style.background = 'rgba(239,68,68,0.15)';
          statusDiv.style.border = '1px solid rgba(239,68,68,0.3)';
          statusDiv.style.color = '#fca5a5';
          statusDiv.textContent = 'Erro ao verificar atualizacoes: ' + e.message;
        }
      } finally {
        btn.disabled = false;
        btn.textContent = 'Verificar Atualizacoes';
      }
    });
    overlay.addEventListener('click', event => {
      if (event.target === overlay) closeActivationUI();
    });
    overlay._wfKeyHandler = event => {
      if (event.key === 'Escape') closeActivationUI();
    };
    document.addEventListener('keydown', overlay._wfKeyHandler);
    return overlay;
  }

  async function openActivationUI() {
    document.getElementById('wf-license-launcher')?.remove();
    if (document.getElementById('flowhatsapp-license-overlay')) return;
    const ui = createActivationUI();
    const body = await whenBodyReady();
    if (!document.getElementById('flowhatsapp-license-overlay')) body.appendChild(ui);
    const machineId = await License.getMachineId();
    const el = document.getElementById('wf-machine-id');
    if (el) el.textContent = machineId;
    document.getElementById('wf-license-key')?.addEventListener('keydown', event => {
      if (event.key === 'Enter') self.FLOWhatsappActivate();
    });
  }

  // ─── Ações da UI ─────────────────────────────────────────────────────────────
  self.FLOWhatsappActivate = async function () {
    const keyInput = document.getElementById('wf-license-key');
    const btn      = document.getElementById('wf-activate-btn');
    const alert    = document.getElementById('wf-alert');
    const key      = keyInput?.value?.trim();

    if (!key) {
      showAlert('Digite a chave de licença.', 'error');
      return;
    }

    btn.disabled    = true;
    btn.textContent = 'Validando...';
    hideAlert();

    try {
      const result = await License.activate(key);
      if (result.valid) {
        showAlert('✓ ' + result.message, 'success');
        setTimeout(() => {
          document.getElementById('flowhatsapp-license-overlay')?.remove();
          document.getElementById('wf-license-launcher')?.remove();
        }, 1800);
      } else {
        showAlert(result.message, 'error');
      }
    } catch (err) {
      showAlert('Erro ao validar licença. Verifique sua conexão.', 'error');
    } finally {
      btn.disabled    = false;
      btn.textContent = 'Ativar Licença';
    }
  };

  self.FLOWhatsappStartTrial = async function () {
    const btn = document.getElementById('wf-trial-btn');
    if (!btn) return;

    // Collect lead data (optional but highly recommended)
    const trialName    = (document.getElementById('wf-trial-name')?.value || '').trim().slice(0, 80);
    const trialContact = (document.getElementById('wf-trial-contact')?.value || '').trim().slice(0, 100);

    btn.disabled = true;
    btn.textContent = 'Iniciando seu teste...';
    hideAlert();
    try {
      // Pass lead data to the service worker which forwards to the API
      const result = await (async () => {
        const machineId = await License.getMachineId();
        return new Promise((resolve, reject) => {
          chrome.runtime.sendMessage({
            type: 'FLOWHATSAPP_LICENSE_TRIAL',
            machineId,
            leadName: trialName,
            leadContact: trialContact
          }, response => {
            if (chrome.runtime.lastError) reject(new Error(chrome.runtime.lastError.message));
            else if (!response) reject(new Error('Sem resposta do serviço.'));
            else if (response.transportError) reject(new Error(response.transportError));
            else resolve(response.result);
          });
        });
      })();

      if (result?.valid) {
        self.FLOWHATSAPP_LICENSE_VALID = true;
        // Save lead data locally for display
        if (trialName) {
          try { chrome.storage.local.set({ wf_trial_name: trialName, wf_trial_contact: trialContact }); } catch (_) {}
        }
        showAlert('✓ Seu teste gratuito de 7 dias está ativo!', 'success');
        setTimeout(() => {
          const overlay = document.getElementById('flowhatsapp-license-overlay');
          if (overlay?._wfKeyHandler) document.removeEventListener('keydown', overlay._wfKeyHandler);
          overlay?.remove();
          ensureActivationLauncher();
        }, 1400);
      } else {
        showAlert(result?.message || 'Não foi possível iniciar o teste.', 'error');
      }
    } catch (_) {
      showAlert('Não foi possível conectar ao servidor. Tente novamente.', 'error');
    } finally {
      btn.disabled = false;
      btn.textContent = 'Iniciar teste grátis de 7 dias';
    }
  };

  function showAlert(msg, type) {
    const el = document.getElementById('wf-alert');
    if (!el) return;
    el.textContent   = msg;
    el.className     = `wf-alert ${type}`;
    el.style.display = 'block';
  }

  function hideAlert() {
    const el = document.getElementById('wf-alert');
    if (el) el.style.display = 'none';
  }

  // ─── Painel de Status (pequeno) na extensão ──────────────────────────────────
  async function injectStatusBadge() {
    const state = await License.getState();
    const plan  = state?.plan || 'inactive';
    const plans = {
      inactive:  { label: 'Inativa',      color: '#64748b' },
      trial_7:   { label: 'Teste',        color: '#f59e0b' },
      mensal:    { label: 'Mensal',       color: '#7C3AED' },
      semestral: { label: 'Semestral',    color: '#7c3aed' },
      anual:     { label: 'Anual',        color: '#059669' },
      vitalicio: { label: 'Vitalício ⭐', color: '#d97706' }
    };
    const info = plans[plan] || plans.inactive;

    // Expõe para o contentScript usar
    self.FLOWHATSAPP_LICENSE_PLAN  = plan;
    self.FLOWHATSAPP_LICENSE_LABEL = info.label;
    self.FLOWHATSAPP_LICENSE_COLOR = info.color;
    self.FLOWHATSAPP_LICENSE_VALID = state?.valid === true;
  }

  // ─── Oferta diária durante o teste ─────────────────────────────────────────
  // A mensagem aparece uma vez por dia local em que o cliente efetivamente abre
  // o WhatsApp. Ela pode ser fechada pelo X ou pelo fundo e jamais bloqueia o uso.
  async function maybeShowTrialDailyOffer() {
    if (document.getElementById('wf-trial-daily-offer')) return;
    const state = await License.getState().catch(() => null);
    if (!state?.valid || state.plan !== 'trial_7') return;

    const days = Math.max(1, Math.min(7, Number(state.expiryDays || 0) || 1));
    const dateKey = new Date().toLocaleDateString('en-CA');
    const storageKey = `wf_trial_offer_seen_${dateKey}`;
    const seen = await new Promise(resolve => chrome.storage.local.get([storageKey], data => resolve(Boolean(data?.[storageKey]))));
    if (seen) return;

    const config = self.FLOWHATSAPP_LICENSE_CONFIG || {};
    const brandColor = safeColor(config.brandColor);
    const appName = escapeHtml(config.appName || 'FLOWhatsapp');
    const copy = {
      7: ['Seu teste começou agora', 'Organize seus atendimentos com calma. Quando estiver pronto, mantenha tudo ativo sem perder o ritmo.'],
      6: ['Um dia de produtividade já faz diferença', 'Você ainda tem tempo para explorar. Garanta continuidade antes que o seu fluxo fique parado.'],
      5: ['Cinco dias para acelerar seus resultados', 'Transforme as rotinas que funcionaram hoje em um processo permanente.'],
      4: ['Seu processo já está ganhando forma', 'Não deixe suas automações, organização e histórico ficarem sem continuidade.'],
      3: ['Faltam só três dias', 'Este é o momento ideal para escolher o plano que acompanha o seu volume de atendimento.'],
      2: ['Seu teste está quase no fim', 'Evite interrupções: escolha agora a continuidade do seu atendimento comercial.'],
      1: ['Último dia do seu teste', 'Mantenha suas ferramentas prontas para trabalhar com você amanhã.'],
    }[days] || ['Seu teste está ativo', 'Aproveite todos os recursos e escolha seu plano quando fizer sentido para sua operação.'];

    let checkoutUrl = safePortalUrl(config.checkoutUrl);
    if (!checkoutUrl) {
      try {
        const base = new URL(String(config.appUrl || config.portalUrl || ''));
        checkoutUrl = new URL('checkout.php', base.href.endsWith('/') ? base.href : `${base.href}/`).href;
      } catch (_) { return; }
    }
    try {
      const url = new URL(checkoutUrl);
      url.searchParams.set('ref', String(config.resellerId || 'admin'));
      url.searchParams.set('source', 'extension_trial_daily');
      url.searchParams.set('days_left', String(days));
      checkoutUrl = url.href;
    } catch (_) { return; }

    const overlay = document.createElement('div');
    overlay.id = 'wf-trial-daily-offer';
    overlay.setAttribute('role', 'dialog');
    overlay.setAttribute('aria-modal', 'false');
    overlay.setAttribute('aria-labelledby', 'wf-trial-daily-title');
    overlay.style.cssText = 'position:fixed;inset:0;z-index:999996;display:flex;align-items:center;justify-content:center;padding:max(12px,env(safe-area-inset-top)) max(12px,env(safe-area-inset-right)) max(12px,env(safe-area-inset-bottom)) max(12px,env(safe-area-inset-left));background:rgba(2,6,23,.62);backdrop-filter:blur(5px);font-family:Montserrat,system-ui,sans-serif;box-sizing:border-box;overflow:auto;overscroll-behavior:contain';
    overlay.innerHTML = `
      <section style="position:relative;width:min(470px,100%);max-height:100%;overflow:auto;overscroll-behavior:contain;border:1px solid ${brandColor}66;border-radius:22px;background:linear-gradient(145deg,#111c34,#0b1222);box-shadow:0 28px 85px rgba(0,0,0,.58);color:#f8fafc">
        <div style="height:5px;background:linear-gradient(90deg,${brandColor},#22c55e)"></div>
        <button type="button" data-close aria-label="Fechar" style="position:absolute;right:14px;top:18px;width:34px;height:34px;border:1px solid #475569;background:#17233a;color:#f8fafc;border-radius:10px;font-size:22px;line-height:1;cursor:pointer">×</button>
        <div style="padding:30px 32px 28px">
          <div style="display:inline-flex;align-items:center;gap:8px;padding:7px 10px;border:1px solid ${brandColor}66;border-radius:999px;background:${brandColor}1c;color:#fff;font-size:12px;font-weight:800;letter-spacing:.04em;text-transform:uppercase">Teste gratuito · ${days} dia${days === 1 ? '' : 's'} restante${days === 1 ? '' : 's'}</div>
          <h2 id="wf-trial-daily-title" style="margin:18px 34px 9px 0;font-size:25px;line-height:1.16;letter-spacing:-.02em;color:#fff">${copy[0]}</h2>
          <p style="margin:0;color:#d7e1ef;font-size:14px;line-height:1.6">${copy[1]}</p>
          <div style="display:flex;align-items:center;justify-content:space-between;gap:14px;margin:22px 0 20px;padding:14px;border:1px solid #334155;border-radius:14px;background:#0b1325">
            <div><div style="font-size:11px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:#a5b4fc">${appName}</div><div style="margin-top:3px;font-size:13px;color:#fff">Acesso completo durante o teste</div></div>
            <div style="min-width:62px;text-align:center;font-size:25px;font-weight:900;color:#fff">${days}<div style="font-size:10px;font-weight:700;color:#cbd5e1;text-transform:uppercase">dias</div></div>
          </div>
          <button type="button" data-buy style="width:100%;border:0;border-radius:12px;padding:14px 16px;background:linear-gradient(135deg,${brandColor},#2563eb);color:#fff;font:800 14px Montserrat,system-ui,sans-serif;cursor:pointer;box-shadow:0 12px 28px ${brandColor}45">Escolher meu plano</button>
          <button type="button" data-later style="display:block;margin:14px auto 0;border:0;background:transparent;color:#cbd5e1;font:600 12px Montserrat,system-ui,sans-serif;cursor:pointer;text-decoration:underline">Continuar explorando por enquanto</button>
        </div>
      </section>`;
    const close = () => { chrome.storage.local.set({ [storageKey]: Date.now() }); overlay.remove(); };
    overlay.addEventListener('click', event => { if (event.target === overlay) close(); });
    overlay.querySelector('[data-close]')?.addEventListener('click', close);
    overlay.querySelector('[data-later]')?.addEventListener('click', close);
    overlay.querySelector('[data-buy]')?.addEventListener('click', () => {
      chrome.storage.local.set({ [storageKey]: Date.now() });
      window.open(checkoutUrl, '_blank', 'noopener,noreferrer');
      overlay.remove();
    });
    document.body.appendChild(overlay);
  }

  // ─── Modal específico de Trial Expirado ──────────────────────────────────────
  async function showTrialExpiredModal() {
    if (document.getElementById('wf-trial-expired-overlay')) return;
    const config = self.FLOWHATSAPP_LICENSE_CONFIG || {};
    const brandColor = safeColor(config.brandColor);
    const appName = escapeHtml(config.appName || 'FLOWhatsapp');

    let checkoutUrl = 'https://flowhatsapp.com.br/checkout.php';
    try {
      const base = new URL(String(config.portalUrl || config.siteUrl || ''));
      const url = new URL('checkout.php', base.origin + '/');
      url.searchParams.set('ref', String(config.resellerId || 'admin'));
      checkoutUrl = url.href;
    } catch (_) {}

    // Retrieve saved lead name for personalization
    const savedData = await new Promise(r => chrome.storage.local.get(['wf_trial_name'], r));
    const firstName = (savedData.wf_trial_name || '').split(' ')[0];
    const greeting = firstName ? `${firstName}, seu` : 'Seu';

    const overlay = document.createElement('div');
    overlay.id = 'wf-trial-expired-overlay';
    overlay.style.cssText = `
      position: fixed; inset: 0; z-index: 999999;
      background: rgba(0,0,0,0.88);
      display: flex; align-items: center; justify-content: center;
      font-family: 'Montserrat', -apple-system, sans-serif;
      backdrop-filter: blur(8px);
      padding: max(12px, env(safe-area-inset-top)) max(12px, env(safe-area-inset-right)) max(12px, env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left));
      overflow: auto; overscroll-behavior: contain; box-sizing: border-box;
    `;

    overlay.innerHTML = `
      <div style="
        background: #0f172a; border: 1px solid ${brandColor}44;
        border-radius: 20px; padding: 32px 28px; width: 480px; max-width: 100%; max-height: 100%; overflow: auto;
        box-shadow: 0 25px 60px rgba(0,0,0,0.6), 0 0 0 1px ${brandColor}22;
        animation: wf-texp-in 0.4s ease; text-align: center; color: #f1f5f9;
      ">
        <style>
          @keyframes wf-texp-in { from { opacity:0; transform:scale(0.92) translateY(16px); } to { opacity:1; transform:none; } }
          #wf-trial-expired-overlay * { box-sizing: border-box; }
          .wf-texp-plans { display:flex; gap:12px; margin:20px 0; }
          .wf-texp-plan { flex:1; background:#1e293b; border:1.5px solid #334155; border-radius:12px; padding:14px 10px; cursor:pointer; transition:all 0.2s; }
          .wf-texp-plan:hover, .wf-texp-plan.selected { border-color:${brandColor}; background:${brandColor}18; }
          .wf-texp-plan .price { font-size:18px; font-weight:800; color:#fff; }
          .wf-texp-plan .label { font-size:11px; color:#cbd5e1; margin-top:2px; }
          .wf-texp-btn { display:block; width:100%; padding:14px; border:none; border-radius:12px; background:linear-gradient(135deg,${brandColor},${brandColor}cc); color:#fff; font-size:15px; font-weight:700; cursor:pointer; transition:all 0.2s; margin-top:6px; font-family:inherit; }
          .wf-texp-btn:hover { opacity:0.9; transform:translateY(-1px); box-shadow:0 8px 24px ${brandColor}44; }
           .wf-texp-later { color:#cbd5e1; font-size:12px; margin-top:16px; cursor:pointer; text-decoration:underline; display:block; }
           .wf-texp-later:hover { color:#fff; }
           @media (max-width: 420px) { .wf-texp-plans { gap:8px; } .wf-texp-plan { padding:12px 6px; } }
        </style>

        <div style="font-size:48px; margin-bottom:10px;">⏰</div>
        <h2 style="margin:0 0 8px; font-size:22px; font-weight:800; color:#fff;">${greeting} teste gratuito acabou!</h2>
        <p style="font-size:13px; color:#cbd5e1; line-height:1.6; margin-bottom:4px;">
          Você aproveitou 7 dias do <strong style="color:#fff;">${appName}</strong>.<br>
          Continue organizando suas vendas — escolha seu plano:
        </p>

        <div class="wf-texp-plans">
          <div class="wf-texp-plan" data-plan="mensal" data-url="${escapeHtml(checkoutUrl + '&plan=mensal')}">
            <div class="price">R$49</div>
            <div class="label">Mensal</div>
          </div>
          <div class="wf-texp-plan" data-plan="semestral" data-url="${escapeHtml(checkoutUrl + '&plan=semestral')}">
            <div class="price">R$250</div>
            <div class="label">Semestral ⚡</div>
          </div>
          <div class="wf-texp-plan" data-plan="anual" data-url="${escapeHtml(checkoutUrl + '&plan=anual')}">
            <div class="price">R$450</div>
            <div class="label">Anual 🏆</div>
          </div>
        </div>

        <button class="wf-texp-btn" id="wf-texp-buy-btn">✅ Assinar Agora</button>
        <span class="wf-texp-later" id="wf-texp-key-btn">Já tenho uma chave de licença</span>
      </div>
    `;

    document.body.appendChild(overlay);

    // Plan selection
    let selectedUrl = checkoutUrl + '&plan=mensal';
    overlay.querySelectorAll('.wf-texp-plan').forEach(card => {
      card.addEventListener('click', () => {
        overlay.querySelectorAll('.wf-texp-plan').forEach(c => c.classList.remove('selected'));
        card.classList.add('selected');
        selectedUrl = card.dataset.url || checkoutUrl;
      });
    });
    // Default select mensal
    overlay.querySelector('[data-plan="mensal"]')?.classList.add('selected');

    document.getElementById('wf-texp-buy-btn').addEventListener('click', () => {
      window.open(selectedUrl, '_blank', 'noopener,noreferrer');
      overlay.remove();
    });
    document.getElementById('wf-texp-key-btn').addEventListener('click', () => {
      overlay.remove();
      openActivationUI(); // Show standard activation modal with key field
    });
  }

  // ─── Mostrar a tela de ativação se necessário ─────────────────────────────────
  async function maybeShowActivation() {
    const show = await shouldShowActivation();
    if (!show) return;

    await new Promise(r => setTimeout(r, 3000)); // Aguarda WhatsApp carregar

    // Check if this is a trial-expired situation
    try {
      const state = await License.getState();
      if (state && !state.valid && state.error === 'trial_expired') {
        await showTrialExpiredModal();
        return;
      }
      // Also check if trial_already_used (machine already burned trial)
      if (state && !state.valid && (state.error === 'trial_already_used' || state.error === 'trial_network_limit')) {
        // Show activation-only modal (no trial button)
        await openActivationUI();
        return;
      }
    } catch (_) {}

    await openActivationUI();
  }

  // ─── Floating Support Chat Widget ─────────────────────────────────────────────
  async function injectSupportWidget() {
    if (document.getElementById('wf-support-widget')) return;

    const config = self.FLOWHATSAPP_LICENSE_CONFIG || {};
    const brandColor = safeColor(config.brandColor);
    const appName = escapeHtml(config.appName || "FLOWhatsapp");
    // syncPublicBranding already receives the correct Super Admin/Whitelabel
    // configuration. Never fall back to a fake support number.
    const supportPhone = String(config.supportPhone || '').replace(/\D/g, '');
    const supportUrl = supportPhone
      ? `https://wa.me/${supportPhone}`
      : (safeHttpsUrl(config.contactUrl) || safeHttpsUrl(config.siteUrl));
    if (!supportUrl) return;

    const widget = document.createElement('div');
    widget.id = 'wf-support-widget';
    widget.style.cssText = `
      position: fixed; z-index: 99999;
      display: flex; align-items: center;
      background: rgba(15, 23, 42, 0.85);
      border: 1px solid ${brandColor}4d;
      border-radius: 30px; padding: 5px;
      width: 44px; height: 44px;
      box-shadow: 0 8px 32px rgba(0,0,0,0.4);
      backdrop-filter: blur(10px);
      cursor: pointer; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      color: #f1f5f9; font-family: 'Montserrat', sans-serif;
      font-size: 13px; font-weight: 600;
      user-select: none;
      box-sizing: border-box;
      overflow: hidden;
    `;

    widget.innerHTML = `
      <div style="
        width: 32px; height: 32px; border-radius: 50%;
        background: ${brandColor}; display: flex;
        align-items: center; justify-content: center;
        box-shadow: 0 4px 12px ${brandColor}66;
        flex-shrink: 0;
      ">
        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icon-tabler-headset">
          <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
          <path d="M4 14v-3a8 8 0 1 1 16 0v3" />
          <path d="M18 19c0 1.657 -2.686 3 -6 3" />
          <path d="M4 14a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v3a2 2 0 0 1 -2 2h-1a2 2 0 0 1 -2 -2z" />
          <path d="M15 14a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v3a2 2 0 0 1 -2 2h-1a2 2 0 0 1 -2 -2z" />
        </svg>
      </div>
      <span style="white-space: nowrap; max-width: 0; overflow: hidden; opacity: 0; transition: all 0.3s ease; color: #f1f5f9; margin-left: 0;">
        Suporte ${appName}
      </span>
    `;

    widget.addEventListener('mouseenter', () => {
      if (widget.dataset.mount === 'native') return;
      const textSpan = widget.querySelector('span');
      if (textSpan) {
        textSpan.style.maxWidth = '180px';
        textSpan.style.opacity = '1';
        textSpan.style.marginLeft = '10px';
      }
      widget.style.width = '200px';
      widget.style.paddingRight = '16px';
      widget.style.background = 'rgba(15, 23, 42, 0.95)';
    });

    widget.addEventListener('mouseleave', () => {
      if (widget.dataset.mount === 'native') return;
      const textSpan = widget.querySelector('span');
      if (textSpan) {
        textSpan.style.maxWidth = '0';
        textSpan.style.opacity = '0';
        textSpan.style.marginLeft = '0';
      }
      widget.style.width = '44px';
      widget.style.paddingRight = '5px';
      widget.style.background = 'rgba(15, 23, 42, 0.85)';
    });

    widget.addEventListener('click', () => {
      window.open(supportUrl, '_blank', 'noopener,noreferrer');
    });

    function mountWidget() {
      const targetBtn = document.querySelector('[data-testid="menu-bar-gallery"]') || 
                        document.querySelector('span[data-icon="gallery"]') ||
                        document.querySelector('[data-testid="menu-bar-settings"]') || 
                        document.querySelector('span[data-icon="settings"]') ||
                        document.querySelector('[role="navigation"] button:last-child');

      if (targetBtn) {
        const anchor = targetBtn.closest('button, [role="button"]') || targetBtn;
        const container = anchor.parentElement;
        if (container && container !== document.body && anchor.isConnected) {
          widget.dataset.mount = 'native';
          widget.style.position = 'relative';
          widget.style.left = 'auto';
          widget.style.right = 'auto';
          widget.style.top = 'auto';
          widget.style.bottom = 'auto';
          widget.style.width = '40px';
          widget.style.height = '40px';
          widget.style.padding = '4px';
          widget.style.margin = '4px auto';
          widget.style.flex = '0 0 auto';
          if (widget.parentElement !== container || widget.nextSibling !== anchor) {
            container.insertBefore(widget, anchor);
          }
          return true;
        }
      }

      widget.dataset.mount = 'fallback';
      if (widget.parentElement !== document.body) document.body.appendChild(widget);
      widget.style.position = 'fixed';
      widget.style.left = '12px';
      widget.style.bottom = '150px';
      widget.style.width = '44px';
      widget.style.height = '44px';
      widget.style.padding = '5px';
      widget.style.margin = '0';
      return false;
    }

    mountWidget();
    // WhatsApp rebuilds its navigation during updates/account switches. Move
    // the same button back into the native bar without creating duplicates.
    let mountTimer = 0;
    const observer = new MutationObserver(() => {
      clearTimeout(mountTimer);
      mountTimer = setTimeout(mountWidget, 250);
    });
    observer.observe(document.body, { childList: true, subtree: true });
    window.addEventListener('resize', mountWidget);
  }

  // Atualiza a identidade da instalação pelo backend antes de criar os
  // elementos visuais. Assim uma mudança feita no Super Admin/Whitelabel
  // alcança extensões já instaladas sem depender da tela de atualizações.
  await Promise.race([
    initialBrandingSync,
    new Promise(resolve => setTimeout(resolve, 1200))
  ]);

  // Inicializar
  await injectStatusBadge();
  // The detailed activation card is shown inside a specific settings panel.
  // Keep a clear launcher available to every customer while the trial is valid.
  if (self.FLOWHATSAPP_LICENSE_VALID && self.FLOWHATSAPP_LICENSE_PLAN === 'trial_7') {
    ensureActivationLauncher();
  }
  if (self.FLOWHATSAPP_LICENSE_VALID) {
    setTimeout(() => {
      injectSupportWidget().catch(() => {});
    }, 5000);
    // Give WhatsApp time to paint before showing the non-blocking daily offer.
    setTimeout(() => maybeShowTrialDailyOffer().catch(() => {}), 4200);
  }
  maybeShowActivation().catch(() => {});

  // ─── Enriquecedor inteligente do painel "Informações da licença" ──────────────
  // Injeta cards contextuais baseados no estado atual da licença:
  //  · Trial ativo    → ID da Instalação (para admin identificar) + campo de chave
  //  · Licença paga   → Chave mascarada + ID + renovação
  //  · Trial expirado → Campo de chave proeminente + compra
  const licenseDialogObserver = new MutationObserver(() => {
    const infoGrid = document.querySelector('.wa-info-grid');
    if (!infoGrid) return;
    // If our cards are already injected and up-to-date, skip
    if (document.getElementById('wf-machine-id-card')) return;

    const config = self.FLOWHATSAPP_LICENSE_CONFIG || {};
    const brandColor = safeColor(config.brandColor || '#7C3AED');
    const plan = self.FLOWHATSAPP_LICENSE_PLAN || 'inactive';
    const isValid = self.FLOWHATSAPP_LICENSE_VALID === true;

    // ── Build checkout URL ──────────────────────────────────────────────────────
    let checkoutUrl = 'https://flowhatsapp.com.br/checkout.php';
    try {
      const portalBase = String(config.portalUrl || config.siteUrl || '');
      if (portalBase) {
        const base = new URL(portalBase);
        const url = new URL('checkout.php', base.origin + '/');
        url.searchParams.set('ref', String(config.resellerId || 'admin'));
        checkoutUrl = url.href;
      }
    } catch (_) {}

    // ── Helper: create a styled info card ──────────────────────────────────────
    function makeCard(id, labelText, bodyHtml, opts = {}) {
      const card = document.createElement('div');
      card.id = id;
      card.className = 'wa-info-card';
      card.style.cssText = `
        background: ${opts.bg || '#1e293b'};
        border: 1.5px solid ${opts.border || '#334155'};
        border-radius: 10px; padding: 12px 14px;
        cursor: ${opts.cursor || 'default'};
        transition: all 0.2s ease;
        display: flex; flex-direction: column; justify-content: center;
        ${opts.fullWidth ? 'grid-column: 1 / -1;' : ''}
        ${opts.extra || ''}
      `;
      card.innerHTML = `
        <div style="font-size:10px; text-transform:uppercase; color:#64748b; font-weight:700; letter-spacing:0.5px; margin-bottom:6px;">${labelText}</div>
        <div>${bodyHtml}</div>
      `;
      return card;
    }

    // ──────────────────────────────────────────────────────────────────────────
    // CARD 1 — ID da Instalação (machine ID)
    // Sempre visível. Admin usa para identificar o cliente e vincular a licença.
    // ──────────────────────────────────────────────────────────────────────────
    const machineIdCard = makeCard(
      'wf-machine-id-card',
      '📟 ID da Instalação',
      `<div style="display:flex; align-items:center; gap:6px;">
        <span id="wf-grid-machine-id" style="font-family:monospace; font-size:11px; color:#60a5fa; word-break:break-all; flex:1;">Carregando...</span>
        <button id="wf-grid-copy-id" style="
          flex-shrink:0; background:${brandColor}22; border:1px solid ${brandColor}44;
          border-radius:6px; padding:4px 8px; color:${brandColor}; cursor:pointer;
          font-size:10px; font-weight:700; font-family:inherit; transition:all 0.15s;
          white-space:nowrap;
        ">📋 Copiar</button>
      </div>
      <div style="font-size:10px; color:#475569; margin-top:4px;">Informe ao admin para receber sua chave</div>`,
      { fullWidth: false, border: `${brandColor}33` }
    );

    // Load and display machine ID async
    License.getMachineId().then(mid => {
      const el = document.getElementById('wf-grid-machine-id');
      if (el) el.textContent = mid || 'Indisponível';
      const btn = document.getElementById('wf-grid-copy-id');
      if (btn && mid) {
        btn.addEventListener('click', async e => {
          e.stopPropagation();
          await navigator.clipboard.writeText(mid).catch(() => {});
          btn.textContent = '✓ Copiado!';
          btn.style.background = '#10b98122';
          btn.style.borderColor = '#10b98144';
          btn.style.color = '#10b981';
          setTimeout(() => {
            btn.textContent = '📋 Copiar';
            btn.style.background = `${brandColor}22`;
            btn.style.borderColor = `${brandColor}44`;
            btn.style.color = brandColor;
          }, 2000);
        });
      }
    }).catch(() => {});

    // ──────────────────────────────────────────────────────────────────────────
    // CARD 2 — Chave de Licença (estado dinâmico)
    // · Trial ativo  → input para digitar chave + botão Ativar
    // · Licença paga → chave mascarada (FLOW-XXXX-••••-••••-XXXX) + copiar
    // · Expirado     → campo proeminente para inserir nova chave
    // ──────────────────────────────────────────────────────────────────────────
    let keyCardHtml, keyCardOpts;

    if (plan === 'trial_7' || (!isValid && plan === 'inactive')) {
      // Trial ou sem licença → mostrar campo de ativação diretamente no painel
      keyCardHtml = `
        <div style="display:flex; gap:6px; align-items:center;">
          <input
            type="text"
            id="wf-grid-key-input"
            placeholder="FLOWHATSAPP-XXXX-XXXX-XXXX"
            style="
              flex:1; background:#0f172a; border:1.5px solid #334155; border-radius:8px;
              color:#e2e8f0; font-family:monospace; font-size:11px; padding:7px 10px;
              outline:none; min-width:0; transition:border-color 0.2s;
            "
            spellcheck="false" autocomplete="off"
          />
          <button id="wf-grid-activate-btn" style="
            flex-shrink:0; background:linear-gradient(135deg,${brandColor},${brandColor}cc);
            border:none; border-radius:8px; color:#fff; cursor:pointer;
            font-size:11px; font-weight:700; font-family:inherit; padding:7px 12px;
            transition:all 0.2s; white-space:nowrap;
          ">✅ Ativar</button>
        </div>
        <div id="wf-grid-key-msg" style="font-size:10px; color:#64748b; margin-top:5px; min-height:14px;"></div>
      `;
      keyCardOpts = { fullWidth: true, border: `${brandColor}44`, extra: 'padding: 14px;' };
    } else if (isValid) {
      // Licença paga ativa → mostrar chave mascarada
      const rawKey = config.licenseKey || '';
      let maskedKey = '••••••••••••••••••••';
      if (rawKey && rawKey.length > 8) {
        // Show first 14 chars + mask middle + last 4
        const parts = rawKey.split('-');
        if (parts.length >= 2) {
          maskedKey = parts[0] + '-' + parts[1] + '-••••-••••-' + (parts[parts.length - 1] || '••••');
        }
      }
      keyCardHtml = `
        <div style="display:flex; align-items:center; gap:6px;">
          <span id="wf-grid-masked-key" style="font-family:monospace; font-size:11px; color:#86efac; flex:1; word-break:break-all;">${escapeHtml(maskedKey)}</span>
          ${rawKey ? `<button id="wf-grid-copy-key" style="
            flex-shrink:0; background:#10b98122; border:1px solid #10b98144;
            border-radius:6px; padding:4px 8px; color:#10b981; cursor:pointer;
            font-size:10px; font-weight:700; font-family:inherit; transition:all 0.15s;
          ">📋 Copiar</button>` : ''}
        </div>
        <div style="font-size:10px; color:#10b981; margin-top:4px;">✓ Licença ativa</div>
      `;
      keyCardOpts = { border: '#10b98144', extra: '' };
    } else {
      // Expirada / inválida → campo de ativação urgente
      keyCardHtml = `
        <div style="display:flex; gap:6px; align-items:center;">
          <input
            type="text"
            id="wf-grid-key-input"
            placeholder="Insira sua chave de licença"
            style="
              flex:1; background:#0f172a; border:1.5px solid #ef444466; border-radius:8px;
              color:#e2e8f0; font-family:monospace; font-size:11px; padding:7px 10px;
              outline:none; min-width:0; transition:border-color 0.2s;
            "
            spellcheck="false" autocomplete="off"
          />
          <button id="wf-grid-activate-btn" style="
            flex-shrink:0; background:linear-gradient(135deg,#ef4444,#dc2626);
            border:none; border-radius:8px; color:#fff; cursor:pointer;
            font-size:11px; font-weight:700; font-family:inherit; padding:7px 12px;
            transition:all 0.2s; white-space:nowrap;
          ">Ativar</button>
        </div>
        <div id="wf-grid-key-msg" style="font-size:10px; color:#fca5a5; margin-top:5px; min-height:14px;">Sua licença expirou. Insira uma nova chave ou renove.</div>
      `;
      keyCardOpts = { fullWidth: true, border: '#ef444444', extra: 'padding:14px;' };
    }

    const keyCard = makeCard(
      'wf-license-key-card',
      plan === 'trial_7' ? '🔑 Já tem uma chave? Ative aqui' : (isValid ? '🎫 Sua Licença' : '🔑 Ativar Licença'),
      keyCardHtml,
      keyCardOpts
    );

    // ── Add cards to the grid ───────────────────────────────────────────────
    // Machine ID before existing cards (prepend)
    infoGrid.insertBefore(machineIdCard, infoGrid.firstChild);
    // License key card at end
    infoGrid.appendChild(keyCard);

    // ── Wire up activation button ────────────────────────────────────────────
    const activateBtn = document.getElementById('wf-grid-activate-btn');
    const keyInput = document.getElementById('wf-grid-key-input');
    const keyMsg = document.getElementById('wf-grid-key-msg');

    if (activateBtn && keyInput) {
      // Style input on focus
      keyInput.addEventListener('focus', () => keyInput.style.borderColor = brandColor);
      keyInput.addEventListener('blur', () => keyInput.style.borderColor = '#334155');
      keyInput.addEventListener('keydown', e => { if (e.key === 'Enter') activateBtn.click(); });

      activateBtn.addEventListener('click', async () => {
        const key = keyInput.value.trim().toUpperCase();
        if (!key) {
          if (keyMsg) { keyMsg.textContent = '⚠ Digite a chave de licença.'; keyMsg.style.color = '#fbbf24'; }
          return;
        }
        activateBtn.disabled = true;
        activateBtn.textContent = '...';
        if (keyMsg) { keyMsg.textContent = 'Validando chave...'; keyMsg.style.color = '#94a3b8'; }

        try {
          const result = await License.activate(key);
          if (result?.valid) {
            if (keyMsg) { keyMsg.textContent = '✓ Licença ativada com sucesso!'; keyMsg.style.color = '#10b981'; }
            activateBtn.textContent = '✓';
            activateBtn.style.background = '#10b981';
            // Reload state and update UI after 1.5s
            setTimeout(() => {
              // Remove injected cards so observer re-injects with updated state
              document.getElementById('wf-machine-id-card')?.remove();
              document.getElementById('wf-license-key-card')?.remove();
              document.getElementById('wf-buy-license-card')?.remove();
            }, 1800);
          } else {
            if (keyMsg) { keyMsg.textContent = `✗ ${result?.message || 'Chave inválida ou expirada.'}`; keyMsg.style.color = '#f87171'; }
            activateBtn.disabled = false;
            activateBtn.textContent = 'Ativar';
          }
        } catch (err) {
          if (keyMsg) { keyMsg.textContent = '✗ Erro de conexão. Tente novamente.'; keyMsg.style.color = '#f87171'; }
          activateBtn.disabled = false;
          activateBtn.textContent = 'Ativar';
        }
      });
    }

    // ── Wire up copy-key button for paid licenses ────────────────────────────
    const copyKeyBtn = document.getElementById('wf-grid-copy-key');
    if (copyKeyBtn && config.licenseKey) {
      copyKeyBtn.addEventListener('click', async e => {
        e.stopPropagation();
        await navigator.clipboard.writeText(config.licenseKey).catch(() => {});
        copyKeyBtn.textContent = '✓ Copiado!';
        setTimeout(() => { copyKeyBtn.textContent = '📋 Copiar'; }, 2000);
      });
    }

    // ── Buy card: only show on trial/expired, not on paid ────────────────────
    if (!isValid || plan === 'trial_7') {
      if (!document.getElementById('wf-buy-license-card')) {
        const buyCard = document.createElement('div');
        buyCard.id = 'wf-buy-license-card';
        buyCard.className = 'wa-info-card';
        buyCard.innerHTML = `
          <div class="wa-info-label" style="font-size:10px;text-transform:uppercase;color:#64748b;font-weight:700;letter-spacing:0.5px;margin-bottom:4px;">Adquirir Licença</div>
          <div class="wa-info-value wa-value-highlight" style="font-size:14px;font-weight:600;color:#ffffff !important;display:flex;align-items:center;gap:6px;">
            Comprar
            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg>
          </div>
        `;
        buyCard.addEventListener('mouseenter', () => { buyCard.style.borderColor = brandColor; buyCard.style.transform = 'translateY(-2px)'; });
        buyCard.addEventListener('mouseleave', () => { buyCard.style.borderColor = '#334155'; buyCard.style.transform = 'none'; });
        buyCard.addEventListener('click', () => window.open(checkoutUrl, '_blank'));
        infoGrid.appendChild(buyCard);
      }
    }
  });
  licenseDialogObserver.observe(document.body, { childList: true, subtree: true });


  // Expõe função para abrir a tela de ativação manualmente (usada pelo painel da extensão)
  self.FLOWhatsappShowActivation = openActivationUI;

  // Expõe a função para abrir modal de avisos
  self.FLOWhatsappShowAnnouncement = function (title, content, id, showMode) {
    if (document.getElementById('wf-announcement-overlay')) return;

    const config = self.FLOWHATSAPP_LICENSE_CONFIG || {};
    const brandColor = safeColor(config.brandColor);

    const overlay = document.createElement('div');
    overlay.id = 'wf-announcement-overlay';
    overlay.style.cssText = `
      position: fixed; inset: 0; z-index: 999999;
      background: rgba(0,0,0,0.85);
      display: flex; align-items: center; justify-content: center;
      font-family: 'Montserrat', -apple-system, sans-serif;
      backdrop-filter: blur(8px);
      padding: max(12px, env(safe-area-inset-top)) max(12px, env(safe-area-inset-right)) max(12px, env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left));
      overflow: auto; overscroll-behavior: contain; box-sizing: border-box;
    `;

    overlay.innerHTML = `
      <div style="
        background: #0f172a; border: 1px solid #1e293b;
        border-radius: 20px; padding: 32px 28px; width: 500px; max-width: 100%; max-height: 100%; overflow: auto;
        box-shadow: 0 25px 60px rgba(0,0,0,0.6);
        animation: wf-announce-fadein 0.4s ease;
        color: #f1f5f9;
      ">
        <style>
          @keyframes wf-announce-fadein { from { opacity:0; transform:translateY(20px); } to { opacity:1; transform:none; } }
          #wf-announcement-overlay * { box-sizing: border-box; }
          #wf-announcement-overlay .wf-announce-btn {
            background: ${brandColor}; color: white; border: none; width: 100%;
            padding: 13px 24px; border-radius: 10px; font-size: 14px; font-weight: 600;
            cursor: pointer; transition: all 0.2s;
          }
          #wf-announcement-overlay .wf-announce-btn:hover { opacity: 0.9; }
        </style>

        <div style="text-align:center; margin-bottom:20px;">
          <div style="font-size:32px; margin-bottom:8px;">📢</div>
          <h2 style="margin:0; font-size:22px; font-weight:700; color:#ffffff;">${escapeHtml(title)}</h2>
        </div>

        <div style="font-size: 14px; line-height: 1.6; color: #cbd5e1; margin-bottom: 25px; max-height: 250px; overflow-y: auto;">
          ${sanitizeRichText(content)}
        </div>

        <button class="wf-announce-btn" id="wf-ann-close-btn">Entendido</button>
      </div>
    `;

    document.body.appendChild(overlay);

    document.getElementById('wf-ann-close-btn').addEventListener('click', async () => {
      overlay.remove();
      if (showMode === 'once') {
        try {
          chrome.storage.local.get(['dismissed_announcements'], (data) => {
            const list = data.dismissed_announcements || [];
            if (!list.includes(id)) {
              list.push(id);
              chrome.storage.local.set({ dismissed_announcements: list });
            }
          });
        } catch (_) {}
      }
    });
  };

  // Expõe a função para abrir o modal de expiração iminente
  self.FLOWhatsappShowExpirationWarning = function (daysLeft, resellerId, appUrl) {
    if (document.getElementById('wf-expiration-overlay')) return;

    const config = self.FLOWHATSAPP_LICENSE_CONFIG || {};
    const brandColor = safeColor(config.brandColor);
    const appName = escapeHtml(config.appName || "FLOWhatsapp");
    const safeDaysLeft = Math.max(0, Math.floor(Number(daysLeft) || 0));

    const overlay = document.createElement('div');
    overlay.id = 'wf-expiration-overlay';
    overlay.style.cssText = `
      position: fixed; inset: 0; z-index: 999999;
      background: rgba(0,0,0,0.8);
      display: flex; align-items: center; justify-content: center;
      font-family: 'Montserrat', -apple-system, sans-serif;
      backdrop-filter: blur(6px);
      padding: max(12px, env(safe-area-inset-top)) max(12px, env(safe-area-inset-right)) max(12px, env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left));
      overflow: auto; overscroll-behavior: contain; box-sizing: border-box;
    `;

    let checkoutUrl = '';
    try {
      const base = new URL(String(appUrl || config.appUrl || ''));
      const local = ['localhost', '127.0.0.1', '::1'].includes(base.hostname);
      if (base.protocol !== 'https:' && !(local && base.protocol === 'http:')) throw new Error('invalid protocol');
      const url = new URL('checkout.php', base.href.endsWith('/') ? base.href : `${base.href}/`);
      url.searchParams.set('ref', String(resellerId || 'admin'));
      checkoutUrl = escapeHtml(url.href);
    } catch (_) { return; }

    overlay.innerHTML = `
      <div style="
        background: #0f172a; border: 1px solid #ef444433;
        border-radius: 20px; padding: 32px 28px; width: 460px; max-width: 100%; max-height: 100%; overflow: auto;
        box-shadow: 0 25px 60px rgba(0,0,0,0.5);
        animation: wf-exp-fadein 0.4s ease;
        color: #f1f5f9;
        text-align: center;
      ">
        <style>
          @keyframes wf-exp-fadein { from { opacity:0; transform:translateY(20px); } to { opacity:1; transform:none; } }
          #wf-expiration-overlay * { box-sizing: border-box; }
          #wf-expiration-overlay .wf-exp-btn-primary {
            background: #ef4444; color: white; border: none; width: 100%;
            padding: 13px 24px; border-radius: 10px; font-size: 14px; font-weight: 700;
            cursor: pointer; transition: all 0.2s; text-decoration: none; display: inline-block;
          }
          #wf-expiration-overlay .wf-exp-btn-primary:hover { background: #dc2626; }
          #wf-expiration-overlay .wf-exp-skip {
            color: #cbd5e1; font-size: 12px; margin-top: 16px; cursor: pointer; text-decoration: underline;
          }
        </style>

        <div style="font-size:44px; margin-bottom:12px;">⏳</div>
        <h2 style="margin:0 0 10px; font-size:22px; font-weight:700; color:#ef4444;">Sua licença expira em breve!</h2>
        
        <p style="font-size: 14px; line-height: 1.6; color: #cbd5e1; margin-bottom: 25px;">
          Sua licença do <strong>${appName}</strong> expira em apenas <strong>${safeDaysLeft} dia${safeDaysLeft !== 1 ? 's' : ''}</strong>. 
          Renove agora mesmo para manter seu Kanban, Chatbots e automações ativos sem interrupções!
        </p>

        <a href="${checkoutUrl}" target="_blank" rel="noopener noreferrer" class="wf-exp-btn-primary" id="wf-exp-renew-btn">Renovar Minha Licença</a>
        
        <div class="wf-exp-skip" id="wf-exp-close-btn">Lembrar mais tarde</div>
      </div>
    `;

    document.body.appendChild(overlay);

    document.getElementById('wf-exp-close-btn').addEventListener('click', () => {
      overlay.remove();
    });
    
    document.getElementById('wf-exp-renew-btn').addEventListener('click', () => {
      overlay.remove();
    });
  };

})();
