<?php
// ==================== CONFIGURAÇÃO ====================
define('EVOLUTION_API_URL', 'https://api.controlmaxerp.com.br');
define('DEBUG_MODE', true);

// Headers CORS para evitar problemas
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, apikey');
header('Access-Control-Max-Age: 86400');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// ==================== FUNÇÕES ====================
function logDebug($message, $data = null) {
    if (DEBUG_MODE) {
        $logMessage = date('Y-m-d H:i:s') . ' - ' . $message;
        if ($data) {
            $logMessage .= " - " . json_encode($data, JSON_UNESCAPED_UNICODE);
        }
        error_log($logMessage);
        
        // Também log em arquivo para debug mais fácil
        file_put_contents('whatsapp_debug.log', $logMessage . PHP_EOL, FILE_APPEND | LOCK_EX);
    }
}

function getApiKeyForInstance($instanceName) {
    // A API Key é o mesmo nome da instância (conforme seu exemplo)
    return $instanceName;
}

function makeEvolutionRequest($endpoint, $method = 'GET', $data = null, $instanceName = '') {
    $url = EVOLUTION_API_URL . $endpoint;
    $apiKey = getApiKeyForInstance($instanceName);
    
    logDebug("🔄 Evolution API Request", [
        'endpoint' => $endpoint,
        'method' => $method,
        'url' => $url,
        'instance' => $instanceName,
        'api_key' => $apiKey,
        'data' => $data
    ]);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'apikey: ' . $apiKey
    ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if ($data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
    } elseif ($method === 'DELETE') {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
    }
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);
    
    $responseData = json_decode($response, true) ?? $response;
    
    logDebug("📥 Evolution API Response", [
        'http_code' => $httpCode,
        'curl_error' => $curlError,
        'response' => $responseData
    ]);
    
    return [
        'success' => $httpCode >= 200 && $httpCode < 300,
        'data' => $responseData,
        'httpCode' => $httpCode,
        'rawResponse' => $response,
        'curlError' => $curlError
    ];
}

// ==================== API HANDLER ====================
if (isset($_GET['api'])) {
    header('Content-Type: application/json; charset=utf-8');
    
    $action = $_GET['action'] ?? '';
    $instanceName = $_GET['instance'] ?? 'w7mastersoftware'; // Instância padrão
    
    logDebug("🎯 Nova Requisição API", [
        'action' => $action,
        'instance' => $instanceName,
        'method' => $_SERVER['REQUEST_METHOD'],
        'get_params' => $_GET
    ]);
    
    try {
        if ($action !== 'health' && empty($instanceName)) {
            throw new Exception('Nome da instância não especificado');
        }
        
        switch ($action) {
            case 'health':
                echo json_encode([
                    'status' => 'ok',
                    'timestamp' => date('Y-m-d H:i:s'),
                    'message' => 'API Evolution funcionando!',
                    'instance' => $instanceName,
                    'api_key' => getApiKeyForInstance($instanceName)
                ]);
                break;
                
            case 'instances':
                $result = makeEvolutionRequest('/instance/fetchInstances', 'GET', null, $instanceName);
                if ($result['success']) {
                    echo $result['rawResponse'];
                } else {
                    throw new Exception('Erro ao buscar instâncias: ' . ($result['curlError'] ?? 'HTTP ' . $result['httpCode']));
                }
                break;
                
            case 'connect':
                logDebug("🔗 Iniciando processo de conexão", ['instance' => $instanceName]);
                
                try {
                    // Primeiro verifica se a instância existe
                    $checkResult = makeEvolutionRequest('/instance/fetchInstances', 'GET', null, $instanceName);
                    
                    $instanceExists = false;
                    if ($checkResult['success'] && isset($checkResult['data']['instances'])) {
                        foreach ($checkResult['data']['instances'] as $instance) {
                            if ($instance['instanceName'] === $instanceName) {
                                $instanceExists = true;
                                logDebug("✅ Instância encontrada", ['status' => $instance['state'] ?? 'unknown']);
                                break;
                            }
                        }
                    }
                    
                    if (!$instanceExists) {
                        logDebug("📝 Criando nova instância", ['instance' => $instanceName]);
                        
                        $createData = [
                            'instanceName' => $instanceName,
                            'qrcode' => true,
                            'token' => $instanceName . '_token',
                            'webhook' => ''
                        ];
                        
                        $createResult = makeEvolutionRequest('/instance/create', 'POST', $createData, $instanceName);
                        
                        if (!$createResult['success']) {
                            $errorMsg = 'Falha ao criar instância: ';
                            if ($createResult['httpCode'] === 401) {
                                $errorMsg .= 'API Key inválida ou não autorizada';
                            } elseif (isset($createResult['data']['message'])) {
                                $errorMsg .= $createResult['data']['message'];
                            } else {
                                $errorMsg .= 'HTTP ' . $createResult['httpCode'];
                            }
                            throw new Exception($errorMsg);
                        }
                        
                        logDebug("✅ Instância criada com sucesso");
                        sleep(2); // Aguarda a instância ser inicializada
                    }
                    
                    // Tenta conectar
                    logDebug("🔄 Conectando instância", ['instance' => $instanceName]);
                    $connectResult = makeEvolutionRequest('/instance/connect/' . $instanceName, 'GET', null, $instanceName);
                    
                    logDebug("📊 Resposta da conexão", [
                        'success' => $connectResult['success'],
                        'httpCode' => $connectResult['httpCode'],
                        'has_data' => !empty($connectResult['data'])
                    ]);
                    
                    if ($connectResult['success']) {
                        $responseData = $connectResult['data'];
                        
                        // Verifica diferentes formatos de resposta do QR Code
                        if (isset($responseData['base64'])) {
                            echo json_encode([
                                'success' => true,
                                'base64' => $responseData['base64'],
                                'code' => $responseData['code'] ?? null,
                                'instance' => $instanceName,
                                'message' => 'QR Code gerado com sucesso'
                            ]);
                        } elseif (isset($responseData['qrcode'])) {
                            // Formato alternativo do QR Code
                            $qrcode = $responseData['qrcode'];
                            echo json_encode([
                                'success' => true,
                                'base64' => is_array($qrcode) ? ($qrcode['base64'] ?? null) : $qrcode,
                                'code' => is_array($qrcode) ? ($qrcode['code'] ?? null) : null,
                                'instance' => $instanceName,
                                'message' => 'QR Code gerado com sucesso'
                            ]);
                        } elseif (isset($responseData['url'])) {
                            // Se retornar URL do QR Code
                            echo json_encode([
                                'success' => true,
                                'qrcode_url' => $responseData['url'],
                                'instance' => $instanceName,
                                'message' => 'QR Code URL gerado'
                            ]);
                        } else {
                            // Se não tem QR code mas a conexão foi bem sucedida
                            echo json_encode([
                                'success' => true,
                                'message' => 'Instância conectada com sucesso',
                                'data' => $responseData,
                                'instance' => $instanceName
                            ]);
                        }
                    } else {
                        $errorMsg = 'Falha na conexão: HTTP ' . $connectResult['httpCode'];
                        
                        if ($connectResult['curlError']) {
                            $errorMsg .= ' - cURL: ' . $connectResult['curlError'];
                        }
                        
                        if (isset($connectResult['data']['message'])) {
                            $errorMsg .= ' - ' . $connectResult['data']['message'];
                        }
                        
                        if (isset($connectResult['data']['error'])) {
                            $errorMsg .= ' - ' . $connectResult['data']['error'];
                        }
                        
                        throw new Exception($errorMsg);
                    }
                    
                } catch (Exception $e) {
                    logDebug("❌ Erro crítico na conexão", ['error' => $e->getMessage()]);
                    throw new Exception('Erro ao conectar WhatsApp: ' . $e->getMessage());
                }
                break;
                
            case 'status':
                $result = makeEvolutionRequest('/instance/connectionState/' . $instanceName, 'GET', null, $instanceName);
                if ($result['success']) {
                    echo $result['rawResponse'];
                } else {
                    // Retorna estado padrão se não conseguir buscar
                    echo json_encode([
                        'instance' => [
                            'instanceName' => $instanceName,
                            'state' => 'close'
                        ]
                    ]);
                }
                break;
                
            case 'logout':
                $result = makeEvolutionRequest('/instance/logout/' . $instanceName, 'DELETE', null, $instanceName);
                if ($result['success']) {
                    echo json_encode([
                        'success' => true,
                        'message' => 'Instância desconectada com sucesso',
                        'instance' => $instanceName
                    ]);
                } else {
                    throw new Exception('Falha ao desconectar instância: ' . ($result['curlError'] ?? 'HTTP ' . $result['httpCode']));
                }
                break;
                
            default:
                http_response_code(400);
                echo json_encode([
                    'error' => 'Ação inválida',
                    'available_actions' => ['health', 'instances', 'connect', 'status', 'logout'],
                    'instance' => $instanceName
                ]);
        }
        
    } catch (Exception $e) {
        logDebug("❌ Erro capturado na API", [
            'message' => $e->getMessage(),
            'action' => $action,
            'instance' => $instanceName
        ]);
        
        http_response_code(500);
        echo json_encode([
            'error' => $e->getMessage(),
            'action' => $action,
            'instance' => $instanceName,
            'debug' => DEBUG_MODE ? [
                'timestamp' => date('Y-m-d H:i:s')
            ] : null
        ]);
    }
    exit;
}

// ==================== HTML INTERFACE ====================
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Conexão WhatsApp - Evolution API</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f8f9fa;
            line-height: 1.6;
        }

        .whatsapp-panel {
            width: 100%;
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .panel-header {
            background: linear-gradient(135deg, #25D366 0%, #128C7E 100%);
            color: white;
            padding: 25px 20px;
            text-align: center;
        }

        .panel-header h1 {
            font-size: 2rem;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .instance-selector {
            background: rgba(255,255,255,0.2);
            padding: 15px;
            border-radius: 10px;
            margin-top: 15px;
            backdrop-filter: blur(10px);
        }

        .instance-selector label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
        }

        .instance-selector input {
            width: 100%;
            padding: 10px;
            border: none;
            border-radius: 5px;
            font-size: 1rem;
            text-align: center;
        }

        .connection-status {
            background: rgba(255,255,255,0.2);
            color: white;
            padding: 10px 25px;
            border-radius: 25px;
            display: inline-block;
            font-weight: bold;
            font-size: 1.1rem;
            backdrop-filter: blur(10px);
            margin-top: 10px;
        }

        .connection-status.connected {
            background: rgba(76, 175, 80, 0.8);
        }

        .connection-status.disconnected {
            background: rgba(220, 53, 69, 0.8);
        }

        .connection-status.checking {
            background: rgba(255, 193, 7, 0.8);
        }

        .content-section {
            padding: 25px;
        }

        .status-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 25px;
        }

        .status-card {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 12px;
            border-left: 4px solid #25D366;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }

        .status-title {
            font-weight: bold;
            color: #333;
            margin-bottom: 15px;
            font-size: 1.2rem;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .status-item {
            margin-bottom: 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .status-label {
            color: #666;
            font-size: 0.95rem;
        }

        .status-value {
            color: #333;
            font-weight: bold;
            text-align: right;
        }

        .connected {
            color: #28a745;
        }

        .not-connected {
            color: #dc3545;
        }

        .success-message {
            background: #d4edda;
            color: #155724;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            margin: 20px 0;
            border-left: 4px solid #28a745;
            font-weight: bold;
        }

        .error-message {
            background: #f8d7da;
            color: #721c24;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            margin: 20px 0;
            border-left: 4px solid #dc3545;
            font-weight: bold;
        }

        .action-buttons {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 12px;
            margin: 25px 0;
        }

        .btn {
            padding: 14px;
            border: none;
            border-radius: 8px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 1rem;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none !important;
        }

        .btn-connect {
            background: #25D366;
            color: white;
        }

        .btn-cancel {
            background: #dc3545;
            color: white;
        }

        .btn-status {
            background: #17a2b8;
            color: white;
        }

        .btn-test {
            background: #6f42c1;
            color: white;
        }

        .btn:hover:not(:disabled) {
            opacity: 0.9;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }

        /* Modal QR Code */
        .qr-modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.9);
            animation: fadeIn 0.3s ease;
        }

        .qr-modal.active {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .qr-modal-content {
            background: white;
            border-radius: 20px;
            max-width: 500px;
            width: 95%;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            animation: slideUp 0.3s ease;
        }

        .qr-modal-header {
            background: linear-gradient(135deg, #25D366 0%, #128C7E 100%);
            color: white;
            padding: 25px;
            border-radius: 20px 20px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .qr-modal-header h2 {
            margin: 0;
            font-size: 1.6rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .qr-close {
            background: none;
            border: none;
            color: white;
            font-size: 2.5rem;
            cursor: pointer;
            line-height: 1;
            padding: 0;
            width: 45px;
            height: 45px;
            border-radius: 50%;
            transition: background 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .qr-close:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        .qr-modal-body {
            padding: 30px;
        }

        .qr-container {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
            text-align: center;
            margin-bottom: 25px;
            border: 2px solid #f0f0f0;
        }

        .qr-container img {
            max-width: 280px;
            width: 100%;
            height: auto;
            border-radius: 10px;
            border: 1px solid #e0e0e0;
        }

        .qr-instructions {
            background: #f8f9fa;
            padding: 25px;
            border-radius: 12px;
            border-left: 4px solid #25D366;
        }

        .qr-instructions h3 {
            color: #333;
            margin-bottom: 18px;
            font-size: 1.3rem;
        }

        .qr-instructions ol {
            margin-left: 20px;
            line-height: 1.8;
        }

        .qr-instructions li {
            margin-bottom: 12px;
            color: #555;
        }

        .qr-instructions strong {
            color: #333;
        }

        .qr-warning {
            background: #fff3cd;
            color: #856404;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            text-align: center;
            font-weight: bold;
            border-left: 4px solid #ffc107;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 30px;
            background: #f8f9fa;
            border-radius: 10px;
            margin: 20px 0;
        }

        .loading.active {
            display: block;
        }

        .loading-spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #25D366;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }

        .info-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }

        .info-table th {
            background: #25D366;
            color: white;
            padding: 15px;
            text-align: left;
            font-weight: 600;
        }

        .info-table td {
            padding: 12px 15px;
            border-bottom: 1px solid #e0e0e0;
        }

        .info-table tr:last-child td {
            border-bottom: none;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes slideUp {
            from {
                transform: translateY(50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        @media (max-width: 768px) {
            .status-grid {
                grid-template-columns: 1fr;
            }
            
            .action-buttons {
                grid-template-columns: 1fr;
            }

            .qr-modal-content {
                width: 95%;
                margin: 10px;
            }

            .qr-container img {
                max-width: 250px;
            }

            .panel-header h1 {
                font-size: 1.6rem;
            }

            .content-section {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="whatsapp-panel">
        <div class="panel-header">
            <h1>📱 Conexão WhatsApp</h1>
            <div class="instance-selector">
                <label for="instanceInput">Nome da Instância:</label>
                <input type="text" id="instanceInput" value="w7mastersoftware" placeholder="Digite o nome da instância">
                <button class="btn btn-test" onclick="updateInstance()" style="margin-top: 10px; padding: 8px 15px; font-size: 0.9rem;">
                    🔄 Usar Instância
                </button>
            </div>
            <div class="connection-status checking" id="connectionStatus">Verificando...</div>
        </div>

        <div class="content-section">
            <div class="loading" id="loading">
                <div class="loading-spinner"></div>
                <p>⏳ Processando sua solicitação...</p>
            </div>

            <div class="error-message" id="errorMessage" style="display: none;">
                <strong>❌ Erro:</strong> <span id="errorText"></span>
            </div>

            <div class="status-grid">
                <div class="status-card">
                    <div class="status-title">🔍 Status do WhatsApp</div>
                    <div class="status-item">
                        <div class="status-label">Status de Conexão:</div>
                        <div class="status-value not-connected" id="connectionState">Verificando...</div>
                    </div>
                    <div class="status-item">
                        <div class="status-label">Número Conectado:</div>
                        <div class="status-value not-connected" id="phoneNumber">Não conectado</div>
                    </div>
                    <div class="status-item">
                        <div class="status-label">Instância:</div>
                        <div class="status-value" id="instanceName">w7mastersoftware</div>
                    </div>
                </div>

                <div class="status-card">
                    <div class="status-title">⚙️ Informações do Sistema</div>
                    <div class="status-item">
                        <div class="status-label">API:</div>
                        <div class="status-value">Evolution API</div>
                    </div>
                    <div class="status-item">
                        <div class="status-label">Última Atualização:</div>
                        <div class="status-value" id="lastUpdate">-</div>
                    </div>
                    <div class="status-item">
                        <div class="status-label">Estado Atual:</div>
                        <div class="status-value" id="currentState">-</div>
                    </div>
                </div>
            </div>

            <div class="success-message" id="successMessage" style="display: none;">
                <strong>✅ WhatsApp conectado e funcionando perfeitamente!</strong>
            </div>

            <div class="action-buttons">
                <button class="btn btn-connect" id="btnConnect">
                    <span>🔗 Conectar WhatsApp</span>
                </button>
                <button class="btn btn-cancel" id="btnDisconnect" disabled>
                    <span>🚫 Desconectar</span>
                </button>
                <button class="btn btn-status" id="btnStatus">
                    <span>🔄 Atualizar Status</span>
                </button>
                <button class="btn btn-test" id="btnTest">
                    <span>🧪 Testar API</span>
                </button>
            </div>

            <!-- Modal QR Code -->
            <div class="qr-modal" id="qrModal">
                <div class="qr-modal-content">
                    <div class="qr-modal-header">
                        <h2>📱 Escanear QR Code</h2>
                        <button class="qr-close" id="qrClose">&times;</button>
                    </div>
                    <div class="qr-modal-body">
                        <div class="qr-container">
                            <img id="qrCodeImage" src="" alt="QR Code do WhatsApp">
                        </div>
                        <div class="qr-instructions">
                            <h3>Como conectar seu WhatsApp:</h3>
                            <ol>
                                <li>Abra o <strong>WhatsApp</strong> no seu celular</li>
                                <li>Toque em <strong>☰ Menu</strong> (três pontos)</li>
                                <li>Selecione <strong>Aparelhos conectados</strong></li>
                                <li>Toque em <strong>Conectar um aparelho</strong></li>
                                <li>Aponte a câmera do celular para esta tela para escanear o código</li>
                            </ol>
                            <div class="qr-warning">
                                ⚠️ O QR Code expira em aproximadamente 40 segundos
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <table class="info-table">
                <thead>
                    <tr>
                        <th>📊 Informações da Instância</th>
                        <th>Valores</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><strong>Instância Atual:</strong></td>
                        <td id="currentInstance">w7mastersoftware</td>
                    </tr>
                    <tr>
                        <td><strong>API Key:</strong></td>
                        <td id="currentApiKey">w7mastersoftware</td>
                    </tr>
                    <tr>
                        <td><strong>Status da API:</strong></td>
                        <td id="apiStatus">🟡 Verificando...</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <script>
        // Configuração - A instância será obtida do input
        let CURRENT_INSTANCE = 'w7mastersoftware';
        const API_URL = window.location.pathname;
        
        // Elementos DOM
        const els = {
            instanceInput: document.getElementById('instanceInput'),
            connectionStatus: document.getElementById('connectionStatus'),
            connectionState: document.getElementById('connectionState'),
            phoneNumber: document.getElementById('phoneNumber'),
            instanceName: document.getElementById('instanceName'),
            currentInstance: document.getElementById('currentInstance'),
            currentApiKey: document.getElementById('currentApiKey'),
            successMessage: document.getElementById('successMessage'),
            errorMessage: document.getElementById('errorMessage'),
            errorText: document.getElementById('errorText'),
            loading: document.getElementById('loading'),
            btnConnect: document.getElementById('btnConnect'),
            btnDisconnect: document.getElementById('btnDisconnect'),
            btnStatus: document.getElementById('btnStatus'),
            btnTest: document.getElementById('btnTest'),
            lastUpdate: document.getElementById('lastUpdate'),
            currentState: document.getElementById('currentState'),
            apiStatus: document.getElementById('apiStatus'),
            qrModal: document.getElementById('qrModal'),
            qrCodeImage: document.getElementById('qrCodeImage'),
            qrClose: document.getElementById('qrClose')
        };

        // Estado da aplicação
        let appState = {
            isConnected: false,
            checkInterval: null,
            qrCheckInterval: null
        };

        // Função para atualizar a instância
        function updateInstance() {
            const newInstance = els.instanceInput.value.trim();
            if (newInstance) {
                CURRENT_INSTANCE = newInstance;
                els.instanceName.textContent = newInstance;
                els.currentInstance.textContent = newInstance;
                els.currentApiKey.textContent = newInstance;
                
                // Reseta o status
                updateStatus('close');
                checkStatus();
                
                showError('Instância alterada para: ' + newInstance);
            }
        }

        // Funções auxiliares
        function showLoading(show) {
            els.loading.classList.toggle('active', show);
        }

        function showError(message) {
            els.errorText.textContent = message;
            els.errorMessage.style.display = 'block';
            setTimeout(() => {
                els.errorMessage.style.display = 'none';
            }, 8000);
        }

        function showQRModal(qrCode) {
            els.qrCodeImage.src = qrCode;
            els.qrModal.classList.add('active');
            
            // Limpa intervalos anteriores
            if (appState.qrCheckInterval) {
                clearInterval(appState.qrCheckInterval);
            }
            
            // Verifica status a cada 3 segundos enquanto o modal estiver aberto
            appState.qrCheckInterval = setInterval(() => {
                checkStatus();
            }, 3000);
        }

        function hideQRModal() {
            els.qrModal.classList.remove('active');
            els.qrCodeImage.src = '';
            
            if (appState.qrCheckInterval) {
                clearInterval(appState.qrCheckInterval);
                appState.qrCheckInterval = null;
            }
        }

        function updateStatus(state, phone = null, instanceData = null) {
            const isConnected = state === 'open';
            appState.isConnected = isConnected;
            
            // Atualiza status principal
            els.connectionStatus.textContent = isConnected ? 'Conectado' : 'Desconectado';
            els.connectionStatus.className = `connection-status ${isConnected ? 'connected' : 'disconnected'}`;
            
            // Atualiza detalhes
            els.connectionState.textContent = isConnected ? '✅ Conectado' : '❌ Desconectado';
            els.connectionState.className = isConnected ? 'status-value connected' : 'status-value not-connected';
            
            if (phone) {
                els.phoneNumber.textContent = phone;
                els.phoneNumber.className = 'status-value connected';
            } else {
                els.phoneNumber.textContent = 'Não conectado';
                els.phoneNumber.className = 'status-value not-connected';
            }
            
            // Mensagens de sucesso/erro
            els.successMessage.style.display = isConnected ? 'block' : 'none';
            
            // Timestamp
            els.lastUpdate.textContent = new Date().toLocaleString('pt-BR');
            els.currentState.textContent = state;

            // Atualiza botões
            els.btnConnect.disabled = isConnected;
            els.btnDisconnect.disabled = !isConnected;
            
            // Atualiza status da API
            els.apiStatus.textContent = isConnected ? '🟢 Online' : '🔴 Offline';
        }

        // API Calls
        async function callAPI(action, method = 'GET') {
            try {
                const url = `${API_URL}?api=1&action=${action}&instance=${CURRENT_INSTANCE}&t=${Date.now()}`;
                const response = await fetch(url, { 
                    method,
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const data = await response.json();
                
                if (!response.ok) {
                    throw new Error(data.error || `HTTP ${response.status}`);
                }
                
                return data;
            } catch (error) {
                console.error('API Error:', error);
                throw error;
            }
        }

        // Conectar WhatsApp
        async function connectWhatsApp() {
            try {
                els.btnConnect.disabled = true;
                els.btnConnect.innerHTML = '<span>⏳ Conectando...</span>';
                showLoading(true);
                showError('');

                const data = await callAPI('connect');
                
                console.log('Resposta da API Connect:', data);
                
                if (data.success && data.base64) {
                    const qrCodeData = `data:image/png;base64,${data.base64}`;
                    showQRModal(qrCodeData);
                    
                    // Feedback para o usuário
                    els.btnConnect.innerHTML = '<span>📱 Aguardando QR Code...</span>';
                    
                } else if (data.success && !data.base64) {
                    // Conexão direta sem QR Code
                    hideQRModal();
                    await checkStatus();
                    alert('✅ WhatsApp conectado com sucesso!');
                    
                } else {
                    throw new Error(data.error || 'Resposta inesperada da API');
                }
                
            } catch (error) {
                console.error('Erro completo:', error);
                showError('Erro ao conectar: ' + error.message);
                els.btnConnect.disabled = false;
                els.btnConnect.innerHTML = '<span>🔗 Conectar WhatsApp</span>';
            } finally {
                showLoading(false);
            }
        }

        // Verificar status
        async function checkStatus() {
            try {
                const data = await callAPI('status');
                
                if (data.instance) {
                    const state = data.instance.state || 'close';
                    const phone = data.instance.owner || data.instance.user?.id || null;
                    updateStatus(state, phone, data.instance);
                    
                    // Se conectou e o modal está aberto, fecha o modal
                    if (state === 'open' && els.qrModal.classList.contains('active')) {
                        hideQRModal();
                        els.btnConnect.innerHTML = '<span>🔗 Conectar WhatsApp</span>';
                        els.btnConnect.disabled = true;
                    }
                }
            } catch (error) {
                console.error('Erro ao verificar status:', error);
                updateStatus('close');
            }
        }

        // Desconectar
        async function disconnect() {
            if (!confirm('Tem certeza que deseja desconectar o WhatsApp?\n\nIsso irá encerrar a sessão atual.')) {
                return;
            }

            try {
                els.btnDisconnect.disabled = true;
                els.btnDisconnect.innerHTML = '<span>⏳ Desconectando...</span>';
                showLoading(true);

                await callAPI('logout', 'DELETE');
                
                updateStatus('close');
                hideQRModal();
                alert('✅ WhatsApp desconectado com sucesso!');
                
            } catch (error) {
                showError('Erro ao desconectar: ' + error.message);
            } finally {
                els.btnDisconnect.disabled = false;
                els.btnDisconnect.innerHTML = '<span>🚫 Desconectar</span>';
                showLoading(false);
            }
        }

        // Testar API
        async function testAPI() {
            try {
                showLoading(true);
                const data = await callAPI('health');
                alert(`✅ Teste de API realizado com sucesso!\n\n📊 Status: ${data.status}\n⏰ Timestamp: ${data.timestamp}\n🔧 Instância: ${data.instance}\n🔑 API Key: ${data.api_key}`);
            } catch (error) {
                showError('❌ Erro ao testar API: ' + error.message);
            } finally {
                showLoading(false);
            }
        }

        // Event Listeners
        els.btnConnect.addEventListener('click', connectWhatsApp);
        els.btnDisconnect.addEventListener('click', disconnect);
        els.btnStatus.addEventListener('click', checkStatus);
        els.btnTest.addEventListener('click', testAPI);
        els.qrClose.addEventListener('click', hideQRModal);
        
        // Enter no input da instância
        els.instanceInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                updateInstance();
            }
        });
        
        // Fechar modal ao clicar fora
        els.qrModal.addEventListener('click', (e) => {
            if (e.target === els.qrModal) {
                hideQRModal();
                els.btnConnect.disabled = false;
                els.btnConnect.innerHTML = '<span>🔗 Conectar WhatsApp</span>';
            }
        });

        // Inicializar
        function init() {
            els.connectionStatus.textContent = 'Verificando...';
            els.connectionStatus.className = 'connection-status checking';
            
            // Primeira verificação
            checkStatus();
            
            // Configurar verificação automática a cada 10 segundos
            appState.checkInterval = setInterval(checkStatus, 10000);
        }

        // Iniciar aplicação
        init();

        // Limpar intervalos ao sair da página
        window.addEventListener('beforeunload', () => {
            if (appState.checkInterval) {
                clearInterval(appState.checkInterval);
            }
            if (appState.qrCheckInterval) {
                clearInterval(appState.qrCheckInterval);
            }
        });
    </script>
</body>
</html>