/**
 * FLOWhatsapp — Bloqueio de Tela (Lock Screen) Content Script
 * Permite bloquear o WhatsApp Web com senha, com salvamento seguro e interface premium.
 */
(() => {
  'use strict';

  function appendWhenDocumentReady(node) {
    const target = document.head || document.documentElement;
    if (target) {
      target.appendChild(node);
      return;
    }
    document.addEventListener('DOMContentLoaded', () => {
      const readyTarget = document.head || document.documentElement;
      if (readyTarget && !node.isConnected) readyTarget.appendChild(node);
    }, { once: true });
  }

  const STYLE_ID = 'flowhatsapp-lock-styles';
  const STORAGE_KEY_PASS = 'wf_lock_password';
  const STORAGE_KEY_ENABLED = 'wf_lock_enabled';
  const STORAGE_KEY_LOCKED = 'wf_lock_locked';
  const STORAGE_KEY_AUTO_LOCK = 'wf_lock_auto_lock';
  const STORAGE_KEY_IDLE_MINUTES = 'wf_lock_idle_minutes';

  // Injetar estilos CSS para o bloqueio de tela
  function injectStyles() {
    if (document.getElementById(STYLE_ID)) return;
    const style = document.createElement('style');
    style.id = STYLE_ID;
    style.textContent = `
      #wf-lock-screen-overlay {
        position: fixed; inset: 0; z-index: 99999999 !important;
        background: rgba(10, 15, 30, 0.82);
        backdrop-filter: blur(25px) saturate(180%);
        -webkit-backdrop-filter: blur(25px) saturate(180%);
        display: flex; align-items: center; justify-content: center;
        font-family: 'Montserrat', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
        color: #f1f5f9;
        animation: wfLockFadeIn 0.3s ease;
      }
      .wf-lock-card {
        background: rgba(23, 31, 50, 0.72);
        border: 1px solid rgba(255, 255, 255, 0.08);
        border-radius: 28px;
        width: 390px; max-width: 92vw;
        padding: 40px 30px;
        box-shadow: 0 24px 70px rgba(0, 0, 0, 0.5), 0 0 40px rgba(167, 139, 250, 0.15);
        display: flex; flex-direction: column; align-items: center;
        text-align: center;
        box-sizing: border-box;
      }
      .wf-lock-avatar-outer {
        width: 100px; height: 100px;
        border-radius: 50%;
        background: linear-gradient(135deg, #7c3aed, #2563eb);
        padding: 4px;
        box-shadow: 0 10px 25px rgba(124, 58, 237, 0.3);
        margin-bottom: 24px;
        display: flex; align-items: center; justify-content: center;
      }
      .wf-lock-avatar-inner {
        width: 100%; height: 100%;
        border-radius: 50%;
        background: #1e293b;
        overflow: hidden;
        display: flex; align-items: center; justify-content: center;
      }
      .wf-lock-avatar-inner img {
        width: 100%; height: 100%; object-fit: cover;
      }
      .wf-lock-avatar-inner svg {
        width: 50%; height: 50%; color: #e2e8f0;
      }
      .wf-lock-title {
        font-size: 22px; font-weight: 700; margin: 0 0 6px 0;
        background: linear-gradient(135deg, #ffffff, #cbd5e1);
        -webkit-background-clip: text; -webkit-text-fill-color: transparent;
      }
      .wf-lock-subtitle {
        font-size: 13px; color: #e2e8f0; margin: 0 0 28px 0; font-weight: 600;
      }
      .wf-lock-input-wrap {
        width: 100%; position: relative; margin-bottom: 20px;
      }
      .wf-lock-input {
        width: 100%; background: rgba(15, 23, 42, 0.6);
        border: 1.5px solid rgba(255, 255, 255, 0.1);
        border-radius: 14px; padding: 14px 44px 14px 18px;
        color: #fff; font-size: 15px; outline: none;
        transition: all 0.25s ease; font-family: inherit;
        box-sizing: border-box;
      }
      .wf-lock-input:focus {
        border-color: #a78bfa;
        box-shadow: 0 0 0 4px rgba(167, 139, 250, 0.15);
        background: rgba(15, 23, 42, 0.8);
      }
      .wf-lock-eye-btn {
        position: absolute; right: 14px; top: 50%;
        transform: translateY(-50%); background: transparent;
        border: none; color: #e2e8f0; cursor: pointer;
        padding: 4px; display: flex; align-items: center;
        justify-content: center; transition: color 0.2s;
      }
      .wf-lock-eye-btn:hover { color: #a78bfa; }
      .wf-lock-btn {
        width: 100%; background: linear-gradient(135deg, #7c3aed, #6d28d9);
        color: #fff; border: none; border-radius: 14px;
        padding: 14px 20px; font-size: 15px; font-weight: 700;
        cursor: pointer; transition: all 0.25s ease;
        box-shadow: 0 6px 20px rgba(124, 58, 237, 0.25);
        font-family: inherit;
      }
      .wf-lock-btn:hover {
        opacity: 0.95; transform: translateY(-1px);
        box-shadow: 0 8px 24px rgba(124, 58, 237, 0.35);
      }
      .wf-lock-btn:active { transform: none; }
      
      /* Styles for Settings Modal */
      .wf-modal-overlay {
        position: fixed; inset: 0; z-index: 9999999;
        background: rgba(0, 0, 0, 0.7); backdrop-filter: blur(8px);
        display: flex; align-items: center; justify-content: center;
        font-family: 'Montserrat', sans-serif; color: #f1f5f9;
        animation: wfLockFadeIn 0.2s ease;
        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;
      }
      .wf-modal-content {
        background: #111b21; border: 1.5px solid #222e35;
        border-radius: 20px; width: 440px; max-width: 100%; max-height: 100%; overflow: auto;
        padding: 30px; box-shadow: 0 20px 50px rgba(0,0,0,0.5);
        display: flex; flex-direction: column; gap: 20px;
        box-sizing: border-box;
      }
      .wf-modal-header {
        display: flex; justify-content: space-between; align-items: center;
      }
      .wf-modal-title {
        font-size: 18px; font-weight: 700; color: #fff; margin: 0;
      }
      .wf-modal-close {
        background: transparent; border: none; color: #e2e8f0;
        font-size: 20px; cursor: pointer; padding: 4px;
      }
      .wf-modal-close:hover { color: #fff; }
      .wa-menu-item.wf-license-disabled {
        opacity: .58 !important; cursor: not-allowed !important;
      }
      .wa-menu-item.wf-license-disabled:hover {
        background: transparent !important; color: inherit !important;
      }
      .wf-license-menu-badge {
        margin-left:auto; display:inline-flex; align-items:center; gap:5px;
        color:#cbd5e1; font-size:10px; font-weight:700;
      }
      .wf-license-menu-badge svg { width:13px; height:13px; }
      .wf-form-group {
        display: flex; flex-direction: column; gap: 6px; width: 100%;
        box-sizing: border-box;
      }
      .wf-form-label {
        font-size: 12px; font-weight: 700; color: #e2e8f0; text-transform: uppercase;
      }
      .wf-form-input {
        background: #202c33; border: 1px solid #2a3942;
        border-radius: 10px; padding: 11px 14px; color: #fff;
        font-family: inherit; font-size: 14px; outline: none;
        box-sizing: border-box;
      }
      .wf-form-input:focus { border-color: #a78bfa; }
      
      .wf-toggle-wrap {
        display: flex; align-items: center; gap: 12px; cursor: pointer;
        padding: 6px 0; user-select: none;
      }
      .wf-switch {
        position: relative; display: inline-block; width: 40px; height: 22px;
      }
      .wf-switch input { opacity: 0; width: 0; height: 0; }
      .wf-slider {
        position: absolute; cursor: pointer; inset: 0;
        background-color: #334155; border-radius: 34px;
        transition: .3s;
      }
      .wf-slider:before {
        position: absolute; content: ""; height: 16px; width: 16px;
        left: 3px; bottom: 3px; background-color: white;
        border-radius: 50%; transition: .3s;
      }
      input:checked + .wf-slider { background-color: #7c3aed; }
      input:checked + .wf-slider:before { transform: translateX(18px); }
      
      @keyframes wfLockFadeIn {
        from { opacity: 0; } to { opacity: 1; }
      }
      @media (max-width: 480px) {
        .wf-modal-content { border-radius: 16px; padding: 22px 18px; gap: 16px; }
      }
    `;
    appendWhenDocumentReady(style);
  }

  // Obter avatar do WhatsApp Web
  function getWhatsAppAvatar() {
    const avatarImg = document.querySelector('header img') || 
                      document.querySelector('div[data-testid="chatlist-header"] img') ||
                      document.querySelector('.wa-profile-avatar img');
    return avatarImg ? avatarImg.src : '';
  }

  // Obter nome ou título do WhatsApp
  function getWhatsAppName() {
    const nameEl = document.querySelector('div[data-testid="chatlist-header"] span') || 
                   document.querySelector('.wa-device-name');
    return nameEl ? nameEl.textContent : 'WhatsApp Web';
  }

  function toBase64(bytes) { return btoa(String.fromCharCode(...bytes)); }
  function fromBase64(value) { return Uint8Array.from(atob(value), char => char.charCodeAt(0)); }

  async function hashPassword(password, salt = crypto.getRandomValues(new Uint8Array(16))) {
    const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(password), 'PBKDF2', false, ['deriveBits']);
    const bits = await crypto.subtle.deriveBits({ name: 'PBKDF2', salt, iterations: 210000, hash: 'SHA-256' }, key, 256);
    return `pbkdf2$210000$${toBase64(salt)}$${toBase64(new Uint8Array(bits))}`;
  }

  async function verifyPassword(password, stored) {
    const value = String(stored || '');
    // Only the PBKDF2 format is accepted. A pre-PBKDF2 local PIN (if any survived from a very
    // old install) simply won't match anymore — disable and re-enable the lock to set a new one.
    if (!value.startsWith('pbkdf2$')) return false;
    const [, iterations, encodedSalt, expected] = value.split('$');
    const count = Number(iterations);
    if (!Number.isInteger(count) || count < 100000 || count > 500000 || !encodedSalt || !expected) return false;
    try {
      const candidate = await hashPassword(password, fromBase64(encodedSalt));
      return candidate.split('$')[3] === expected;
    } catch (_) { return false; }
  }

  function escapeHtml(value) {
    return String(value || '').replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' })[char]);
  }

  function safeImageUrl(value) {
    try { const url = new URL(String(value || '')); return url.protocol === 'https:' ? url.href : ''; } catch (_) { return ''; }
  }

  function getLicenseState() {
    return new Promise(resolve => {
      chrome.runtime.sendMessage({ type: 'FLOWHATSAPP_LICENSE_GET_STATE' }, response => {
        if (chrome.runtime.lastError || response?.transportError) return resolve(null);
        resolve(response?.result || null);
      });
    });
  }

  async function hasActiveLicense() {
    const state = await getLicenseState();
    return state?.valid === true;
  }

  async function requireActiveLicense() {
    if (await hasActiveLicense()) return true;
    if (typeof self.FLOWhatsappShowActivation === 'function') self.FLOWhatsappShowActivation();
    else document.getElementById('wf-license-launcher')?.click();
    return false;
  }

  function applyMenuLicenseState(licenseValid) {
    const items = [
      {
        element: document.getElementById('wf-lock-menu-item'),
        title: 'Ative sua licença para usar o bloqueio de tela'
      },
      {
        element: document.getElementById('wf-lock-config-item'),
        title: 'Ative sua licença para configurar o bloqueio'
      }
    ];

    items.forEach(({ element, title }) => {
      if (!element) return;
      element.classList.toggle('wf-license-disabled', !licenseValid);
      element.setAttribute('aria-disabled', String(!licenseValid));
      element.tabIndex = licenseValid ? 0 : -1;
      element.title = licenseValid ? '' : title;

      let badge = element.querySelector('.wf-license-menu-badge');
      if (!licenseValid && !badge) {
        badge = document.createElement('span');
        badge.className = 'wf-license-menu-badge';
        badge.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="5" y="10" width="14" height="11" rx="2"></rect><path d="M8 10V7a4 4 0 0 1 8 0v3"></path></svg>Licença';
        element.appendChild(badge);
      } else if (licenseValid) {
        badge?.remove();
      }
    });
  }

  async function refreshMenuLicenseState() {
    applyMenuLicenseState(await hasActiveLicense());
  }

  // Bloquear a tela mostrando o overlay de senha
  async function lockScreen() {
    if (!(await requireActiveLicense())) return;
    // Evitar overlays duplicados
    if (document.getElementById('wf-lock-screen-overlay')) return;

    // Salvar estado atual no storage
    await chrome.storage.local.set({ [STORAGE_KEY_LOCKED]: true });

    injectStyles();

    const overlay = document.createElement('div');
    overlay.id = 'wf-lock-screen-overlay';

    const avatarUrl = safeImageUrl(getWhatsAppAvatar());
    const displayName = escapeHtml(getWhatsAppName());

    overlay.innerHTML = `
      <div class="wf-lock-card">
        <div class="wf-lock-avatar-outer">
          <div class="wf-lock-avatar-inner">
            ${avatarUrl ? `<img src="${avatarUrl}" alt="Profile">` : `
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                <circle cx="12" cy="7" r="4"></circle>
              </svg>
            `}
          </div>
        </div>
        <h2 class="wf-lock-title">${displayName}</h2>
        <p class="wf-lock-subtitle">Esta tela foi protegida pelo FLOWhatsapp</p>
        
        <div class="wf-lock-input-wrap">
          <input type="password" id="wf-lock-password-input" class="wf-lock-input" placeholder="Digite sua senha de acesso..." autocomplete="current-password" />
          <button type="button" id="wf-lock-eye-btn" class="wf-lock-eye-btn" aria-label="Mostrar senha">
            <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
              <circle cx="12" cy="12" r="3"></circle>
            </svg>
          </button>
        </div>
        <div id="wf-lock-err" style="color: #ef4444; font-size: 13px; font-weight: 600; margin-bottom: 15px; display: none;">Senha incorreta. Tente novamente.</div>
        <button type="button" id="wf-lock-submit" class="wf-lock-btn">Desbloquear Tela</button>
      </div>
    `;

    document.body.appendChild(overlay);

    const input = overlay.querySelector('#wf-lock-password-input');
    const submitBtn = overlay.querySelector('#wf-lock-submit');
    const eyeBtn = overlay.querySelector('#wf-lock-eye-btn');
    const errorDiv = overlay.querySelector('#wf-lock-err');

    input.focus();

    // Olho mostrar/ocultar senha
    eyeBtn.addEventListener('click', () => {
      if (input.type === 'password') {
        input.type = 'text';
        eyeBtn.innerHTML = `
          <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path>
            <line x1="1" y1="1" x2="23" y2="23"></line>
          </svg>
        `;
      } else {
        input.type = 'password';
        eyeBtn.innerHTML = `
          <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
            <circle cx="12" cy="12" r="3"></circle>
          </svg>
        `;
      }
    });

    // Submissão da senha
    async function attemptUnlock() {
      const storage = await chrome.storage.local.get(STORAGE_KEY_PASS);
      const savedPass = storage[STORAGE_KEY_PASS];
      if (await verifyPassword(input.value, savedPass)) {
        if (!String(savedPass).startsWith('pbkdf2$')) {
          await chrome.storage.local.set({ [STORAGE_KEY_PASS]: await hashPassword(input.value) });
        }
        await chrome.storage.local.set({ [STORAGE_KEY_LOCKED]: false });
        overlay.remove();
      } else {
        errorDiv.style.display = 'block';
        input.value = '';
        input.focus();
      }
    }

    submitBtn.addEventListener('click', attemptUnlock);
    input.addEventListener('keydown', (e) => {
      if (e.key === 'Enter') attemptUnlock();
    });

    // Bloquear atalhos e cliques fora
    overlay.addEventListener('click', (e) => {
      e.stopPropagation();
      input.focus();
    });
  }

  // Abrir modal de configurações de bloqueio
  async function openLockSettings() {
    if (!(await requireActiveLicense())) return;
    if (document.getElementById('wf-lock-settings-modal')) return;

    injectStyles();

    const storage = await chrome.storage.local.get([
      STORAGE_KEY_PASS, STORAGE_KEY_ENABLED, STORAGE_KEY_AUTO_LOCK, STORAGE_KEY_IDLE_MINUTES
    ]);
    const hasPassword = !!storage[STORAGE_KEY_PASS];
    const isEnabled = storage[STORAGE_KEY_ENABLED] !== false;
    const autoLockEnabled = storage[STORAGE_KEY_AUTO_LOCK] !== false;
    const idleMinutes = [5, 15, 30].includes(Number(storage[STORAGE_KEY_IDLE_MINUTES]))
      ? Number(storage[STORAGE_KEY_IDLE_MINUTES]) : 15;

    const modal = document.createElement('div');
    modal.id = 'wf-lock-settings-modal';
    modal.className = 'wf-modal-overlay';

    modal.innerHTML = `
      <div class="wf-modal-content">
        <div class="wf-modal-header">
          <h3 class="wf-modal-title">Configurações de Bloqueio</h3>
          <button class="wf-modal-close" id="wf-settings-close">×</button>
        </div>
        
        <div class="wf-toggle-wrap" id="wf-lock-toggle-row">
          <label class="wf-switch">
            <input type="checkbox" id="wf-lock-enable-toggle" ${isEnabled ? 'checked' : ''} />
            <span class="wf-slider"></span>
          </label>
          <span style="font-size:14px; font-weight:600;">Ativar função Bloqueio de Tela</span>
        </div>

        <div class="wf-toggle-wrap" style="align-items:flex-start;">
          <label class="wf-switch" style="margin-top:1px;">
            <input type="checkbox" id="wf-auto-lock-toggle" ${autoLockEnabled ? 'checked' : ''} />
            <span class="wf-slider"></span>
          </label>
          <label for="wf-auto-lock-toggle" style="display:flex; flex-direction:column; gap:6px; cursor:pointer;">
            <span style="font-size:14px; font-weight:600;">Bloquear automaticamente por inatividade</span>
            <span style="font-size:12px; color:#cbd5e1;">Após <select id="wf-idle-minutes" class="wf-form-input" style="display:inline-block; width:auto; padding:5px 8px; margin:0 3px;">${[5, 15, 30].map(value => `<option value="${value}" ${idleMinutes === value ? 'selected' : ''}>${value} min</option>`).join('')}</select> sem interação no WhatsApp Web.</span>
          </label>
        </div>

        <div id="wf-password-form-section">
          ${hasPassword ? `
            <p style="font-size:12px; color:#e2e8f0; margin:0 0 10px 0;">Já existe uma senha cadastrada. Preencha abaixo para alterá-la.</p>
            <div class="wf-form-group">
              <label class="wf-form-label">Senha Atual</label>
              <input type="password" class="wf-form-input" id="wf-pass-current" placeholder="Sua senha atual..." />
            </div>
          ` : `
            <p style="font-size:12px; color:#e2e8f0; margin:0 0 10px 0;">Cadastre uma senha para ativar a segurança.</p>
          `}
          
          <div class="wf-form-group" style="margin-top:12px;">
            <label class="wf-form-label">Nova Senha</label>
            <input type="password" class="wf-form-input" id="wf-pass-new" placeholder="Digite a nova senha..." />
          </div>
          
          <div class="wf-form-group" style="margin-top:12px;">
            <label class="wf-form-label">Confirmar Nova Senha</label>
            <input type="password" class="wf-form-input" id="wf-pass-confirm" placeholder="Confirme a nova senha..." />
          </div>

          <div id="wf-settings-error" style="color:#ef4444; font-size:13px; font-weight:600; margin-top:12px; display:none;"></div>
          <div id="wf-settings-success" style="color:#10b981; font-size:13px; font-weight:600; margin-top:12px; display:none;">Alterações salvas com sucesso!</div>
        </div>

        <button type="button" class="wf-lock-btn" id="wf-settings-save" style="margin-top:10px;">Salvar Configurações</button>
      </div>
    `;

    document.body.appendChild(modal);

    const closeBtn = modal.querySelector('#wf-settings-close');
    const saveBtn = modal.querySelector('#wf-settings-save');
    const toggleInput = modal.querySelector('#wf-lock-enable-toggle');
    const autoLockInput = modal.querySelector('#wf-auto-lock-toggle');
    const idleMinutesInput = modal.querySelector('#wf-idle-minutes');
    const errorDiv = modal.querySelector('#wf-settings-error');
    const successDiv = modal.querySelector('#wf-settings-success');

    closeBtn.addEventListener('click', () => modal.remove());

    // Se o usuário clicar fora do modal
    modal.addEventListener('click', (e) => {
      if (e.target === modal) modal.remove();
    });

    saveBtn.addEventListener('click', async () => {
      errorDiv.style.display = 'none';
      successDiv.style.display = 'none';

      const enabled = toggleInput.checked;
      const autoLock = autoLockInput.checked;
      const idleMinutes = [5, 15, 30].includes(Number(idleMinutesInput.value)) ? Number(idleMinutesInput.value) : 15;
      const currentInput = modal.querySelector('#wf-pass-current');
      const newInput = modal.querySelector('#wf-pass-new');
      const confirmInput = modal.querySelector('#wf-pass-confirm');

      // Se desativar o bloqueio apenas
      if (!enabled) {
        await chrome.storage.local.set({
          [STORAGE_KEY_ENABLED]: false,
          [STORAGE_KEY_AUTO_LOCK]: autoLock,
          [STORAGE_KEY_IDLE_MINUTES]: idleMinutes,
        });
        window.dispatchEvent(new Event('wf-lock-settings-changed'));
        successDiv.style.display = 'block';
        setTimeout(() => modal.remove(), 1200);
        return;
      }

      // Senhas vazias
      if (!hasPassword && (!newInput.value || !confirmInput.value)) {
        errorDiv.textContent = 'Preencha todos os campos de senha.';
        errorDiv.style.display = 'block';
        return;
      }

      if (newInput.value || confirmInput.value) {
        // Se já tinha senha e está alterando
        if (hasPassword) {
          if (!currentInput.value) {
            errorDiv.textContent = 'Digite sua senha atual.';
            errorDiv.style.display = 'block';
            return;
          }
          const savedPass = storage[STORAGE_KEY_PASS];
          if (!(await verifyPassword(currentInput.value, savedPass))) {
            errorDiv.textContent = 'Senha atual incorreta.';
            errorDiv.style.display = 'block';
            return;
          }
        }

        // Senha nova e confirmação diferem
        if (newInput.value !== confirmInput.value) {
          errorDiv.textContent = 'As novas senhas não coincidem.';
          errorDiv.style.display = 'block';
          return;
        }

        // Senha curta
        if (newInput.value.length < 8) {
          errorDiv.textContent = 'A senha deve ter no mínimo 8 caracteres.';
          errorDiv.style.display = 'block';
          return;
        }

        // Salvar nova senha
        await chrome.storage.local.set({
          [STORAGE_KEY_PASS]: await hashPassword(newInput.value),
          [STORAGE_KEY_ENABLED]: true,
          [STORAGE_KEY_AUTO_LOCK]: autoLock,
          [STORAGE_KEY_IDLE_MINUTES]: idleMinutes,
        });
      } else {
        // Apenas ativou a função sem trocar senha
        await chrome.storage.local.set({
          [STORAGE_KEY_ENABLED]: true,
          [STORAGE_KEY_AUTO_LOCK]: autoLock,
          [STORAGE_KEY_IDLE_MINUTES]: idleMinutes,
        });
      }

      window.dispatchEvent(new Event('wf-lock-settings-changed'));
      successDiv.style.display = 'block';
      setTimeout(() => modal.remove(), 1200);
    });
  }

  // Inserir opções no dropdown do menu da extensão
  async function injectMenuOption(dropdown) {
    const menuContainer = dropdown.querySelector('.wa-dropdown-menu');
    if (!menuContainer) return;

    // Evitar itens duplicados
    if (document.getElementById('wf-lock-menu-item') || dropdown.dataset.wfLockInjectionPending === 'true') return;
    dropdown.dataset.wfLockInjectionPending = 'true';
    const licenseValid = await hasActiveLicense();
    delete dropdown.dataset.wfLockInjectionPending;
    if (document.getElementById('wf-lock-menu-item')) return;

    // Criar divisória
    const divider = document.createElement('div');
    divider.className = 'wa-dropdown-divider';

    // Item: Bloquear Tela
    const lockItem = document.createElement('div');
    lockItem.className = 'wa-menu-item';
    lockItem.id = 'wf-lock-menu-item';
    lockItem.innerHTML = `
      <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right:12px; color:#a78bfa; flex-shrink: 0;">
        <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
        <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
      </svg>
      <span>Bloquear Tela</span>
      ${licenseValid ? '' : '<span class="wf-license-menu-badge"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="5" y="10" width="14" height="11" rx="2"></rect><path d="M8 10V7a4 4 0 0 1 8 0v3"></path></svg>Licença</span>'}
    `;
    lockItem.classList.toggle('wf-license-disabled', !licenseValid);
    lockItem.setAttribute('role', 'menuitem');
    lockItem.setAttribute('aria-disabled', String(!licenseValid));
    lockItem.tabIndex = licenseValid ? 0 : -1;
    if (!licenseValid) lockItem.title = 'Ative sua licença para usar o bloqueio de tela';

    lockItem.addEventListener('click', async () => {
      // Ocultar dropdown
      dropdown.style.display = 'none';
      if (!(await requireActiveLicense())) return;

      // Verificar se possui senha cadastrada
      const storage = await chrome.storage.local.get([STORAGE_KEY_PASS, STORAGE_KEY_ENABLED]);
      if (!storage[STORAGE_KEY_PASS]) {
        // Sem senha -> abre modal para cadastrar
        openLockSettings();
      } else {
        // Bloquear
        lockScreen();
      }
    });

    // Item: Configurar Bloqueio
    const configItem = document.createElement('div');
    configItem.className = 'wa-menu-item';
    configItem.id = 'wf-lock-config-item';
    configItem.innerHTML = `
      <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right:12px; color:#a78bfa; flex-shrink: 0;">
        <circle cx="12" cy="12" r="3"></circle>
        <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
      </svg>
      <span>Configurar Bloqueio</span>
      ${licenseValid ? '' : '<span class="wf-license-menu-badge"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="5" y="10" width="14" height="11" rx="2"></rect><path d="M8 10V7a4 4 0 0 1 8 0v3"></path></svg>Licença</span>'}
    `;
    configItem.classList.toggle('wf-license-disabled', !licenseValid);
    configItem.setAttribute('role', 'menuitem');
    configItem.setAttribute('aria-disabled', String(!licenseValid));
    configItem.tabIndex = licenseValid ? 0 : -1;
    if (!licenseValid) configItem.title = 'Ative sua licença para configurar o bloqueio';

    configItem.addEventListener('click', async () => {
      dropdown.style.display = 'none';
      if (!(await requireActiveLicense())) return;
      openLockSettings();
    });

    // Inserir antes da última divisória do menu ou no final
    const lastDivider = menuContainer.querySelector('.wa-dropdown-divider:last-child') || 
                        menuContainer.querySelector('div[style*="height: 1px"]');
    
    if (lastDivider) {
      menuContainer.insertBefore(divider, lastDivider);
      menuContainer.insertBefore(lockItem, lastDivider);
      menuContainer.insertBefore(configItem, lastDivider);
    } else {
      menuContainer.appendChild(divider);
      menuContainer.appendChild(lockItem);
      menuContainer.appendChild(configItem);
    }
    applyMenuLicenseState(licenseValid);
  }

  // Inicializar observação de inatividade e estado persistente
  async function init() {
    // 1. Verificar se deve bloquear no carregamento
    const storage = await chrome.storage.local.get([
      STORAGE_KEY_LOCKED, STORAGE_KEY_ENABLED, STORAGE_KEY_PASS, STORAGE_KEY_AUTO_LOCK, STORAGE_KEY_IDLE_MINUTES
    ]);
    const isLocked = storage[STORAGE_KEY_LOCKED] === true;
    const isEnabled = storage[STORAGE_KEY_ENABLED] !== false;
    const hasPassword = !!storage[STORAGE_KEY_PASS];
    let autoLockEnabled = storage[STORAGE_KEY_AUTO_LOCK] !== false;
    let idleTimeLimit = ([5, 15, 30].includes(Number(storage[STORAGE_KEY_IDLE_MINUTES]))
      ? Number(storage[STORAGE_KEY_IDLE_MINUTES]) : 15) * 60 * 1000;

    if (isLocked && isEnabled && hasPassword && await hasActiveLicense()) {
      lockScreen();
    }

    // 2. Escutar por alterações do dropdown
    const observer = new MutationObserver(() => {
      const dropdown = document.querySelector('.wa-profile-dropdown');
      if (dropdown && !document.getElementById('wf-lock-menu-item')) {
        injectMenuOption(dropdown);
      }
    });
    observer.observe(document.body, { childList: true, subtree: true });

    // The license service persists every activation, trial, heartbeat and
    // deactivation in this key. Keep both menu entries in sync without a page
    // reload, while still re-checking the server-backed state on every click.
    chrome.storage.onChanged.addListener((changes, areaName) => {
      if (areaName === 'local' && changes.flowhatsapp_license_session) {
        refreshMenuLicenseState();
      }
    });

    // 3. Monitoramento de Inatividade (Auto-Lock opcional)
    let idleTimer;

    function resetIdleTimer() {
      clearTimeout(idleTimer);
      if (!autoLockEnabled) return;
      idleTimer = setTimeout(async () => {
        const check = await chrome.storage.local.get([STORAGE_KEY_ENABLED, STORAGE_KEY_PASS]);
        if (check[STORAGE_KEY_ENABLED] !== false && check[STORAGE_KEY_PASS] && await hasActiveLicense()) {
          lockScreen();
        }
      }, idleTimeLimit);
    }

    // Apenas se auto-lock estiver habilitado
    window.addEventListener('mousemove', resetIdleTimer);
    window.addEventListener('keypress', resetIdleTimer);
    window.addEventListener('click', resetIdleTimer);
    window.addEventListener('scroll', resetIdleTimer);
    window.addEventListener('wf-lock-settings-changed', async () => {
      const current = await chrome.storage.local.get([STORAGE_KEY_AUTO_LOCK, STORAGE_KEY_IDLE_MINUTES]);
      autoLockEnabled = current[STORAGE_KEY_AUTO_LOCK] !== false;
      const minutes = Number(current[STORAGE_KEY_IDLE_MINUTES]);
      idleTimeLimit = ([5, 15, 30].includes(minutes) ? minutes : 15) * 60 * 1000;
      resetIdleTimer();
    });
    resetIdleTimer();
  }

  // Executar init de forma segura aguardando o DOM
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
