/**
 * FLOWhatsapp v2.0 - AI Assistant UI
 * Injects an AI panel into WhatsApp Web for sales assistance.
 */

(() => {
  'use strict';

  /* ── Constants ─────────────────────────────────────────── */
  const PANEL_ID        = 'flowhatsapp-ai-panel';
  const BTN_ID          = 'flowhatsapp-ai-btn';
  const STYLE_ID        = 'flowhatsapp-ai-styles';
  const WA_INPUT_SEL    = "div[contenteditable='true'][data-tab='10']";
  const LEARN_TOGGLE_ID = 'flow-learn-toggle';
  const RESULT_ID       = 'flow-ai-result';
  const SPINNER_ID      = 'flow-ai-spinner';
  const USER_TEXTAREA   = 'flow-user-text';

  /* ── State ──────────────────────────────────────────────── */
  let API_BASE_URL   = '';
  let licenseKey     = '';
  let learnMode      = false;
  let learnObserver  = null;
  let injected       = false;

  /* ── Load config from the real license state ───────────── */
  // The license key lives behind FLOWHATSAPP_LICENSE_GET_STATE (managed by
  // flowhatsapp-license-service.js), not in flat chrome.storage.local keys — those were never
  // written by anything, which is why the AI panel always saw an empty licenseKey before this fix.
  function loadConfig (cb) {
    API_BASE_URL = String((self.FLOWHATSAPP_LICENSE_CONFIG && self.FLOWHATSAPP_LICENSE_CONFIG.appUrl) || '').replace(/\/$/, '');
    chrome.runtime.sendMessage({ type: 'FLOWHATSAPP_LICENSE_GET_STATE' }, (response) => {
      licenseKey = response?.result?.licenseKey || '';
      cb();
    });
  }

  async function getAccessToken () {
    const response = await chrome.runtime.sendMessage({ type: 'FLOWHATSAPP_LICENSE_ACCESS_TOKEN' });
    return response?.result?.success === true ? response.result.accessToken : '';
  }

  /* ── Safe head mounting (document.head may not exist yet at document_start) ─ */
  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 });
  }

  /* ── Styles ─────────────────────────────────────────────── */
  function injectStyles () {
    if (document.getElementById(STYLE_ID)) return;
    const style = document.createElement('style');
    style.id = STYLE_ID;
    style.textContent = `
      :root { --flow-accent: #25D366; }

      #${BTN_ID} {
        display: inline-flex;
        align-items: center;
        gap: 5px;
        padding: 6px 12px;
        margin-left: 6px;
        background: linear-gradient(135deg, var(--flow-accent), #128C7E);
        color: #fff;
        border: none;
        border-radius: 20px;
        font-size: 13px;
        font-weight: 600;
        font-family: 'Segoe UI', sans-serif;
        cursor: pointer;
        box-shadow: 0 2px 12px rgba(37,211,102,0.4);
        transition: transform 0.15s ease, box-shadow 0.15s ease;
        z-index: 9998;
        user-select: none;
      }
      #${BTN_ID}:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 18px rgba(37,211,102,0.55);
      }
      #${BTN_ID}:active { transform: scale(0.97); }

      #${PANEL_ID} {
        position: fixed;
        top: 60px;
        right: 16px;
        width: min(360px, calc(100vw - 24px));
        max-height: calc(100dvh - 24px);
        overflow-y: auto;
        background: rgba(15, 23, 42, 0.95);
        border: 1px solid rgba(255, 255, 255, 0.1);
        border-radius: 16px;
        backdrop-filter: blur(20px);
        -webkit-backdrop-filter: blur(20px);
        box-shadow: 0 8px 40px rgba(0,0,0,0.6), 0 0 0 1px rgba(37,211,102,0.12);
        color: #e2e8f0;
        font-family: 'Segoe UI', system-ui, sans-serif;
        font-size: 14px;
        z-index: 99999;
        animation: flowSlideIn 0.25s cubic-bezier(0.34,1.56,0.64,1);
      }
      @keyframes flowSlideIn {
        from { opacity: 0; transform: translateX(30px) scale(0.96); }
        to   { opacity: 1; transform: translateX(0) scale(1); }
      }

      #${PANEL_ID} .flow-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 14px 16px;
        border-bottom: 1px solid rgba(255,255,255,0.08);
        background: linear-gradient(135deg, rgba(37,211,102,0.12), rgba(18,140,126,0.08));
        border-radius: 16px 16px 0 0;
      }
      #${PANEL_ID} .flow-header-title {
        font-size: 15px;
        font-weight: 700;
        background: linear-gradient(90deg, #25D366, #a3e8c0);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
      }
      #${PANEL_ID} .flow-close {
        background: rgba(255,255,255,0.08);
        border: none;
        color: #e2e8f0;
        width: 28px;
        height: 28px;
        border-radius: 50%;
        cursor: pointer;
        font-size: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: background 0.2s, color 0.2s;
      }
      #${PANEL_ID} .flow-close:hover { background: rgba(239,68,68,0.3); color: #fff; }

      #${PANEL_ID} .flow-body { padding: 14px 16px; display: flex; flex-direction: column; gap: 10px; }

      #${USER_TEXTAREA} {
        width: 100%;
        min-height: 70px;
        background: rgba(255,255,255,0.05);
        border: 1px solid rgba(255,255,255,0.1);
        border-radius: 10px;
        color: #e2e8f0;
        padding: 10px;
        font-family: inherit;
        font-size: 13px;
        resize: vertical;
        outline: none;
        box-sizing: border-box;
        transition: border-color 0.2s;
      }
      #${USER_TEXTAREA}:focus { border-color: var(--flow-accent); }
      #${USER_TEXTAREA}::placeholder { color: #cbd5e1; }

      #${PANEL_ID} .flow-label {
        font-size: 11px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.06em;
        color: #cbd5e1;
        margin-bottom: -4px;
      }

      #${PANEL_ID} .flow-btn-row {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        gap: 6px;
      }
      #${PANEL_ID} .flow-action-btn {
        background: rgba(37,211,102,0.1);
        border: 1px solid rgba(37,211,102,0.25);
        color: #a3e8c0;
        border-radius: 8px;
        padding: 8px 4px;
        font-size: 11px;
        font-weight: 600;
        cursor: pointer;
        text-align: center;
        transition: background 0.2s, transform 0.1s;
        line-height: 1.3;
      }
      #${PANEL_ID} .flow-action-btn:hover {
        background: rgba(37,211,102,0.22);
        transform: translateY(-1px);
      }
      #${PANEL_ID} .flow-action-btn:disabled {
        opacity: 0.4;
        cursor: not-allowed;
        transform: none;
      }

      #${PANEL_ID} .flow-learn-row {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 10px;
        background: rgba(255,255,255,0.03);
        border-radius: 8px;
        border: 1px solid rgba(255,255,255,0.07);
      }
      #${PANEL_ID} .flow-learn-row label {
        font-size: 12px;
        color: #e2e8f0;
        cursor: pointer;
        flex: 1;
      }

      .flow-toggle {
        position: relative;
        width: 36px;
        height: 20px;
        flex-shrink: 0;
      }
      .flow-toggle input { opacity: 0; width: 0; height: 0; }
      .flow-toggle .flow-slider {
        position: absolute;
        inset: 0;
        background: rgba(255,255,255,0.1);
        border-radius: 20px;
        cursor: pointer;
        transition: background 0.3s;
      }
      .flow-toggle .flow-slider::before {
        content: '';
        position: absolute;
        width: 14px;
        height: 14px;
        left: 3px;
        top: 3px;
        background: #fff;
        border-radius: 50%;
        transition: transform 0.3s;
      }
      .flow-toggle input:checked + .flow-slider { background: var(--flow-accent); }
      .flow-toggle input:checked + .flow-slider::before { transform: translateX(16px); }

      #${SPINNER_ID} {
        display: none;
        justify-content: center;
        align-items: center;
        padding: 10px 0;
      }
      #${SPINNER_ID}.active { display: flex; }
      #${SPINNER_ID} .flow-spin {
        width: 28px;
        height: 28px;
        border: 3px solid rgba(37,211,102,0.2);
        border-top-color: var(--flow-accent);
        border-radius: 50%;
        animation: flowSpin 0.7s linear infinite;
      }
      @keyframes flowSpin { to { transform: rotate(360deg); } }

      #${RESULT_ID} {
        background: rgba(255,255,255,0.04);
        border: 1px solid rgba(255,255,255,0.08);
        border-radius: 10px;
        padding: 12px;
        font-size: 13px;
        line-height: 1.6;
        color: #cbd5e1;
        white-space: pre-wrap;
        word-break: break-word;
        max-height: 280px;
        overflow-y: auto;
        display: none;
      }
      #${RESULT_ID}.visible { display: block; animation: flowFadeIn 0.3s ease; }
      @keyframes flowFadeIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }

      #${RESULT_ID} .flow-copy-btn {
        display: block;
        margin-top: 10px;
        background: rgba(37,211,102,0.15);
        border: 1px solid rgba(37,211,102,0.3);
        color: #a3e8c0;
        border-radius: 6px;
        padding: 5px 10px;
        font-size: 11px;
        font-weight: 600;
        cursor: pointer;
        transition: background 0.2s;
      }
      #${RESULT_ID} .flow-copy-btn:hover { background: rgba(37,211,102,0.28); }

      #${PANEL_ID} .flow-error {
        color: #f87171;
        background: rgba(239,68,68,0.08);
        border: 1px solid rgba(239,68,68,0.2);
        border-radius: 8px;
        padding: 8px 10px;
        font-size: 12px;
      }

      #${PANEL_ID}::-webkit-scrollbar { width: 4px; }
      #${PANEL_ID}::-webkit-scrollbar-track { background: transparent; }
      #${PANEL_ID}::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 4px; }
    `;
    appendWhenDocumentReady(style);
  }

  /* ── Build Panel HTML ───────────────────────────────────── */
  function buildPanel () {
    const panel = document.createElement('div');
    panel.id = PANEL_ID;
    panel.innerHTML = `
      <div class="flow-header">
        <span class="flow-header-title">🤖 Assistente FLOWhatsapp</span>
        <button class="flow-close" id="flow-close-btn" title="Fechar">✕</button>
      </div>
      <div class="flow-body">
        <span class="flow-label">Sua mensagem / texto para melhorar</span>
        <textarea id="${USER_TEXTAREA}" placeholder="Cole ou escreva o texto que deseja melhorar..."></textarea>

        <span class="flow-label">Ações da IA</span>
        <div class="flow-btn-row">
          <button class="flow-action-btn" data-action="suggest">💡 Sugerir<br>Resposta</button>
          <button class="flow-action-btn" data-action="improve">✨ Melhorar<br>Meu Texto</button>
          <button class="flow-action-btn" data-action="spellcheck">🔤 Corrigir<br>Ortografia</button>
        </div>

        <div class="flow-learn-row">
          <label class="flow-toggle">
            <input type="checkbox" id="${LEARN_TOGGLE_ID}">
            <span class="flow-slider"></span>
          </label>
          <label for="${LEARN_TOGGLE_ID}">🧠 Modo Aprendizado <small style="color:#475569">(salva contexto da conversa)</small></label>
        </div>

        <div id="${SPINNER_ID}"><div class="flow-spin"></div></div>
        <div id="${RESULT_ID}"></div>
      </div>
    `;
    document.body.appendChild(panel);
    bindPanelEvents(panel);
  }

  /* ── Get last client message from WA DOM ────────────────── */
  function getLastClientMessage () {
    const msgs = document.querySelectorAll('div.message-in span.selectable-text');
    if (!msgs.length) return '';
    return msgs[msgs.length - 1].innerText.trim().slice(0, 2000);
  }

  /* ── API call ───────────────────────────────────────────── */
  async function callAI (action) {
    if (!API_BASE_URL || !licenseKey) {
      showResult('❌ Configure o servidor e a licença nas configurações da extensão.', true);
      return;
    }

    const userText   = document.getElementById(USER_TEXTAREA).value.trim();
    const clientMsg  = getLastClientMessage();

    if (action === 'suggest' && !clientMsg) {
      showResult('⚠️ Nenhuma mensagem do cliente encontrada na conversa.', true);
      return;
    }
    if ((action === 'improve' || action === 'spellcheck') && !userText) {
      showResult('⚠️ Digite o texto que deseja melhorar/corrigir.', true);
      return;
    }

    setLoading(true);

    try {
      const accessToken = await getAccessToken();
      if (!accessToken) throw new Error('license_authorization_required');
      const resp = await fetch(`${API_BASE_URL}/api/ai-proxy.php`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-FLOWhatsapp-Access': accessToken },
        body: JSON.stringify({ licenseKey, action, userMessage: userText, clientMessage: clientMsg })
      });
      const data = await resp.json();

      if (data.error) {
        showResult(`❌ ${data.error}`, true);
      } else {
        showResult(data.result, false);
      }
    } catch (err) {
      showResult('❌ Erro de conexão com o servidor. Verifique sua internet.', true);
    } finally {
      setLoading(false);
    }
  }

  /* ── UI helpers ─────────────────────────────────────────── */
  function setLoading (active) {
    const spinner  = document.getElementById(SPINNER_ID);
    const btns     = document.querySelectorAll(`#${PANEL_ID} .flow-action-btn`);
    if (spinner) spinner.classList.toggle('active', active);
    btns.forEach(b => (b.disabled = active));
  }

  function showResult (text, isError) {
    const el = document.getElementById(RESULT_ID);
    if (!el) return;
    el.classList.remove('visible');
    el.innerHTML = '';

    const content = document.createElement('div');
    if (isError) {
      content.className = 'flow-error';
      content.textContent = text;
    } else {
      content.textContent = text;
      const copyBtn = document.createElement('button');
      copyBtn.className = 'flow-copy-btn';
      copyBtn.textContent = '📋 Copiar';
      copyBtn.onclick = () => {
        navigator.clipboard.writeText(text).then(() => {
          copyBtn.textContent = '✅ Copiado!';
          setTimeout(() => (copyBtn.textContent = '📋 Copiar'), 2000);
        });
      };
      el.appendChild(content);
      el.appendChild(copyBtn);
      el.classList.add('visible');
      return;
    }
    el.appendChild(content);
    el.classList.add('visible');
  }

  /* ── Learn Mode ─────────────────────────────────────────── */
  function enableLearnMode () {
    if (learnObserver) return;
    learnObserver = new MutationObserver((mutations) => {
      for (const mut of mutations) {
        for (const node of mut.addedNodes) {
          if (!(node instanceof Element)) continue;
          const msgEl = node.querySelector?.('div.message-in span.selectable-text');
          if (!msgEl) continue;
          const snippet = msgEl.innerText.trim().slice(0, 1000);
          if (snippet) sendSnippet(snippet);
        }
      }
    });
    const chatContainer = document.querySelector('#main') || document.body;
    learnObserver.observe(chatContainer, { childList: true, subtree: true });
    console.log('[FLOWhatsapp AI] Modo aprendizado ativado.');
  }

  function disableLearnMode () {
    if (learnObserver) {
      learnObserver.disconnect();
      learnObserver = null;
    }
    console.log('[FLOWhatsapp AI] Modo aprendizado desativado.');
  }

  async function sendSnippet (snippet) {
    if (!API_BASE_URL || !licenseKey) return;
    try {
      const accessToken = await getAccessToken();
      if (!accessToken) return;
      await fetch(`${API_BASE_URL}/api/ai-learn.php`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-FLOWhatsapp-Access': accessToken },
        body: JSON.stringify({ licenseKey, action: 'append', snippet })
      });
    } catch (_) { /* silent */ }
  }

  /* ── Bind panel button events ───────────────────────────── */
  function bindPanelEvents (panel) {
    panel.querySelector('#flow-close-btn').addEventListener('click', () => {
      panel.remove();
    });

    panel.querySelectorAll('.flow-action-btn').forEach(btn => {
      btn.addEventListener('click', () => callAI(btn.dataset.action));
    });

    panel.querySelector(`#${LEARN_TOGGLE_ID}`).addEventListener('change', (e) => {
      learnMode = e.target.checked;
      learnMode ? enableLearnMode() : disableLearnMode();
    });
  }

  /* ── Inject AI Button ───────────────────────────────────── */
  function injectAIButton () {
    if (document.getElementById(BTN_ID)) return;

    const inputEl = document.querySelector(WA_INPUT_SEL);
    if (!inputEl) return;

    // Walk up to find toolbar/footer area
    const footer = inputEl.closest('footer') || inputEl.parentElement;
    if (!footer) return;

    const btn = document.createElement('button');
    btn.id = BTN_ID;
    btn.innerHTML = '🤖 IA';
    btn.title = 'Abrir Assistente FLOWhatsapp';
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      if (document.getElementById(PANEL_ID)) {
        document.getElementById(PANEL_ID).remove();
      } else {
        // Refresh config before opening
        loadConfig(() => {
          injectStyles();
          buildPanel();
          // Pre-fill textarea with current input
          const waInput = document.querySelector(WA_INPUT_SEL);
          if (waInput && document.getElementById(USER_TEXTAREA)) {
            document.getElementById(USER_TEXTAREA).value = waInput.innerText.trim();
          }
        });
      }
    });

    footer.appendChild(btn);
    injected = true;
  }

  /* ── Observe WA for chat open ───────────────────────────── */
  function watchForWhatsApp () {
    const observer = new MutationObserver(() => {
      const input = document.querySelector(WA_INPUT_SEL);
      if (input && !document.getElementById(BTN_ID)) {
        injectAIButton();
      }
    });

    observer.observe(document.body, { childList: true, subtree: true });

    // Also try immediately
    injectAIButton();
  }

  /* ── Init ───────────────────────────────────────────────── */
  function init () {
    loadConfig(() => {
      injectStyles();
      watchForWhatsApp();
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }

})();
