/* ==========================================================================
   DUOTALK WEBHOOK SIMULATOR
   Interactive modal to simulate incoming CRM webhooks and events
   ========================================================================== */

const WebhookSimulator = {
  presets: {
    whatsapp_compass: {
      protocol: "DT-2026-99101",
      conversa_id: "CONV-WA-99101",
      customer: {
        name: "Guilherme Siqueira",
        phone: "+55 (11) 98111-4433",
        email: "guilherme.siq@gmail.com",
        location: "São Paulo, SP",
        tags: ["Lead Quente", "Compass 2024", "Troca com Troco"]
      },
      interaction: {
        channel: "WhatsApp",
        origin: "Campanha Meta Ads - Compass 2024",
        intention: "Compra de Veículo 0km",
        target_product: "Jeep Compass Longitude 2024",
        estimated_value_brl: 189900.0,
        messages: [
          { sender: "customer", sender_name: "Guilherme", text: "Boa tarde! Vi a promoção do Compass Longitude com taxa 0%. Ainda tem disponível?", time: "15:30:10" },
          { sender: "agent", sender_name: "Lucas Silva", text: "Boa tarde Guilherme! Sim, temos as últimas 2 unidades com taxa 0% em 24x. Possui seminovo na troca?", time: "15:30:42" },
          { sender: "customer", sender_name: "Guilherme", text: "Tenho um Renegade 2022. Posso ir à concessionária amanhã fazer a avaliação?", time: "15:32:00" },
          { sender: "agent", sender_name: "Lucas Silva", text: "Com certeza Guilherme! Já reservei seu atendimento para amanhã às 14:30 com nosso avaliador.", time: "15:33:15" }
        ]
      },
      operator: {
        id: "OP-01",
        name: "Lucas Silva",
        email: "lucas.silva@duotalk.com.br"
      },
      outcome: {
        qualification: "Quente (Em Negociação)",
        closing_reason: "Em andamento / Proposta enviada",
        closed_by: "Lucas Silva"
      }
    },

    webchat_perda_info: {
      protocol: "DT-2026-99202",
      conversa_id: "CONV-WB-99202",
      customer: {
        name: "Julio Cesar Brandão",
        phone: "+55 (21) 97722-1100",
        email: "julio.brandao@outlook.com",
        location: "Rio de Janeiro, RJ",
        tags: ["Webchat Lead", "Somente Informações"]
      },
      interaction: {
        channel: "Webchat",
        origin: "Portal Web Oficial DuoBI",
        intention: "Dúvidas Gerais",
        target_product: "Toyota Corolla Cross XRE",
        estimated_value_brl: 178500.0,
        messages: [
          { sender: "customer", sender_name: "Julio Cesar", text: "Qual a taxa de financiamento atual para o Corolla Cross?", time: "11:10:00" },
          { sender: "agent", sender_name: "Lucas Silva", text: "Olá Julio! A taxa fica em 1.19% ao mês com 40% de entrada.", time: "11:12:30" },
          { sender: "customer", sender_name: "Julio Cesar", text: "Obrigado, era só para ter uma ideia dos valores.", time: "11:13:00" }
        ]
      },
      operator: {
        id: "OP-01",
        name: "Lucas Silva",
        email: "lucas.silva@duotalk.com.br"
      },
      outcome: {
        qualification: "Desqualificado",
        closing_reason: "Somente informações",
        closed_by: "Lucas Silva"
      }
    },

    conversao_venda: {
      protocol: "DT-2026-99303",
      conversa_id: "CONV-IG-99303",
      customer: {
        name: "Dra. Heloisa Fonseca",
        phone: "+55 (31) 99344-8899",
        email: "heloisa.fonseca@clinica.com.br",
        location: "Belo Horizonte, MG",
        tags: ["Convertido", "Venda Concluída", "BMW 320i"]
      },
      interaction: {
        channel: "Instagram Direct",
        origin: "Instagram Stories - Feirão Seminovos",
        intention: "Compra de Veículo 0km",
        target_product: "BMW 320i M Sport 2023",
        estimated_value_brl: 298000.0,
        messages: [
          { sender: "customer", sender_name: "Dra. Heloisa", text: "Adorei a 320i que postaram no story. Está disponível?", time: "16:00:15" },
          { sender: "agent", sender_name: "Beatriz Santos", text: "Olá Heloisa! Está sim, acabou de chegar no estoque. Laudo cautelar 100% aprovado.", time: "16:01:05" },
          { sender: "customer", sender_name: "Dra. Heloisa", text: "Perfeito, vou fazer o sinal de reserva agora pelo PIX!", time: "16:15:00" },
          { sender: "agent", sender_name: "Beatriz Santos", text: "Sinal recebido com sucesso! Parabéns pela aquisição!", time: "16:20:00" }
        ]
      },
      operator: {
        id: "OP-02",
        name: "Beatriz Santos",
        email: "beatriz.santos@duotalk.com.br"
      },
      outcome: {
        qualification: "Convertido (Venda)",
        closing_reason: "Venda Concluída",
        closed_by: "Beatriz Santos"
      }
    }
  },

  init() {
    this.bindEvents();
  },

  bindEvents() {
    const btnOpen = document.getElementById('btn-open-simulator');
    const modal = document.getElementById('simulator-modal');
    const btnClose = document.getElementById('btn-close-simulator');
    const btnSubmit = document.getElementById('btn-submit-simulator');
    const presetSelect = document.getElementById('simulator-preset-select');

    if (btnOpen) {
      btnOpen.addEventListener('click', () => {
        this.loadPreset('whatsapp_compass');
        if (modal) modal.classList.add('open');
      });
    }

    if (btnClose && modal) {
      btnClose.addEventListener('click', () => modal.classList.remove('open'));
      modal.addEventListener('click', (e) => {
        if (e.target === modal) modal.classList.remove('open');
      });
    }

    if (presetSelect) {
      presetSelect.addEventListener('change', (e) => {
        this.loadPreset(e.target.value);
      });
    }

    if (btnSubmit) {
      btnSubmit.addEventListener('click', () => this.sendPayload());
    }
  },

  loadPreset(key) {
    const data = this.presets[key];
    const textarea = document.getElementById('simulator-payload-editor');
    if (textarea && data) {
      // Gerar protocolo aleatório para cada envio
      const cloned = JSON.parse(JSON.stringify(data));
      cloned.protocol = `DT-2026-${Math.floor(10000 + Math.random() * 90000)}`;
      cloned.conversa_id = `CONV-SIM-${Math.floor(10000 + Math.random() * 90000)}`;
      textarea.value = JSON.stringify(cloned, null, 2);
    }
  },

  async sendPayload() {
    const textarea = document.getElementById('simulator-payload-editor');
    const modal = document.getElementById('simulator-modal');
    const btnSubmit = document.getElementById('btn-submit-simulator');

    if (!textarea) return;

    let payloadObj;
    try {
      payloadObj = JSON.parse(textarea.value);
    } catch (e) {
      showToast('JSON inválido. Verifique a sintaxe antes de enviar.', 'error');
      return;
    }

    try {
      if (btnSubmit) {
        btnSubmit.disabled = true;
        btnSubmit.innerHTML = 'Enviando Webhook...';
      }

      const res = await API.post('/api/conversations/webhook', payloadObj);
      if (res.success) {
        showToast(`Webhook Duotalk processado! Protocolo: ${res.protocol}`, 'success');
        if (modal) modal.classList.remove('open');
        
        // Recarregar aba atual
        window.App.refreshCurrentView();
      }
    } catch (err) {
      showToast(err.message || 'Erro ao enviar webhook.', 'error');
    } finally {
      if (btnSubmit) {
        btnSubmit.disabled = false;
        btnSubmit.innerHTML = 'Disparar Webhook';
      }
    }
  }
};
