/** FLOWhatsapp v2.0 — content-side bridge to the MV3 license service worker. */
(() => {
  '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 });
  }

  let machineIdPromise;

  async function sha256(value) {
    const bytes = new TextEncoder().encode(String(value || ''));
    const digest = await crypto.subtle.digest('SHA-256', bytes);
    return Array.from(new Uint8Array(digest), b => b.toString(16).padStart(2, '0')).join('');
  }

  async function getMachineId() {
    if (!machineIdPromise) {
      machineIdPromise = (async () => {
        let canvasSignature = '';
        let webglSignature = '';
        try {
          const canvas = document.createElement('canvas');
          canvas.width = 240; canvas.height = 60;
          const context = canvas.getContext('2d');
          context.textBaseline = 'top'; context.font = '16px Arial';
          context.fillStyle = '#7C3AED'; context.fillRect(3, 3, 90, 27);
          context.fillStyle = '#f59e0b'; context.fillText('FLOWhatsapp • 2026', 8, 9);
          canvasSignature = canvas.toDataURL();
        } catch (_) {}
        try {
          const canvas = document.createElement('canvas');
          const gl = canvas.getContext('webgl');
          const extension = gl?.getExtension('WEBGL_debug_renderer_info');
          webglSignature = extension
            ? `${gl.getParameter(extension.UNMASKED_VENDOR_WEBGL)}|${gl.getParameter(extension.UNMASKED_RENDERER_WEBGL)}`
            : `${gl?.getParameter(gl.VENDOR) || ''}|${gl?.getParameter(gl.RENDERER) || ''}`;
        } catch (_) {}
        const parts = [
          'flowhatsapp-device-v2', navigator.userAgent || '', navigator.platform || '',
          `${screen.width}x${screen.height}x${screen.availWidth}x${screen.availHeight}x${screen.colorDepth}`,
          `pixel:${devicePixelRatio || 1}`, `cpu:${navigator.hardwareConcurrency || 0}`,
          `ram:${navigator.deviceMemory || 0}`, `touch:${navigator.maxTouchPoints || 0}`,
          Intl.DateTimeFormat().resolvedOptions().timeZone || '',
          (navigator.languages || [navigator.language || '']).join(','), canvasSignature, webglSignature
        ];
        return (await sha256(parts.join('|'))).slice(0, 32);
      })();
    }
    return machineIdPromise;
  }

  function send(type, payload = {}) {
    return new Promise((resolve, reject) => {
      chrome.runtime.sendMessage({ type, ...payload }, response => {
        if (chrome.runtime.lastError) reject(new Error(chrome.runtime.lastError.message));
        else if (!response) reject(new Error('O serviço de licença não respondeu.'));
        else if (response.transportError) reject(new Error(response.transportError));
        else resolve(response.result);
      });
    });
  }

  async function getState() {
    const machineId = await getMachineId();
    // The service worker performs a server-side bootstrap when local storage
    // is empty. Never issue a second client-side trial request after a denial.
    return send('FLOWHATSAPP_LICENSE_GET_STATE', { machineId });
  }

  function detectWhatsAppState() {
    if (document.querySelector('canvas[data-ref], [data-testid="qrcode"]')) return 'qr_code';
    if (document.querySelector('progress, [data-testid="startup-progress"]')) return 'loading';
    if (document.getElementById('side') || document.querySelector('[data-testid="chat-list"]')) return 'connected';
    return 'disconnected';
  }

  self.FLOWhatsappLicense = {
    getMachineId,
    getState,
    async startTrial(lead = {}) {
      return send('FLOWHATSAPP_LICENSE_TRIAL', {
        machineId: await getMachineId(),
        leadName: String(lead.name || '').slice(0, 80),
        leadContact: String(lead.contact || '').slice(0, 100)
      });
    },
    async activate(key) {
      return send('FLOWHATSAPP_LICENSE_ACTIVATE', { key, machineId: await getMachineId() });
    },
    async isActive() {
      const state = await getState();
      return state?.valid === true && (!state.expiresAt || new Date(state.expiresAt).getTime() > Date.now());
    },
    async getPlan() { return (await getState())?.plan || 'inactive'; },
    async getFeatures() {
      const state = await getState();
      return state?.valid === true && Array.isArray(state.featuresEnabled) ? state.featuresEnabled : [];
    },
    async deactivate() { return send('FLOWHATSAPP_LICENSE_DEACTIVATE'); },
    async getPublicConfig() { return send('FLOWHATSAPP_LICENSE_PUBLIC_CONFIG'); },
    async fsGet(collection) {
      if (collection !== 'resellers') return null;
      const config = await send('FLOWHATSAPP_LICENSE_PUBLIC_CONFIG');
      return config ? {
        phone: config.supportPhone,
        name: config.appName,
        brandColor: config.brandColor,
        tutorialUrl: config.tutorialUrl,
        contactUrl: config.contactUrl,
        siteUrl: config.siteUrl
      } : null;
    }
  };

  const getWhatsappLink = (phone) => {
    if (!phone) return '';
    const num = String(phone).replace(/\D/g, '');
    if (!num) return '';
    let clean = num.replace(/^0+/, '');
    if (clean.length === 10 || clean.length === 11) {
      clean = '55' + clean;
    }
    return 'https://wa.me/' + clean;
  };

  setTimeout(() => getState().catch(() => {}), 1500);
  setInterval(async () => {
    try {
      await send('FLOWHATSAPP_LICENSE_HEARTBEAT', {
        machineId: await getMachineId(),
        whatsappState: detectWhatsAppState()
      });
    } catch (_) {
      // The next scheduled heartbeat retries without affecting WhatsApp Web.
    }
  }, 5 * 60 * 1000);

  // Listener do Isolated World para responder às solicitações de branding do Main World
  window.addEventListener('message', async (event) => {
    if (event.source !== window) return;
    const data = event?.data;
    if (data && data.type === 'FLOWHATSAPP_REQUEST_PDF_BRANDING') {
      let branding = {};
      try {
        const config = await send('FLOWHATSAPP_LICENSE_PUBLIC_CONFIG');
        if (config) {
          branding = {
            appName: config.appName,
            brandColor: config.brandColor,
            brandLogoUrl: config.brandLogoUrl,
            supportPhone: config.supportPhone,
            tutorialUrl: config.tutorialUrl,
            contactUrl: config.contactUrl,
            siteUrl: config.siteUrl
          };
        }
      } catch (_) {}
      window.postMessage({ type: 'FLOWHATSAPP_RESPONSE_PDF_BRANDING', branding }, window.location.origin);
    }
  });

  async function injectExportScriptToMainWorld() {
    // Manifest V3 forbids inline script execution. The packaged bridge asks this
    // isolated content script to generate the report without weakening CSP.
    const bridge = document.createElement('script');
    bridge.src = chrome.runtime.getURL('flowhatsapp-pdf-bridge.js');
    bridge.async = false;
    appendWhenDocumentReady(bridge);
    bridge.addEventListener('load', () => bridge.remove(), { once: true });
    bridge.addEventListener('error', () => bridge.remove(), { once: true });
  }

  // Executar injeção no Main World e também manter no Isolated World
  injectExportScriptToMainWorld().catch(() => {});

  self.FLOWHATSAPP_EXPORT_PDF = async function () {
    const leads = typeof window.FLOWHATSAPP_GET_LEADS === 'function' ? window.FLOWHATSAPP_GET_LEADS() : null;
    if (!leads || !leads.length) {
      alert('Nenhum lead disponível para exportar no momento.');
      return;
    }

    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) : '#2563eb';
    // Leads are scraped from third-party Google Maps listings, so whatsapp/website fields are
    // untrusted: escapeHtml() alone does not stop a "javascript:" scheme from surviving into an
    // href attribute, only a real scheme allowlist does.
    const safeHttpsUrl = (value) => {
      try { const url = new URL(String(value || '')); return url.protocol === 'https:' ? url.href : ''; }
      catch (_) { return ''; }
    };

    let config = self.FLOWHATSAPP_LICENSE_CONFIG;
    if (!config) {
      try {
        const remote = await self.FLOWhatsappLicense.getPublicConfig();
        if (remote?.success) {
          config = {
            appName: remote.appName,
            brandColor: remote.brandColor,
            brandLogoUrl: remote.brandLogoUrl,
            supportPhone: remote.supportPhone,
            tutorialUrl: remote.tutorialUrl,
            contactUrl: remote.contactUrl,
            siteUrl: remote.siteUrl
          };
          self.FLOWHATSAPP_LICENSE_CONFIG = config;
        }
      } catch (_) {}
    }
    if (!config) config = {};

    const appName = config.appName || 'FLOWhatsapp';
    const brandColor = safeColor(config.brandColor);
    const logoUrl = config.brandLogoUrl || '';
    // Packaged font, same as the rest of the product — this report window must not depend on
    // a remote Google Fonts request (CSP-free popup, and it would leak the user's IP to Google).
    const fontUrl = chrome.runtime.getURL('fonts/Montserrat-Variable.ttf');
    
    const totalLeads = leads.length;
    let leadsWithPhone = 0;
    let leadsWithEmail = 0;
    let totalRating = 0;
    let ratedCount = 0;
    
    leads.forEach(l => {
      if (l.phone && l.phone.trim().length > 0) leadsWithPhone++;
      if (l.email && l.email.trim().length > 0) leadsWithEmail++;
      if (l.rating !== undefined && l.rating !== null && !isNaN(Number(l.rating))) {
        totalRating += Number(l.rating);
        ratedCount++;
      }
    });
    
    const avgRating = ratedCount > 0 ? (totalRating / ratedCount).toFixed(1) : 'N/A';

    const printWindow = window.open('', '_blank');
    if (!printWindow) {
      alert('Por favor, permita popups neste site para abrir o relatório em PDF.');
      return;
    }

    const dateStr = new Date().toLocaleString('pt-BR');

    let html = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Relatório de Leads GMaps - ${escapeHtml(appName)}</title>
  <style>
    @font-face {
      font-family: 'Montserrat';
      src: url('${fontUrl}') format('truetype');
      font-weight: 300 800;
      font-style: normal;
      font-display: swap;
    }
    :root {
      --brand-color: ${brandColor};
      --bg-light: #f8fafc;
      --text-main: #0f172a;
      --text-muted: #475569;
      --border-color: #e2e8f0;
    }
    
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    
    @page {
      size: A4 landscape;
      margin: 10mm;
    }
    
    body {
      font-family: 'Montserrat', sans-serif;
      color: var(--text-main);
      background-color: #ffffff;
      padding: 20px;
      line-height: 1.4;
    }
    
    .no-print-header {
      background: #0f172a;
      padding: 12px 24px;
      margin: -20px -20px 20px -20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: #ffffff;
      box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);
    }
    
    .no-print-header h1 {
      font-size: 15px;
      font-weight: 600;
      letter-spacing: 0.5px;
      display: flex;
      align-items: center;
      gap: 8px;
    }
    
    .no-print-btn {
      background: var(--brand-color);
      color: #ffffff;
      border: none;
      padding: 8px 16px;
      border-radius: 6px;
      font-size: 12px;
      font-weight: 700;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      gap: 6px;
      transition: opacity 0.2s;
    }
    
    .no-print-btn:hover {
      opacity: 0.9;
    }

    .report-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 2px solid var(--brand-color);
      padding-bottom: 15px;
      margin-bottom: 20px;
    }
    
    .logo-area {
      display: flex;
      align-items: center;
      gap: 10px;
    }
    
    .logo-img {
      max-height: 40px;
      max-width: 120px;
      object-fit: contain;
    }
    
    .brand-name {
      font-size: 20px;
      font-weight: 800;
      color: var(--brand-color);
      letter-spacing: -0.5px;
    }
    
    .report-title-area {
      text-align: right;
    }
    
    .report-title {
      font-size: 18px;
      font-weight: 700;
      color: #1e293b;
      margin-bottom: 2px;
    }
    
    .report-date {
      font-size: 11px;
      color: var(--text-muted);
      font-weight: 500;
    }

    .summary-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 15px;
      margin-bottom: 25px;
    }
    
    .summary-card {
      background: var(--bg-light);
      border: 1px solid var(--border-color);
      border-radius: 8px;
      padding: 12px;
      text-align: center;
    }
    
    .summary-label {
      font-size: 10px;
      font-weight: 700;
      text-transform: uppercase;
      color: var(--text-muted);
      letter-spacing: 0.5px;
      margin-bottom: 4px;
    }
    
    .summary-val {
      font-size: 20px;
      font-weight: 800;
      color: var(--brand-color);
    }

    .leads-table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 15px;
      font-size: 10.5px;
    }
    
    .leads-table th {
      background-color: #0f172a;
      color: #ffffff !important;
      text-align: left;
      padding: 10px 8px;
      font-weight: 700;
      border-bottom: 2px solid var(--brand-color);
    }
    
    .leads-table td {
      padding: 8px 8px;
      border-bottom: 1px solid var(--border-color);
      color: var(--text-main);
      vertical-align: middle;
      word-break: break-word;
    }
    
    .leads-table tr:nth-child(even) {
      background-color: var(--bg-light);
    }
    
    .badge {
      display: inline-block;
      padding: 2px 5px;
      border-radius: 3px;
      font-size: 9px;
      font-weight: 700;
      text-transform: uppercase;
      white-space: nowrap;
    }
    
    .badge-phone {
      background-color: #dcfce7;
      color: #15803d;
    }
    
    .badge-rating {
      background-color: #fef9c3;
      color: #a16207;
      display: inline-flex;
      align-items: center;
      gap: 2px;
    }
    
    .link-text {
      color: var(--brand-color);
      text-decoration: none;
      word-break: break-all;
    }
    
    @media print {
      body {
        padding: 0;
      }
      .no-print-header {
        display: none !important;
      }
      .summary-card {
        background: #ffffff !important;
        border: 1px solid #cbd5e1 !important;
      }
      .leads-table th {
        background-color: #1e293b !important;
        color: #ffffff !important;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
        border-bottom: 2px solid var(--brand-color) !important;
      }
      .leads-table tr:nth-child(even) {
        background-color: #f8fafc !important;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
      }
      .badge-phone {
        background-color: #e2e8f0 !important;
        color: #000000 !important;
      }
      .badge-rating {
        background-color: #e2e8f0 !important;
        color: #000000 !important;
      }
    }
  </style>
</head>
<body>

  <div class="no-print-header">
    <h1>
      <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
        <polyline points="14 2 14 8 20 8"></polyline>
        <line x1="16" y1="13" x2="8" y2="13"></line>
        <line x1="16" y1="17" x2="8" y2="17"></line>
        <polyline points="10 9 9 9 8 9"></polyline>
      </svg>
      Visualização de Impressão do Relatório
    </h1>
    <button class="no-print-btn" onclick="window.print()">
      <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
        <polyline points="6 9 6 2 18 2 18 9"></polyline>
        <path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"></path>
        <rect x="6" y="14" width="12" height="8"></rect>
      </svg>
      Imprimir / Salvar PDF
    </button>
  </div>

  <div class="report-header">
    <div class="logo-area">
      ${logoUrl ? `<img class="logo-img" src="${escapeHtml(logoUrl)}" alt="Logo">` : ''}
      <span class="brand-name">${escapeHtml(appName)}</span>
    </div>
    <div class="report-title-area">
      <div class="report-title">Relatório de Leads GMaps</div>
      <div class="report-date">Gerado em ${escapeHtml(dateStr)}</div>
    </div>
  </div>

  <div class="summary-grid">
    <div class="summary-card">
      <div class="summary-label">Total de Leads</div>
      <div class="summary-val">${totalLeads}</div>
    </div>
    <div class="summary-card">
      <div class="summary-label">Com Telefone</div>
      <div class="summary-val">${leadsWithPhone}</div>
    </div>
    <div class="summary-card">
      <div class="summary-label">Com E-mail</div>
      <div class="summary-val">${leadsWithEmail}</div>
    </div>
    <div class="summary-card">
      <div class="summary-label">Média Avaliações</div>
      <div class="summary-val">${avgRating} ★</div>
    </div>
  </div>

  <table class="leads-table">
    <thead>
      <tr>
        <th style="width: 18%;">Nome da Empresa</th>
        <th style="width: 10%;">Telefone</th>
        <th style="width: 10%;">WhatsApp</th>
        <th style="width: 10%;">Instagram</th>
        <th style="width: 10%;">Categoria</th>
        <th style="width: 8%; text-align: center;">Nota</th>
        <th style="width: 14%;">Endereço</th>
        <th style="width: 10%;">E-mail</th>
        <th style="width: 10%;">Site</th>
      </tr>
    </thead>
    <tbody>`;

    leads.forEach(l => {
      const name = escapeHtml(l.name || 'N/A');
      const phone = escapeHtml(l.phone || 'N/A');
      const whatsappRaw = l.whatsapp ? String(l.whatsapp) : '';
      const whatsappUrl = whatsappRaw ? safeHttpsUrl(whatsappRaw) : '';
      const instagramRaw = l.instagram ? String(l.instagram) : '';
      const instagramUrl = instagramRaw ? safeHttpsUrl(instagramRaw) : '';
      const category = escapeHtml(l.category || 'N/A');
      const rating = l.rating !== undefined && l.rating !== null ? `${Number(l.rating).toFixed(1)}` : 'N/A';
      const reviews = l.reviews !== undefined && l.reviews !== null ? ` (${l.reviews})` : '';
      const address = escapeHtml(l.address || 'N/A');
      const email = escapeHtml(l.email || '');
      const websiteRaw = l.website ? String(l.website) : '';
      const websiteUrl = websiteRaw ? safeHttpsUrl(websiteRaw) : '';
      const websiteLabel = websiteRaw ? escapeHtml(websiteRaw.replace(/^https?:\/\/(www\.)?/, '')) : '';

      html += `
      <tr>
        <td style="font-weight: 600;">${name}</td>
        <td>${phone !== 'N/A' ? `<span class="badge badge-phone">${phone}</span>` : 'N/A'}</td>
        <td>${whatsappUrl ? `<a class="link-text" href="${whatsappUrl}" target="_blank">WhatsApp</a>` : (whatsappRaw ? escapeHtml(whatsappRaw) : 'N/A')}</td>
        <td>${instagramUrl ? `<a class="link-text" href="${instagramUrl}" target="_blank">Instagram</a>` : (instagramRaw ? escapeHtml(instagramRaw) : 'N/A')}</td>
        <td>${category}</td>
        <td style="text-align: center;">
          ${rating !== 'N/A' ? `<span class="badge badge-rating">${rating} ★${reviews}</span>` : 'N/A'}
        </td>
        <td>${address}</td>
        <td>${email ? `<a class="link-text" href="mailto:${email}">${email}</a>` : 'N/A'}</td>
        <td>${websiteUrl ? `<a class="link-text" href="${websiteUrl}" target="_blank">${websiteLabel}</a>` : (websiteRaw ? escapeHtml(websiteRaw) : 'N/A')}</td>
      </tr>`;
    });

    html += `
    </tbody>
  </table>
</body>
</html>`;

    printWindow.document.write(html);
    printWindow.document.close();
    setTimeout(() => printWindow.print(), 500);
  };

  window.addEventListener('message', event => {
    if (event.source === window && event.data?.type === 'FLOWHATSAPP_REQUEST_EXPORT_PDF') {
      self.FLOWHATSAPP_EXPORT_PDF();
    }
  });
})();
