let activeTemplateInputId = null;
const templateModalElement = document.getElementById('templateEditorModal');
const promoModalElement = document.getElementById('chatbotInfoModal');
const modalTitle = document.getElementById('templateModalTitle');
const modalDescription = document.getElementById('templateModalDescription');
const modalTextarea = document.getElementById('templateModalTextarea');
const previewBox = document.getElementById('templatePreviewBox');
const saveTemplateModalBtn = document.getElementById('saveTemplateModalBtn');
let modalFallbackBackdrop = null;

function hasJQuery() {
  return typeof window.jQuery !== 'undefined';
}

function cleanupModalCompat(modalElement) {
  if (modalFallbackBackdrop && modalFallbackBackdrop.parentNode) {
    modalFallbackBackdrop.parentNode.removeChild(modalFallbackBackdrop);
  }
  modalFallbackBackdrop = null;
  document.querySelectorAll('.modal-backdrop').forEach(function(node, idx) {
    if (idx > 0 || !hasJQuery()) {
      if (node.parentNode) node.parentNode.removeChild(node);
    }
  });
  if (modalElement) {
    modalElement.classList.remove('show');
    modalElement.style.display = 'none';
    modalElement.setAttribute('aria-hidden', 'true');
    modalElement.removeAttribute('aria-modal');
  }
  document.body.classList.remove('modal-open');
  document.body.style.overflow = '';
}

function openModalCompat(modalElement) {
  if (!modalElement) return;
  cleanupModalCompat();

  if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
    bootstrap.Modal.getOrCreateInstance(modalElement).show();
    return;
  }

  if (hasJQuery() && typeof window.jQuery.fn.modal === 'function') {
    window.jQuery(modalElement).modal('show');
    return;
  }

  modalElement.style.display = 'block';
  modalElement.classList.add('show');
  modalElement.removeAttribute('aria-hidden');
  modalElement.setAttribute('aria-modal', 'true');
  document.body.classList.add('modal-open');
  document.body.style.overflow = 'hidden';

  modalFallbackBackdrop = document.createElement('div');
  modalFallbackBackdrop.className = 'modal-backdrop fade show';
  modalFallbackBackdrop.addEventListener('click', function() { closeModalCompat(modalElement); });
  document.body.appendChild(modalFallbackBackdrop);
}

function closeModalCompat(modalElement) {
  if (!modalElement) return;

  if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
    bootstrap.Modal.getOrCreateInstance(modalElement).hide();
    setTimeout(function(){ cleanupModalCompat(modalElement); }, 250);
    return;
  }

  if (hasJQuery() && typeof window.jQuery.fn.modal === 'function') {
    window.jQuery(modalElement).modal('hide');
    setTimeout(function(){ cleanupModalCompat(modalElement); }, 250);
    return;
  }

  cleanupModalCompat(modalElement);
}

function maybeShowPromoModal() {
  if (!promoModalElement) return;
  const storageKey = 'wa_chatbot_info_modal_seen';
  if (window.sessionStorage && !sessionStorage.getItem(storageKey)) {
    openModalCompat(promoModalElement);
    sessionStorage.setItem(storageKey, '1');
  }
}

function updateTemplateStatus(inputId) {
  const textarea = document.getElementById(inputId);
  const status = document.getElementById('status_' + inputId);
  if (!textarea || !status) return;

  const value = (textarea.value || '').trim();
  if (value.length) {
    status.innerHTML = '<span class="text-success"><i class="bx bx-check-circle"></i> Template configurado</span>';
  } else {
    status.innerHTML = '<span class="text-secondary"><i class="bx bx-minus-circle"></i> Template vazio</span>';
  }
}

function updateTemplatePreview() {
  const value = (modalTextarea.value || '').trim();
  previewBox.textContent = value.length ? value : 'Digite ou edite o template para ver o conteúdo aqui.';
}

function insertAtCursor(field, text) {
  const start = field.selectionStart || 0;
  const end = field.selectionEnd || 0;
  const original = field.value || '';
  field.value = original.substring(0, start) + text + original.substring(end);
  const newPos = start + text.length;
  field.focus();
  if (typeof field.setSelectionRange === 'function') {
    field.setSelectionRange(newPos, newPos);
  }
  updateTemplatePreview();
}

function openTemplateEditor(button) {
  const inputId = button.getAttribute('data-template-input');
  const label = button.getAttribute('data-template-label') || 'Editar template';
  const description = button.getAttribute('data-template-description') || '';
  const hiddenField = document.getElementById(inputId);

  if (!hiddenField) return;

  activeTemplateInputId = inputId;
  modalTitle.textContent = label;
  modalDescription.textContent = description;
  modalTextarea.value = hiddenField.value || '';
  updateTemplatePreview();
  openModalCompat(templateModalElement);

  setTimeout(function() {
    modalTextarea.focus();
    const len = modalTextarea.value.length;
    if (typeof modalTextarea.setSelectionRange === 'function') {
      modalTextarea.setSelectionRange(len, len);
    }
  }, 150);
}

async function refreshWhatsappStatus() {
  const badge = document.getElementById('waStatusBadge');
  const qr = document.getElementById('qrWrapper');
  const expiry = document.getElementById('waInstanceExpiry');
  if (!badge || !qr) { return { success: true, data: {} }; }

  try {
    const resp = await fetch('api/whatsapp_status.php', {
      headers: { 'Accept': 'application/json' }
    });

    const text = await resp.text();
    let data = null;

    try {
      data = JSON.parse(text);
    } catch (e) {
      console.error('Resposta inválida do status:', text);
      throw new Error('Resposta não é JSON válido.');
    }

    const payload = data.data || {};
    const control = payload.control || {};
    const expiryLabel = control.expires_at_label || payload.expiresAtLabel || 'Sem vencimento';

    if (expiry) {
      expiry.textContent = 'Vencimento: ' + expiryLabel;
    }

    if (payload.connected) {
      badge.className = 'badge bg-success';
      badge.textContent = 'Conectado';
      qr.innerHTML = `
        <div class="text-success text-center">
          <i class="bx bx-check-circle" style="font-size:72px;"></i>
          <div class="mt-2 fw-bold">WhatsApp conectado</div>
          <div class="small text-secondary mt-1">Sua sessão está ativa e pronta para uso.</div>
        </div>
      `;
      return data;
    }

    badge.className = 'badge bg-danger';
    badge.textContent = 'Desconectado';

    if (payload.qrDataUrl) {
      qr.innerHTML = '<img src="' + payload.qrDataUrl + '" alt="QR Code do WhatsApp" class="img-fluid">';
    } else {
      qr.innerHTML = `
        <div class="text-muted text-center">
          <i class="bx bx-qr" style="font-size:56px;opacity:.5;"></i>
          <div class="mt-2">QR ainda não disponível.</div>
          ${data.message ? '<small class="d-block mt-1">' + data.message + '</small>' : ''}
        </div>
      `;
    }

    return data;
  } catch (e) {
    console.error('Erro ao consultar status:', e);
    badge.className = 'badge bg-warning text-dark';
    badge.textContent = 'Erro ao consultar';
    qr.innerHTML = `
      <div class="text-muted text-center">
        <i class="bx bx-error-circle" style="font-size:56px;opacity:.6;"></i>
        <div class="mt-2">Não foi possível carregar o status do WhatsApp.</div>
      </div>
    `;
    return { success: false, message: e && e.message ? e.message : 'Falha ao consultar status.', data: {} };
  }
}

let waRegisterPromise = null;
let waLastRegisterAt = 0;

function shouldAutoRegisterFromStatus(statusData) {
  const payload = (statusData && statusData.data) || {};
  const message = String((statusData && statusData.message) || '').toLowerCase();

  if (payload.connected || payload.qrDataUrl) {
    return false;
  }

  if (!message) {
    return true;
  }

  return [
    'não registrado',
    'nao registrado',
    'não encontrada',
    'nao encontrada',
    'não encontrado',
    'nao encontrado',
    'instance',
    'instância',
    'instancia',
    'qr',
    'painel'
  ].some(function(term) {
    return message.indexOf(term) !== -1;
  });
}

async function registerWhatsappPanel(options = {}) {
  const silent = !!options.silent;
  const cooldownMs = options.cooldownMs || 12000;
  const now = Date.now();

  if ((now - waLastRegisterAt) < cooldownMs) {
    return { success: false, skipped: true, message: 'Aguardando novo ciclo de registro.' };
  }

  if (waRegisterPromise) {
    return waRegisterPromise;
  }

  waLastRegisterAt = now;
  waRegisterPromise = (async function() {
    try {
      const resp = await fetch('api/whatsapp_register.php', {
        method: 'POST',
        headers: { 'Accept': 'application/json' }
      });
      const text = await resp.text();
      let data = {};

      try {
        data = JSON.parse(text);
      } catch (e) {
        data = { success: false, message: text || 'Resposta inválida ao registrar painel.' };
      }

      if (!silent && data.message) {
        alert(data.message);
      }

      return data;
    } catch (e) {
      if (!silent) {
        alert('Falha ao registrar painel no bot.');
      }
      return { success: false, message: 'Falha ao registrar painel no bot.' };
    } finally {
      waRegisterPromise = null;
    }
  })();

  return waRegisterPromise;
}

async function ensureWhatsappPanelRegistered(statusData = null) {
  if (!shouldAutoRegisterFromStatus(statusData)) {
    return { success: false, skipped: true };
  }

  const result = await registerWhatsappPanel({ silent: true });

  if (!result.skipped) {
    setTimeout(function() {
      refreshWhatsappStatus();
    }, 1800);
    setTimeout(function() {
      refreshWhatsappStatus();
    }, 4200);
  }

  return result;
}

document.querySelectorAll('.template-trigger').forEach(function(button) {
  button.addEventListener('click', function() {
    openTemplateEditor(button);
  });
});

document.querySelectorAll('.template-var-btn').forEach(function(button) {
  button.addEventListener('click', function() {
    insertAtCursor(modalTextarea, button.getAttribute('data-var') || '');
  });
});

document.querySelectorAll('[data-dismiss="modal"]').forEach(function(button) {
  button.addEventListener('click', function() {
    closeModalCompat(templateModalElement);
  });
});

document.querySelectorAll('[data-dismiss="promo-modal"]').forEach(function(button) {
  button.addEventListener('click', function() {
    closeModalCompat(promoModalElement);
  });
});

if (templateModalElement) {
  templateModalElement.addEventListener('click', function(e) {
    if (e.target === templateModalElement) {
      closeModalCompat(templateModalElement);
    }
  });
}

if (promoModalElement) {
  promoModalElement.addEventListener('click', function(e) {
    if (e.target === promoModalElement) {
      closeModalCompat(promoModalElement);
    }
  });
}


if (templateModalElement) {
  templateModalElement.addEventListener('hidden.bs.modal', function(){ cleanupModalCompat(templateModalElement); });
}
if (promoModalElement) {
  promoModalElement.addEventListener('hidden.bs.modal', function(){ cleanupModalCompat(promoModalElement); });
}

document.addEventListener('keydown', function(e) {
  if (e.key !== 'Escape') return;

  if (templateModalElement && templateModalElement.classList.contains('show')) {
    closeModalCompat(templateModalElement);
  }

  if (promoModalElement && promoModalElement.classList.contains('show')) {
    closeModalCompat(promoModalElement);
  }
});

if (modalTextarea) modalTextarea.addEventListener('input', updateTemplatePreview);

if (saveTemplateModalBtn) saveTemplateModalBtn.addEventListener('click', function() {
  if (!activeTemplateInputId) return;

  const hiddenField = document.getElementById(activeTemplateInputId);
  if (!hiddenField) return;

  hiddenField.value = modalTextarea.value;
  updateTemplateStatus(activeTemplateInputId);
  closeModalCompat(templateModalElement);
});

const btnDisconnect = document.getElementById('btnDisconnect') || document.getElementById('btnDisconnectWhatsapp');
const btnConnect = document.getElementById('btnConnectWhatsapp') || document.getElementById('btnConnect');
const btnProcessDue = document.getElementById('btnProcessDueWhatsapp') || document.getElementById('btnProcessDue');


if (btnConnect) btnConnect.addEventListener('click', async function() {
  try {
    await fetch('api/whatsapp_connect.php', { method: 'POST', headers: { 'Accept': 'application/json' } });
    setTimeout(async function() {
      const statusData = await refreshWhatsappStatus();
      await ensureWhatsappPanelRegistered(statusData);
    }, 1200);
  } catch (e) {
    alert('Falha ao iniciar a conexão.');
  }
});

if (btnProcessDue) btnProcessDue.addEventListener('click', async function() {
  try {
    await fetch('api/whatsapp_process_due.php', { method: 'POST', headers: { 'Accept': 'application/json' } });
    setTimeout(function(){ refreshWhatsappStatus(); }, 800);
  } catch (e) {
    alert('Falha ao processar agora.');
  }
});

if (btnDisconnect) btnDisconnect.addEventListener('click', async function() {
  try {
    await fetch('api/whatsapp_disconnect.php', { method: 'POST' });
    setTimeout(async function() {
      const statusData = await refreshWhatsappStatus();
      await ensureWhatsappPanelRegistered(statusData);
      setTimeout(function() {
        refreshWhatsappStatus();
      }, 2500);
    }, 1500);
  } catch (e) {
    alert('Falha ao desconectar a sessão.');
  }
});

['tpl_aviso_vencimento', 'tpl_confirmacao_renovacao', 'tpl_cobranca_manual', 'tpl_boas_vindas', 'tpl_teste_criado', 'tpl_teste_expirado', 'tpl_gerar_pix', 'tpl_revenda_criada', 'tpl_revenda_vencida', 'tpl_revenda_renovada', 'tpl_chatbot_menu', 'tpl_chatbot_revenda_menu', 'tpl_chatbot_fallback'].forEach(updateTemplateStatus);

(async function initWhatsappPage() {
  maybeShowPromoModal();
  let statusData = await refreshWhatsappStatus();
  await ensureWhatsappPanelRegistered(statusData);
  setTimeout(function() {
    refreshWhatsappStatus();
  }, 2500);

  setInterval(async function() {
    const currentStatus = await refreshWhatsappStatus();
    await ensureWhatsappPanelRegistered(currentStatus);
  }, 5000);
})();
