// Configuracao do Mautic - Avanzato
// URL: https://mkt.avanzato.com.br

// --- DETECAO DE AMBIENTE ---
// Em homologacao (localhost, IP, ou nao-producao), o Mautic fica em modo simulacao
// Apenas loga no console, nao envia dados reais
const hostname = typeof window !== 'undefined' ? window.location.hostname : '';
const PROD_HOSTS = ['avanzato.com.br'];
export const IS_HOMOLOGATION = !PROD_HOSTS.includes(hostname);

export const MAUTIC_CONFIG = {
  baseUrl: 'https://mkt.avanzato.com.br',

  forms: {
    condominio: { id: '2', enabled: true },
    avaliacaoTI: { id: '3', enabled: true },
    contato: { id: '4', enabled: true },
  },

  // Desativa envio real em homologacao
  enabled: !IS_HOMOLOGATION,
};

/**
 * Envia lead ao Mautic
 * Em homologacao: apenas simula (loga no console), nao envia dados reais
 * Em producao: envia via iframe POST para o Mautic
 */
export const sendLeadToMautic = (
  formType: 'condominio' | 'avaliacaoTI' | 'contato',
  formData: Record<string, string>
): boolean => {
  const formConfig = MAUTIC_CONFIG.forms[formType];

  if (!formConfig?.enabled || !formConfig?.id) {
    console.warn(`[Mautic] Form ${formType} desativado na configuracao.`);
    return false;
  }

  // MODO HOMOLOGACAO: simula envio, nao manda dados reais
  if (IS_HOMOLOGATION) {
    console.log('%c[HOMOLOGACAO] Mautic em modo simulacao - dados NAO enviados ao servidor real', 'background:#f59e0b;color:#000;font-weight:bold;padding:4px 8px;border-radius:4px');
    console.log(`[Mautic] Form: ${formType} | Form ID: ${formConfig.id}`);
    console.log(`[Mautic] Dados que seriam enviados:`, JSON.stringify(formData, null, 2));
    console.log(`[Mautic] Em producao, enviaria para: ${MAUTIC_CONFIG.baseUrl}/form/submit?formId=${formConfig.id}`);
    return true; // Retorna true para o fluxo continuar (simula sucesso)
  }

  // MODO PRODUCAO: envio real via iframe
  try {
    console.log(`[Mautic] Enviando ${formType} para Form ID ${formConfig.id}`);
    console.log(`[Mautic] Dados:`, JSON.stringify(formData, null, 2));

    const container = document.createElement('div');
    container.style.cssText = 'position:absolute;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;';
    document.body.appendChild(container);

    const iframe = document.createElement('iframe');
    iframe.name = `mautic_${Date.now()}`;
    container.appendChild(iframe);

    const form = document.createElement('form');
    form.method = 'POST';
    form.action = `${MAUTIC_CONFIG.baseUrl}/form/submit?formId=${formConfig.id}`;
    form.target = iframe.name;
    form.enctype = 'application/x-www-form-urlencoded';

    const addInput = (name: string, value: string) => {
      const input = document.createElement('input');
      input.type = 'hidden';
      input.name = name;
      input.value = value;
      form.appendChild(input);
    };

    Object.entries(formData).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        addInput(`mauticform[${key}]`, String(value));
      }
    });

    addInput('mauticform[formId]', formConfig.id);
    addInput('mauticform[return]', '');
    addInput('mauticform[formName]', `mauticform_${formConfig.id}`);

    if (formData.nome) addInput('mauticform[firstname]', formData.nome);
    if (formData.email) addInput('mauticform[email]', formData.email);

    container.appendChild(form);
    form.submit();

    console.log(`[Mautic] Formulario submetido! Verifique em: ${MAUTIC_CONFIG.baseUrl}/s/forms/view/${formConfig.id}`);

    setTimeout(() => {
      if (container.parentNode) document.body.removeChild(container);
    }, 5000);

    return true;
  } catch (error) {
    console.error(`[Mautic] Erro:`, error);
    return false;
  }
};

/**
 * Fallback: e-mail
 */
export const sendLeadViaMailto = (formData: Record<string, string>): void => {
  const subject = encodeURIComponent(`[Lead Site] ${formData.nome || 'Sem nome'}`);
  const body = encodeURIComponent(
    `Novo lead do site avanzato.com.br!\n\n` +
    Object.entries(formData)
      .filter(([, v]) => v)
      .map(([k, v]) => `${k}: ${v}`)
      .join('\n') +
    `\n\n---\n${new Date().toLocaleString('pt-BR')}`
  );
  window.open(`mailto:leads@avanzato.com.br?subject=${subject}&body=${body}`, '_blank');
};

/**
 * Tracking Google Ads
 * Desativado em homologacao para nao poluir dados
 */
export const trackConversion = (): void => {
  if (IS_HOMOLOGATION) {
    console.log('%c[HOMOLOGACAO] Google Ads conversion NAO disparado (ambiente de teste)', 'color:#f59e0b');
    return;
  }
  if (typeof window !== 'undefined' && (window as any).gtag) {
    (window as any).gtag('event', 'conversion', {
      send_to: 'AW-16714813566/submit_lead_form',
      value: 1.0,
      currency: 'BRL',
    });
    console.log('[Google Ads] Conversion disparado');
  }
};

/**
 * Tracking Facebook Pixel (Meta)
 * Desativado em homologacao
 */
export const trackFacebookPixel = (eventName: string = 'Lead', params?: Record<string, any>): void => {
  if (IS_HOMOLOGATION) {
    console.log(`%c[HOMOLOGACAO] Facebook Pixel "${eventName}" NAO disparado (ambiente de teste)`, 'color:#f59e0b', params);
    return;
  }
  if (typeof window !== 'undefined' && (window as any).fbq) {
    (window as any).fbq('track', eventName, params || {});
    console.log(`[Facebook Pixel] Evento: ${eventName}`, params);
  }
};
