<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tvi Fone - Zenvia REAL</title>
    <style>
        * { box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        #phoneContainer {
            width: 100%;
            max-width: 380px;
            margin: 0 auto;
            background: white;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            border-radius: 20px;
            overflow: hidden;
        }
        header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            font-weight: bold;
            text-align: center;
            font-size: 1.5em;
        }
        .status-bar {
            background: #f8f9fa;
            padding: 10px;
            text-align: center;
            border-bottom: 1px solid #e9ecef;
        }
        .status-online { color: #27ae60; font-weight: bold; }
        .status-offline { color: #e74c3c; font-weight: bold; }
        .status-calling { color: #f39c12; font-weight: bold; }
        .status-connected { color: #27ae60; font-weight: bold; }
        .content { padding: 25px; text-align: center; }
        .number-display {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 5px;
            margin-bottom: 20px;
            border: 2px solid #e9ecef;
        }
        input[type="text"] {
            width: 100%;
            padding: 15px;
            font-size: 1.6em;
            border: none;
            background: transparent;
            border-radius: 8px;
            margin-bottom: 5px;
            text-align: center;
            font-family: monospace;
            outline: none;
        }
        .contact-info { font-size: 0.85em; color: #7f8c8d; }
        #keyboard {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 12px;
            margin-bottom: 25px;
        }
        #keyboard button {
            padding: 18px 0;
            font-size: 1.5em;
            font-weight: bold;
            border-radius: 12px;
            border: none;
            cursor: pointer;
            background: #f1f3f5;
            color: #2c3e50;
            transition: all 0.2s;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        #keyboard button:hover {
            background: #e9ecef;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        #keyboard button:active { transform: translateY(0); }
        #keyboard button:last-child {
            background: #ff6b6b;
            color: white;
        }
        .actions {
            display: flex;
            flex-direction: column;
            gap: 12px;
            margin-top: 20px;
        }
        .actions button {
            width: 100%;
            padding: 15px;
            font-size: 1.2em;
            font-weight: bold;
            border-radius: 50px;
            border: none;
            cursor: pointer;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
        .callBtn { background: linear-gradient(135deg, #27ae60 0%, #2ecc71 100%); }
        .endBtn { background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%); }
        .actions button:hover { transform: translateY(-2px); }
        .actions button:disabled { opacity: 0.5; cursor: not-allowed; }
        .call-info {
            margin-top: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
            text-align: left;
            border-left: 4px solid #667eea;
        }
        .error-message {
            color: #e74c3c;
            font-size: 0.9em;
            margin-top: 10px;
            padding: 10px;
            background: #fde8e8;
            border-radius: 8px;
            display: none;
        }
        .error-message.show { display: block; }
        .call-timer {
            font-family: monospace;
            font-size: 1.2em;
            color: #667eea;
            font-weight: bold;
        }
        #debugPanel {
            margin-top: 20px;
            padding: 10px;
            background: #1e1e1e;
            border-radius: 8px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            text-align: left;
            max-height: 300px;
            overflow-y: auto;
            color: #00ff00;
            border: 1px solid #333;
        }
        .debug-line {
            border-bottom: 1px solid #333;
            padding: 3px 0;
            color: #00ff00;
            white-space: pre-wrap;
            word-break: break-all;
        }
        .debug-error { color: #ff6b6b; }
        .debug-success { color: #5cb85c; }
        .debug-warning { color: #f0ad4e; }
        .register-btn {
            margin-bottom: 10px;
            padding: 10px;
            background: #3498db;
            color: white;
            border: none;
            border-radius: 5px;
            width: 100%;
            cursor: pointer;
            font-weight: bold;
        }
        .register-btn:hover { background: #2980b9; }
        .balance-btn {
            margin-bottom: 10px;
            padding: 10px;
            background: #f39c12;
            color: white;
            border: none;
            border-radius: 5px;
            width: 100%;
            cursor: pointer;
            font-weight: bold;
        }
        .balance-btn:hover { background: #e67e22; }
    </style>
    
    <!-- SIP.js versão 0.15.2 - Última versão com suporte global confirmado -->
<script src="https://npmcdn.com/jssip@3.10.1/dist/jssip.min.js"></script>
<script>
    // Verificação silenciosa
    setTimeout(function() {
        if (typeof SIP === 'undefined') {
            console.error('❌ SIP.js não carregou');
            if (window.debugLog) window.debugLog('❌ SIP.js não carregou. Tente recarregar.', 'error');
        } else {
            console.log('✅ SIP.js carregado:', SIP.version);
            if (window.debugLog) window.debugLog('✅ SIP.js carregado com sucesso', 'success');
        }
    }, 2000);
</script>
</head>
<body>
    <div id="phoneContainer">
        <header>📞 Tvi Fone - Zenvia REAL</header>
        
        <div class="status-bar" id="statusBar">
            <span id="statusText">Inicializando...</span>
            <span id="callTimer" class="call-timer" style="display: none;"></span>
        </div>

        <div class="content">
            <div class="number-display">
                <input type="text" id="inputNumber" placeholder="Digite o número..." 
                       value="" inputmode="numeric" autocomplete="off">
                <div class="contact-info" id="contactInfo"></div>
            </div>

            <div id="keyboard">
                <button onclick="addToInput('1')">1</button>
                <button onclick="addToInput('2')">2</button>
                <button onclick="addToInput('3')">3</button>
                <button onclick="addToInput('4')">4</button>
                <button onclick="addToInput('5')">5</button>
                <button onclick="addToInput('6')">6</button>
                <button onclick="addToInput('7')">7</button>
                <button onclick="addToInput('8')">8</button>
                <button onclick="addToInput('9')">9</button>
                <button onclick="addToInput('*')">*</button>
                <button onclick="addToInput('0')">0</button>
                <button onclick="clearInput()">⌫</button>
            </div>
            
            <div style="display: flex; gap: 10px; margin-bottom: 10px;">
                <button onclick="clearDebug()" style="flex:1; padding:5px; background:#333; color:white; border:none; border-radius:5px;">
                    🧹 Limpar Debug
                </button>
                <button onclick="checkBalance()" class="balance-btn" style="flex:1;">
                    💰 Ver Saldo
                </button>
            </div>

            <button onclick="initializeWebphone()" class="register-btn">
                🔄 Inicializar Webfone
            </button>

            <div id="debugPanel">
                <div class="debug-line">=== Painel de Debug Zenvia REAL ===</div>
                <div class="debug-line">API: /api/zenvia</div>
                <div class="debug-line">Status: Aguardando...</div>
            </div>

            <div class="actions">
                <button class="callBtn" onclick="startCall()" id="callBtn" disabled>📞 Ligar</button>
                <button class="endBtn" onclick="endCall()" id="endBtn" disabled>🔴 Finalizar Chamada</button>
            </div>

            <div class="call-info" id="callInfo" style="display: none;">
                <div id="callStatus"></div>
                <div id="callDuration"></div>
            </div>

            <div class="error-message" id="errorMessage"></div>
        </div>
    </div>

    <script>
        // =============================================
        // CONFIGURAÇÕES ZENVIA
        // =============================================
        const CONFIG = {
            API_URL: '/api/zenvia',
            IDENTITY: 'webuser_' + Math.random().toString(36).substr(2, 9),
            SIP_DOMAIN: 'sip.zenvia.com',
            WS_SERVER: 'wss://sip.zenvia.com:8089/ws'
        };

        let accessToken = null;
        let currentCall = null;
        let connectionStatus = 'offline';
        let callStartTime = null;
        let timerInterval = null;
        let callCheckInterval = null;
        let userAgent = null;
        let sipSession = null;

        const elements = {
            inputNumber: document.getElementById('inputNumber'),
            statusText: document.getElementById('statusText'),
            callBtn: document.getElementById('callBtn'),
            endBtn: document.getElementById('endBtn'),
            callInfo: document.getElementById('callInfo'),
            callStatus: document.getElementById('callStatus'),
            callTimer: document.getElementById('callTimer'),
            errorMessage: document.getElementById('errorMessage'),
            contactInfo: document.getElementById('contactInfo'),
            debugPanel: document.getElementById('debugPanel')
        };

        // Expor debugLog globalmente para a verificação do SIP.js
        window.debugLog = function(message, type) {
            const panel = elements.debugPanel;
            const line = document.createElement('div');
            line.className = `debug-line debug-${type}`;
            line.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
            panel.appendChild(line);
            panel.scrollTop = panel.scrollHeight;
        };

        function debugLog(message, type = 'info') {
            window.debugLog(message, type);
        }

        function formatPhoneNumber(number) {
            if (!number) return '';
            const cleaned = number.replace(/\D/g, '');
            if (cleaned.length === 11) {
                return cleaned.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3');
            } else if (cleaned.length === 10) {
                return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3');
            }
            return number;
        }

        function updateContactInfo() {
            const number = elements.inputNumber.value;
            elements.contactInfo.textContent = number ? formatPhoneNumber(number) : 'Digite um número';
        }

        function showError(message, isWarning = false) {
            elements.errorMessage.textContent = message;
            elements.errorMessage.style.backgroundColor = isWarning ? '#fff3cd' : '#fde8e8';
            elements.errorMessage.style.color = isWarning ? '#856404' : '#e74c3c';
            elements.errorMessage.classList.add('show');
            setTimeout(() => elements.errorMessage.classList.remove('show'), 5000);
            debugLog(`⚠️ ${message}`, isWarning ? 'warning' : 'error');
        }

        function updateStatus(status, message) {
            connectionStatus = status;
            const statusMap = {
                'online': { class: 'status-online', text: '🟢 Online', btnEnabled: true },
                'offline': { class: 'status-offline', text: '🔴 Offline', btnEnabled: false },
                'calling': { class: 'status-calling', text: '🟠 Chamando...', btnEnabled: false },
                'connected': { class: 'status-connected', text: '🟢 Em Chamada', btnEnabled: false }
            };
            const statusConfig = statusMap[status] || statusMap.offline;
            elements.statusText.className = statusConfig.class;
            elements.statusText.innerHTML = message || statusConfig.text;
            elements.callBtn.disabled = !statusConfig.btnEnabled;
            elements.endBtn.disabled = status !== 'connected';
            debugLog(`Status: ${status} - ${message || statusConfig.text}`);
        }

        function startTimer() {
            callStartTime = new Date();
            timerInterval = setInterval(() => {
                if (!callStartTime) return;
                const diff = Math.floor((new Date() - callStartTime) / 1000);
                const minutes = Math.floor(diff / 60);
                const seconds = diff % 60;
                elements.callTimer.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            }, 1000);
            elements.callTimer.style.display = 'inline';
        }

        function stopTimer() {
            if (timerInterval) clearInterval(timerInterval);
            timerInterval = null;
            callStartTime = null;
            elements.callTimer.style.display = 'none';
            elements.callTimer.textContent = '';
        }

        // =============================================
        // FUNÇÕES DA API ZENVIA
        // =============================================
        async function fetchToken() {
            debugLog(`🔑 Buscando token para: ${CONFIG.IDENTITY}`);
            try {
                const response = await fetch(`${CONFIG.API_URL}/token?identity=${encodeURIComponent(CONFIG.IDENTITY)}`);
                const data = await response.json();
                
                if (data.success) {
                    debugLog(`✅ Token obtido: ${data.token.substring(0, 20)}...`, 'success');
                    accessToken = data.token;
                    return data;
                } else {
                    throw new Error('Falha ao obter token');
                }
            } catch (error) {
                debugLog(`❌ Erro ao buscar token: ${error.message}`, 'error');
                throw error;
            }
        }

        async function checkBalance() {
            debugLog('💰 Verificando saldo...');
            try {
                const response = await fetch(`${CONFIG.API_URL}/balance`);
                const data = await response.json();
                
                if (data.success) {
                    const saldo = data.balance.saldo;
                    debugLog(`✅ Saldo disponível: R$ ${saldo.toFixed(2)}`, 'success');
                    showError(`Saldo: R$ ${saldo.toFixed(2)}`, true);
                    return saldo;
                } else {
                    throw new Error('Falha ao verificar saldo');
                }
            } catch (error) {
                debugLog(`❌ Erro ao verificar saldo: ${error.message}`, 'error');
                showError('Erro ao verificar saldo');
            }
        }

        // =============================================
        // FUNÇÕES WEBRTC REAIS COM SIP.JS
        // =============================================
        async function initializeWebRTC() {
            debugLog('📱 Inicializando WebRTC real com SIP.js...');
            
            try {
                // Verificar se SIP está definido
                if (typeof SIP === 'undefined') {
                    throw new Error('SIP.js não carregou. Verifique sua conexão.');
                }
                
                debugLog('✅ SIP.js carregado com sucesso!');
                
                // Configurar User Agent SIP
                const uri = SIP.UserAgent.makeURI(`sip:${CONFIG.IDENTITY}@${CONFIG.SIP_DOMAIN}`);
                
                userAgent = new SIP.UserAgent({
                    uri: uri,
                    transportOptions: {
                        wsServers: CONFIG.WS_SERVER,
                        traceSip: true
                    },
                    authorizationPassword: accessToken,
                    authorizationUsername: CONFIG.IDENTITY
                });
                
                // Eventos do User Agent
                userAgent.delegate = {
                    onConnect: () => {
                        debugLog('✅ Conectado ao servidor SIP!', 'success');
                        updateStatus('online');
                    },
                    onDisconnect: (error) => {
                        debugLog('🔴 Desconectado do servidor SIP', 'error');
                        updateStatus('offline');
                    },
                    onInvite: (invitation) => {
                        debugLog('📞 Chamada recebida!', 'success');
                        handleIncomingCall(invitation);
                    }
                };
                
                // Conectar
                await userAgent.start();
                debugLog('✅ User Agent SIP iniciado');
                
            } catch (error) {
                debugLog(`❌ Erro ao inicializar WebRTC: ${error.message}`, 'error');
                throw error;
            }
        }

        async function startCall() {
            let number = elements.inputNumber.value.trim();
            
            if (!number) {
                showError('Digite um número para ligar', true);
                return;
            }

            // Formatar número
            if (!number.startsWith('+')) {
                if (number.length === 10 || number.length === 11) {
                    number = '+55' + number.replace(/\D/g, '');
                } else {
                    number = '+' + number.replace(/\D/g, '');
                }
            }
            
            debugLog(`📞 Iniciando chamada REAL para: ${number}`);
            updateStatus('calling', '🟠 Chamando...');

            try {
                // 1. Iniciar chamada via API (para registrar na Zenvia)
                const response = await fetch(`${CONFIG.API_URL}/call`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        to: number,
                        caller: CONFIG.IDENTITY
                    })
                });

                const data = await response.json();
                
                if (data.success) {
                    debugLog(`✅ Chamada registrada com ID: ${data.callId}`, 'success');
                    
                    // 2. Fazer chamada via SIP
                    if (userAgent) {
                        const targetUri = SIP.UserAgent.makeURI(`sip:${number}@${CONFIG.SIP_DOMAIN}`);
                        const inviter = new SIP.Inviter(userAgent, targetUri);
                        
                        inviter.delegate = {
                            onSessionAccept: () => {
                                debugLog('✅ Chamada aceita!', 'success');
                                sipSession = inviter;
                                updateStatus('connected', '🟢 Em Chamada');
                                startTimer();
                                elements.callStatus.textContent = `Em chamada com ${number}`;
                            },
                            onSessionTerminate: () => {
                                debugLog('🔴 Chamada encerrada');
                                endCall();
                            }
                        };
                        
                        await inviter.invite();
                        currentCall = { id: data.callId, session: inviter };
                        elements.callInfo.style.display = 'block';
                        elements.callStatus.textContent = `Chamando ${number}...`;
                        startTimer();
                    }
                    
                    // Verificar status da chamada periodicamente
                    callCheckInterval = setInterval(() => checkCallStatus(data.callId), 5000);
                    
                } else {
                    throw new Error(data.error || 'Falha ao iniciar chamada');
                }
            } catch (error) {
                debugLog(`❌ Erro ao ligar: ${error.message}`, 'error');
                updateStatus('online');
                showError(`Erro: ${error.message}`);
            }
        }

        async function checkCallStatus(callId) {
            if (!callId) return;
            
            try {
                const response = await fetch(`${CONFIG.API_URL}/call/${callId}`);
                const data = await response.json();
                
                if (data.success) {
                    debugLog(`📊 Status da chamada ${callId}: ${data.call.status || 'desconhecido'}`);
                    
                    if (data.call.status === 'finalizada' || data.call.status === 'encerrada') {
                        endCall();
                    }
                }
            } catch (error) {
                debugLog(`⚠️ Erro ao verificar status: ${error.message}`, 'warning');
            }
        }

        function handleIncomingCall(invitation) {
            debugLog('📞 Chamada recebida!');
            
            // Aceitar automaticamente (pode mudar para confirmação)
            invitation.accept();
            sipSession = invitation;
            currentCall = { session: invitation };
            updateStatus('connected', '🟢 Em Chamada');
            startTimer();
            elements.callInfo.style.display = 'block';
            elements.callStatus.textContent = 'Chamada em andamento';
        }

        function endCall() {
            debugLog('🔴 Finalizando chamada...');
            
            if (callCheckInterval) {
                clearInterval(callCheckInterval);
                callCheckInterval = null;
            }
            
            if (sipSession) {
                sipSession.terminate();
                sipSession = null;
            }
            
            stopTimer();
            currentCall = null;
            updateStatus('online');
            elements.callInfo.style.display = 'none';
            showError('Chamada finalizada', true);
        }

        // =============================================
        // FUNÇÕES DE INTERFACE
        // =============================================
        function addToInput(value) {
            elements.inputNumber.value += value;
            updateContactInfo();
        }

        function clearInput() {
            elements.inputNumber.value = elements.inputNumber.value.slice(0, -1);
            updateContactInfo();
        }

        function clearDebug() {
            elements.debugPanel.innerHTML = '<div class="debug-line">=== Painel de Debug Limpo ===</div>';
        }

        async function initializeWebphone() {
            debugLog('🚀 Inicializando webfone Zenvia REAL...');
            
            try {
                await fetchToken();
                const saldo = await checkBalance();
                
                if (saldo > 0) {
                    await initializeWebRTC();
                    debugLog('✅ Webfone pronto para chamadas REAIS!', 'success');
                } else {
                    debugLog('❌ Saldo insuficiente', 'error');
                    updateStatus('offline');
                }
            } catch (error) {
                debugLog(`❌ Falha na inicialização: ${error.message}`, 'error');
                updateStatus('offline');
            }
        }

        // =============================================
        // EVENT LISTENERS E INICIALIZAÇÃO
        // =============================================
        elements.inputNumber.addEventListener('input', updateContactInfo);
        elements.inputNumber.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') startCall();
        });

        elements.inputNumber.addEventListener('keydown', (e) => {
            const validKeys = ['0','1','2','3','4','5','6','7','8','9','*','#','+','-','(',')','Backspace','Delete','ArrowLeft','ArrowRight','Tab'];
            if (!validKeys.includes(e.key) && !e.ctrlKey && !e.metaKey) e.preventDefault();
        });

        // Inicialização automática
        window.onload = () => {
            debugLog('=== WEBFONE ZENVIA REAL INICIADO ===');
            debugLog(`API: ${CONFIG.API_URL}`);
            debugLog(`Identity: ${CONFIG.IDENTITY}`);
            
            // Pequeno atraso para garantir que o SIP.js carregou
            setTimeout(() => {
                initializeWebphone();
            }, 500);
        };
    </script>
</body>
</html>