.elementor-kit-7{--e-global-color-primary:#406777;--e-global-color-secondary:#54595F;--e-global-color-text:#7A7A7A;--e-global-color-accent:#61CE70;--e-global-color-1eeaafa:#80d08d;--e-global-color-a8cc910:#243564;--e-global-color-73fb328:#011640;--e-global-color-b8bef56:#3C4C5A;--e-global-color-e46cc1a:#1B252F;--e-global-typography-primary-font-family:"Montserrat";--e-global-typography-primary-font-weight:800;--e-global-typography-secondary-font-family:"Montserrat";--e-global-typography-secondary-font-weight:600;--e-global-typography-text-font-family:"Montserrat";--e-global-typography-text-font-weight:400;--e-global-typography-accent-font-family:"Montserrat";--e-global-typography-accent-font-weight:500;}.elementor-kit-7 e-page-transition{background-color:#FFBC7D;}.elementor-section.elementor-section-boxed > .elementor-container{max-width:1140px;}.e-con{--container-max-width:1140px;}.elementor-widget:not(:last-child){margin-block-end:20px;}.elementor-element{--widgets-spacing:20px 20px;--widgets-spacing-row:20px;--widgets-spacing-column:20px;}{}h1.entry-title{display:var(--page-title-display);}@media(max-width:1024px){.elementor-section.elementor-section-boxed > .elementor-container{max-width:1024px;}.e-con{--container-max-width:1024px;}}@media(max-width:767px){.elementor-section.elementor-section-boxed > .elementor-container{max-width:767px;}.e-con{--container-max-width:767px;}}/* Start custom CSS */// Widget de Chat ZPRO
(function() {
    // Cria o elemento do widget
    const widgetHTML = `
    <div id="zpro-chat-widget">
        <button id="zpro-chat-button">
            <img src="https://comunidadezdg.com.br/wp-content/uploads/2025/05/webchat-logo.png" alt="WebChat Logo">
        </button>
    </div>

    <div id="zpro-chat-container">
        <div id="zpro-chat-header">
            <h3>WEBChat</h3>
            <span id="zpro-chat-session" style="font-size:11px;color:#e3f2fd;margin-left:8px;"></span>
            <div style="display: flex; gap: 8px;">
                <button id="zpro-chat-clear" style="background: none; border: none; color: white; cursor: pointer; font-size: 14px;">🔄</button>
                <button id="zpro-chat-close">×</button>
            </div>
        </div>
        <div id="zpro-chat-messages"></div>
        <div id="zpro-chat-input-area">
            <input type="text" id="zpro-chat-input" placeholder="Digite sua mensagem...">
            <button id="zpro-chat-send">Enviar</button>
        </div>
    </div>

    <style>
        #zpro-chat-widget {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 9999;
        }

        #zpro-chat-button {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: #2196F3;
            border: none;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: transform 0.3s;
        }

        #zpro-chat-button:hover {
            transform: scale(1.1);
        }

        #zpro-chat-button img {
            width: 30px;
            height: 30px;
        }

        #zpro-chat-container {
            display: none;
            position: fixed;
            bottom: 90px;
            right: 20px;
            width: 320px;
            height: 500px;
            background: #fff;
            border-radius: 16px;
            box-shadow: 0 4px 24px rgba(0,0,0,0.08);
            flex-direction: column;
            transition: all 0.3s;
            z-index: 9998;
        }

        #zpro-chat-container.show {
            display: flex;
        }

        #zpro-chat-widget.hide {
            display: none;
        }

        #zpro-chat-header {
            background: #2196F3;
            color: white;
            padding: 12px 16px;
            border-radius: 16px 16px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        #zpro-chat-header h3 {
            margin: 0;
            font-size: 16px;
        }

        #zpro-chat-close {
            background: none;
            border: none;
            color: white;
            cursor: pointer;
            font-size: 20px;
        }

        #zpro-chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 16px;
            background: #f7fafd;
        }

        #zpro-chat-input-area {
            display: flex;
            padding: 12px;
            background: #f7fafd;
            border-top: 1px solid #e0e0e0;
        }

        #zpro-chat-input {
            flex: 1;
            padding: 8px;
            border: 1px solid #cfd8dc;
            border-radius: 8px;
            font-size: 14px;
            outline: none;
            margin-right: 8px;
        }

        #zpro-chat-send {
            padding: 0 16px;
            background: #2196F3;
            color: #fff;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            cursor: pointer;
        }

        .zpro-message {
            max-width: 75%;
            margin-bottom: 8px;
            padding: 8px 12px;
            border-radius: 16px;
            word-break: break-word;
            font-size: 14px;
        }

        .zpro-sent {
            background: #d1eaff;
            margin-left: auto;
            border-bottom-right-radius: 4px;
        }

        .zpro-received {
            background: #fff;
            margin-right: auto;
            border-bottom-left-radius: 4px;
            border: 1px solid #e3f2fd;
            box-shadow: 0 1px 2px rgba(33,150,243,0.06);
        }

        .zpro-ack {
            font-size: 10px;
            color: #888;
            margin-left: 8px;
        }

        @media (max-width: 480px) {
            #zpro-chat-container {
                width: 100%;
                height: 100vh;
                bottom: 0;
                right: 0;
                border-radius: 0;
            }
            #zpro-chat-widget {
                right: 20px;
                bottom: 20px;
            }
        }
    </style>
    `;

    // Adiciona o widget ao documento
    document.body.insertAdjacentHTML('beforeend', widgetHTML);

    // Inicializa o widget
    const chatButton = document.getElementById('zpro-chat-button');
    const chatContainer = document.getElementById('zpro-chat-container');
    const chatClose = document.getElementById('zpro-chat-close');
    const chatClear = document.getElementById('zpro-chat-clear');
    const messagesDiv = document.getElementById('zpro-chat-messages');
    const messageInput = document.getElementById('zpro-chat-input');
    const sendButton = document.getElementById('zpro-chat-send');
    const sessionSpan = document.getElementById('zpro-chat-session');
    const widgetDiv = document.getElementById('zpro-chat-widget');

    // Variáveis globais para sessão e token
    let webchatId = null;
    let token = null;
    let ws = null;
    let chatLoaded = false;

    // Funções de controle do widget
    chatButton.addEventListener('click', async () => {
        chatContainer.classList.add('show');
        if (!chatLoaded) {
            await loadMessageHistory();
            connectWebSocket();
            chatLoaded = true;
        }
    });

    chatClose.addEventListener('click', () => {
        chatContainer.classList.remove('show');
    });

    // Função para gerar ID único de sessão
    function generateUniqueId() {
        const timestamp = Date.now().toString(36);
        const random = Math.random().toString(36).substring(2, 8);
        return `${timestamp}-${random}`;
    }
    function generateSessionId() {
        if (!sessionStorage.getItem('zproWebchatId')) {
            sessionStorage.setItem('zproWebchatId', generateUniqueId());
        }
        return sessionStorage.getItem('zproWebchatId');
    }

    // Função para registrar o usuário no backend
    async function registerWebchat() {
        webchatId = generateSessionId();
        const name = 'WebChat ' + webchatId;
        const email = 'webchat@webchat.com';
        const tenantId = '1';
        const wabaId = '86d10511-a8e2-4117-88d8-e82d7254a0b7';
        const websocketToken = 'bea91098-89e7-4208-931e-47a0f03c0dca';
        console.log('[WebChat] Registrando sessão:', { webchatId, name, email, tenantId, wabaId });
        const response = await fetch(`https://crmapi.zapmestre.com/webchat/register/${wabaId}`, {
            method: 'POST',
            headers: { 
                'Content-Type': 'application/json',
                'x-websocket-token': websocketToken
            },
            body: JSON.stringify({ webchatId, name, email, tenantId })
        });
        const data = await response.json();
        token = data.token;
        console.log('[WebChat] Sessão registrada:', { webchatId, token });
        return { webchatId, token };
    }

    // Exibe o ID da sessão
    async function showSessionId() {
        const { webchatId } = await registerWebchat();
        sessionSpan.textContent = `Sessão: ${webchatId}`;
    }
    showSessionId();

    // Função para formatar hora
    function formatTime(dateString) {
        const date = new Date(dateString);
        return date.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
    }

    // Função para formatar texto estilo WhatsApp
    function formatWhatsapp(text) {
        return text.replace(/\*(.*?)\*/g, '<b>$1</b>');
    }

    // Função para adicionar mensagem
    function appendMessage(text, type, time = '', ack = null, id = null) {
        const messageDiv = document.createElement('div');
        if (id) messageDiv.id = 'msg-' + id;
        messageDiv.className = `zpro-message ${type}`;
        let ackHtml = '';
        if (type === 'zpro-sent' && ack !== null && ack !== undefined) {
            ackHtml = `<span class="zpro-ack">${getAckIcon(ack)}</span>`;
        }
        messageDiv.innerHTML = `<span>${formatWhatsapp(text)}</span><br><span style="font-size:10px;color:#888;">${time} ${ackHtml}</span>`;
        messagesDiv.appendChild(messageDiv);
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
    }

    // Função para atualizar o ack de uma mensagem
    function updateMessageAck(messageId, ack) {
        const msgDiv = document.getElementById('msg-' + messageId);
        if (msgDiv) {
            const ackSpan = msgDiv.querySelector('.zpro-ack');
            if (ackSpan) {
                ackSpan.innerHTML = getAckIcon(ack);
            }
        }
    }

    // Função para obter ícone do ack
    function getAckIcon(ack) {
        if (ack === 0) return '🕓';
        if (ack === 1) return '✔️';
        if (ack === 2) return '<span style="color:#9E9E9E;">✔️</span>';
        if (ack === 3) return '<span style="color:#2196F3;">✔️✔️</span>';
        if (ack === -1) return '❌';
        return '';
    }

    // Função para renderizar o histórico completo
    function renderHistory(messages) {
        messagesDiv.innerHTML = '';
        messages.forEach(msg => {
            appendMessage(
                msg.body,
                msg.fromMe ? 'zpro-received' : 'zpro-sent',
                formatTime(msg.createdAt),
                msg.ack,
                msg.id
            );
        });
    }

    // Função para carregar histórico de mensagens
    async function loadMessageHistory() {
        try {
            const wabaId = '86d10511-a8e2-4117-88d8-e82d7254a0b7';
            const websocketToken = 'bea91098-89e7-4208-931e-47a0f03c0dca';
            const response = await fetch(`https://crmapi.zapmestre.com/webchat/messages/${wabaId}?from=${webchatId}&tenantId=1`, {
                headers: {
                    'x-websocket-token': websocketToken
                }
            });
            const data = await response.json();
            console.log('[WebChat] Histórico carregado:', data);
            if (Array.isArray(data)) {
                renderHistory(data);
            } else {
                console.warn('[WebChat] Resposta da API não é um array:', data);
            }
        } catch (error) {
            console.error('[WebChat] Erro ao carregar histórico:', error);
        }
    }

    // Função para gerar um ID temporário para mensagens enviadas
    function generateTempId() {
        return 'temp-' + Math.random().toString(36).substr(2, 9);
    }

    // Função para atualizar o ID de uma mensagem no DOM
    function updateMessageId(tempId, realId) {
        const tempDiv = document.getElementById('msg-' + tempId);
        if (tempDiv) {
            tempDiv.id = 'msg-' + realId;
        }
    }

    // Event listeners para envio de mensagem
    sendButton.addEventListener('click', async () => {
        const message = messageInput.value.trim();
        if (message) {
            const tempId = generateTempId();
            appendMessage(message, 'zpro-sent', formatTime(new Date().toISOString()), 0, tempId);
            messageInput.value = '';
            const data = {
                body: message,
                from: webchatId,
                name: webchatId,
                email: webchatId + '@webchat.com',
                tenantId: '1',
                event: 'messages.upsert',
                fromMe: false,
                channel: 'webchat',
                type: 'webchat',
                webchatId: webchatId
            };
            console.log('[WebChat] Enviando mensagem:', data);
            try {
                const wabaId = '86d10511-a8e2-4117-88d8-e82d7254a0b7';
                const websocketToken = 'bea91098-89e7-4208-931e-47a0f03c0dca';
                const response = await fetch(`https://crmapi.zapmestre.com/webchat-webhook/${wabaId}`, {
                    method: 'POST',
                    headers: { 
                        'Content-Type': 'application/json',
                        'x-websocket-token': websocketToken
                    },
                    body: JSON.stringify(data)
                });
                const respData = await response.json();
                console.log('[WebChat] Resposta do backend:', respData);
                if (respData && respData.id) {
                    updateMessageId(tempId, respData.id);
                }
            } catch (error) {
                console.error('[WebChat] Erro ao enviar mensagem:', error);
            }
        }
    });

    messageInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            sendButton.click();
        }
    });

    // WebSocket para receber mensagens e ack em tempo real
    function connectWebSocket() {
        if (!webchatId || !token) return;
        
        let pingInterval;
        let historyInterval;
        let reconnectAttempts = 0;
        const MAX_RECONNECT_ATTEMPTS = 5;
        const RECONNECT_DELAY = 5000;
        const PING_INTERVAL = 30000;
        const HISTORY_INTERVAL = 60000;

        function connect() {
            const wabaId = '86d10511-a8e2-4117-88d8-e82d7254a0b7';
            const websocketToken = 'bea91098-89e7-4208-931e-47a0f03c0dca';
            ws = new WebSocket(`wss://webchat.zapmestre.com/wss?from=${webchatId}&token=${token}`);
            
            ws.onopen = () => {
                console.log('[WebChat] WebSocket conectado!');
                reconnectAttempts = 0;
                
                pingInterval = setInterval(() => {
                    if (ws.readyState === WebSocket.OPEN) {
                        ws.send(JSON.stringify({ type: 'ping' }));
                    }
                }, PING_INTERVAL);

                historyInterval = setInterval(async () => {
                    if (ws.readyState === WebSocket.OPEN) {
                        console.log('[WebChat] Buscando histórico periodicamente...');
                        await loadMessageHistory();
                    }
                }, HISTORY_INTERVAL);
            };

            ws.onmessage = (event) => {
                try {
                    const data = JSON.parse(event.data);
                    console.log('[WebChat] Evento recebido do backend:', data);
                    if (data.type === 'webhook' && data.payload && data.payload.message) {
                        const msg = data.payload.message;
                        appendMessage(
                            msg.body,
                            'zpro-received',
                            formatTime(msg.createdAt),
                            msg.ack,
                            msg.id
                        );
                    }
                    if (data.type === 'ack_update' && data.payload) {
                        updateMessageAck(data.payload.messageId, data.payload.ack);
                    }
                    if (data.type === 'pong') {
                        console.log('[WebChat] Pong recebido');
                    }
                } catch (error) {
                    console.error('[WebChat] Erro ao processar mensagem WebSocket:', error);
                }
            };

            ws.onerror = (error) => {
                console.error('[WebChat] Erro na conexão WebSocket:', error);
            };

            ws.onclose = () => {
                console.log('[WebChat] Conexão WebSocket fechada');
                clearInterval(pingInterval);
                clearInterval(historyInterval);
                
                if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
                    reconnectAttempts++;
                    console.log(`[WebChat] Tentando reconectar (tentativa ${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})...`);
                    setTimeout(connect, RECONNECT_DELAY);
                } else {
                    console.error('[WebChat] Número máximo de tentativas de reconexão atingido');
                }
            };
        }

        connect();
    }

    // Função para limpar a sessão
    async function clearSession() {
        if (confirm('Tem certeza que deseja limpar a sessão e começar uma nova conversa?')) {
            messagesDiv.innerHTML = '';
            sessionStorage.removeItem('zproWebchatId');
            if (ws) {
                ws.close();
            }
            webchatId = null;
            token = null;
            chatLoaded = false;
            await showSessionId();
            await loadMessageHistory();
            connectWebSocket();
        }
    }

    chatClear.addEventListener('click', clearSession);
})();/* End custom CSS */