// Configuración y estado de la aplicación
const AppState = {
    config: {
        apiKey: 'dev_test_key_admin',
        secretKey: 'dev_secret_key_admin_123456',
        baseUrl: 'http://localhost:3000'
    },
    transactions: [],
    banks: []
};

// Inicialización de la aplicación
document.addEventListener('DOMContentLoaded', function() {
    console.log('🚀 Payment Gateway Frontend Iniciado');
    
    // Cargar configuración guardada
    loadSavedSettings();
    
    // Cargar datos iniciales
    loadDashboardData();
    loadBanks();
    
    // Generar datos de prueba
    generateTestData();
});

// Navegación entre secciones
function showSection(sectionId) {
    // Ocultar todas las secciones
    document.querySelectorAll('.content-area').forEach(section => {
        section.classList.remove('active');
    });
    
    // Mostrar la sección seleccionada
    document.getElementById(sectionId).classList.add('active');
    
    // Actualizar menú activo
    document.querySelectorAll('.menu-item').forEach(item => {
        item.classList.remove('active');
    });
    
    // Encontrar el elemento del menú que fue clickeado
    const menuItems = document.querySelectorAll('.menu-item');
    for (let item of menuItems) {
        if (item.onclick && item.onclick.toString().includes(sectionId)) {
            item.classList.add('active');
            break;
        }
    }
    
    // Actualizar título
    const titles = {
        'dashboard': 'Dashboard',
        'create-payment': 'Crear Pago',
        'transactions': 'Transacciones',
        'banks': 'Bancos',
        'settings': 'Configuración'
    };
    document.getElementById('section-title').textContent = titles[sectionId];
    
    // Cargar datos específicos de la sección
    if (sectionId === 'transactions') {
        loadTransactions();
    } else if (sectionId === 'dashboard') {
        loadDashboardData();
    } else if (sectionId === 'banks') {
        loadBanks();
    }
}

// Cargar configuración guardada
function loadSavedSettings() {
    const savedConfig = localStorage.getItem('paymentGatewayConfig');
    if (savedConfig) {
        AppState.config = { ...AppState.config, ...JSON.parse(savedConfig) };
        document.getElementById('apiKey').value = AppState.config.apiKey;
        document.getElementById('secretKey').value = AppState.config.secretKey;
        document.getElementById('baseUrl').value = AppState.config.baseUrl;
    }
}

// Guardar configuración
function saveSettings() {
    AppState.config = {
        apiKey: document.getElementById('apiKey').value,
        secretKey: document.getElementById('secretKey').value,
        baseUrl: document.getElementById('baseUrl').value
    };
    
    localStorage.setItem('paymentGatewayConfig', JSON.stringify(AppState.config));
    showNotification('✅ Configuración guardada correctamente', 'success');
}

// Generar firma HMAC-SHA256 (COMPATIBLE con el backend corregido)
async function generateSignature(secretKey, method, path, timestamp, body) {
    // CORRECCIÓN: Asegurar que el body esté correctamente formateado
    const bodyString = JSON.stringify(body || {});
    
    const payload = `${method.toUpperCase()}${path}${timestamp}${bodyString}`;
    
    console.log('\n🔐 [FRONTEND] Generando firma:');
    console.log('   Método:', method.toUpperCase());
    console.log('   Path:', path);
    console.log('   Timestamp:', timestamp);
    console.log('   Body:', bodyString);
    console.log('   Payload completo:', `"${payload}"`);
    console.log('   Longitud payload:', payload.length);
    console.log('   Secret Key:', secretKey ? '***' + secretKey.slice(-4) : 'MISSING');
    
    try {
        // Usar Web Crypto API para HMAC-SHA256
        const encoder = new TextEncoder();
        const keyData = encoder.encode(secretKey);
        const payloadData = encoder.encode(payload);
        
        const key = await crypto.subtle.importKey(
            'raw', 
            keyData, 
            { name: 'HMAC', hash: 'SHA-256' },
            false, 
            ['sign']
        );
        
        const signatureBuffer = await crypto.subtle.sign('HMAC', key, payloadData);
        const signatureArray = Array.from(new Uint8Array(signatureBuffer));
        const signatureHex = signatureArray.map(b => b.toString(16).padStart(2, '0')).join('');
        
        console.log('   ✅ Firma generada:', signatureHex);
        console.log('   Longitud firma:', signatureHex.length);
        
        return signatureHex;
        
    } catch (error) {
        console.error('❌ [FRONTEND] Error con Web Crypto:', error);
        // Fallback para desarrollo
        return generateSignatureFallback(secretKey, method, path, timestamp, body);
    }
}

// Fallback para navegadores sin Web Crypto API
function generateSignatureFallback(secretKey, method, path, timestamp, body) {
    const bodyString = JSON.stringify(body || {});
    const payload = `${method.toUpperCase()}${path}${timestamp}${bodyString}`;
    
    console.log('🔄 [FRONTEND] Usando fallback para firma');
    
    // Implementación simple de HMAC (solo para desarrollo)
    let hash = 0;
    for (let i = 0; i < payload.length; i++) {
        const char = payload.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
        hash = hash & hash;
    }
    
    let result = '';
    const combined = secretKey + Math.abs(hash).toString(16) + payload;
    
    for (let i = 0; i < combined.length; i++) {
        const charCode = combined.charCodeAt(i);
        result += charCode.toString(16).padStart(2, '0');
    }
    
    // Asegurar longitud de 64 caracteres
    while (result.length < 64) {
        result += '0';
    }
    
    const finalSignature = result.substring(0, 64);
    console.log('   🔄 Firma fallback:', finalSignature);
    
    return finalSignature;
}

// Función para hacer requests con debug completo
async function makeRequest(method, path, body = null) {
    const timestamp = Date.now().toString();
    
    console.log(`\n🚀 [FRONTEND] Preparando request ${method} ${path}`);
    
    // CORRECCIÓN: Para requests GET, usar body vacío
    const requestBody = method === 'GET' ? {} : (body || {});
    
    // Validar que tenemos secretKey
    if (!AppState.config.secretKey) {
        console.error('❌ [FRONTEND] Secret Key no configurado');
        return {
            success: false,
            error: 'Secret Key no configurado'
        };
    }
    
    const signature = await generateSignature(
        AppState.config.secretKey,
        method,
        path,
        timestamp,
        requestBody
    );
    
    const headers = {
        'Content-Type': 'application/json',
        'x-api-key': AppState.config.apiKey,
        'x-signature': signature,
        'x-timestamp': timestamp
    };
    
    console.log('📤 [FRONTEND] Enviando request:');
    console.log('   URL:', `${AppState.config.baseUrl}${path}`);
    console.log('   Headers:', {
        'x-api-key': '***' + AppState.config.apiKey.slice(-4),
        'x-signature': signature.substring(0, 20) + '...',
        'x-timestamp': timestamp,
        'Content-Type': 'application/json'
    });
    console.log('   Body usado para firma:', JSON.stringify(requestBody));
    
    const config = {
        method: method,
        headers: headers
    };
    
    // Solo enviar body en requests que lo requieran
    if (method !== 'GET' && method !== 'HEAD' && body !== null) {
        config.body = JSON.stringify(body);
        console.log('   Body enviado en request:', JSON.stringify(body));
    }
    
    try {
        const response = await fetch(`${AppState.config.baseUrl}${path}`, config);
        const data = await response.json();
        
        console.log(`📥 [FRONTEND] Respuesta recibida:`);
        console.log('   Status:', response.status);
        console.log('   Data:', data);
        
        return {
            success: response.ok,
            status: response.status,
            data: data
        };
        
    } catch (error) {
        console.error('❌ [FRONTEND] Error de conexión:', error);
        return {
            success: false,
            error: error.message
        };
    }
}

// Probar conexión con la API
async function testConnection() {
    showLoading('paymentLoading', true);
    
    console.log('\n🧪 [FRONTEND] Probando conexión...');
    const result = await makeRequest('GET', '/health');
    
    if (result.success) {
        showNotification('✅ Conexión exitosa con el servidor', 'success', result.data);
    } else {
        showNotification(`❌ Error en la conexión: ${result.data?.error || result.error}`, 'error', result.data);
    }
    
    showLoading('paymentLoading', false);
}

// Cargar bancos
async function loadBanks() {
    showLoading('banksLoading', true);
    
    console.log('\n🏦 [FRONTEND] Cargando bancos...');
    const result = await makeRequest('GET', '/api/v1/banks');
    
    if (result.success) {
        AppState.banks = result.data.data || [];
        displayBanks(AppState.banks);
        showNotification('✅ Bancos cargados correctamente', 'success');
    } else {
        showNotification(`❌ Error cargando bancos: ${result.data?.error || result.error}`, 'error', result.data);
        
        // Mostrar bancos de ejemplo para desarrollo
        const mockBanks = [
            { code: '0102', name: 'Banco de Venezuela', is_active: true },
            { code: '0104', name: 'Banco Provincial', is_active: true },
            { code: '0105', name: 'Mercantil', is_active: false },
            { code: '0134', name: 'Banesco', is_active: true }
        ];
        
        AppState.banks = mockBanks;
        displayBanks(mockBanks);
    }
    
    showLoading('banksLoading', false);
}

// Crear un nuevo pago
async function createPayment() {
    //document.getElementById('bankCode').value
    const paymentData = {
        order_id: document.getElementById('orderId').value,
        amount: parseFloat(document.getElementById('amount').value),
        bank_code: document.getElementById('bankCode').value,
        payer_info: {
            document: document.getElementById('payerDocument').value,
            phone: document.getElementById('payerPhone').value,
            name: document.getElementById('payerName').value
        },
        beneficiary_info: {
            phone: document.getElementById('beneficiaryPhone').value,
            document: document.getElementById('beneficiaryDocument').value
        },
        description: document.getElementById('description').value
    };
    
    // Validaciones
    if (!paymentData.amount || paymentData.amount <= 0) {
        showNotification('❌ El monto debe ser mayor a 0', 'error');
        return;
    }
    
    if (!AppState.config.secretKey) {
        showNotification('❌ Secret Key es requerido', 'error');
        return;
    }
    
    showLoading('paymentLoading', true);
    
    console.log('\n💳 [FRONTEND] Creando pago...');
    const result = await makeRequest('POST', '/api/v1/payments/create', paymentData);
    
    if (result.success) {
        showNotification('✅ Pago creado exitosamente', 'success');
        showPaymentResult(result.data, true);
        
        // Actualizar dashboard
        loadDashboardData();
        
        // Mostrar instrucciones de pago
        if (result.data.data && result.data.data.payment_instructions) {
            setTimeout(() => {
                showPaymentInstructions(result.data.data.payment_instructions);
            }, 1000);
        }
    } else {
        showNotification(`❌ Error: ${result.data?.error || result.error}`, 'error');
        showPaymentResult(result.data, false);
    }
    
    showLoading('paymentLoading', false);
}

// Cargar transacciones
async function loadTransactions() {
    showLoading('transactionsLoading', true);
    
    try {
        // En un sistema real, aquí harías una petición a la API
        // Por ahora simulamos datos
        const mockTransactions = [
            {
                transaction_id: 'test-' + Date.now(),
                reference: 'TEST-001',
                amount: 150.75,
                status: 'completed',
                created_at: new Date().toISOString()
            },
            {
                transaction_id: 'test-' + (Date.now() - 1000),
                reference: 'TEST-002',
                amount: 200.00,
                status: 'pending',
                created_at: new Date(Date.now() - 3600000).toISOString()
            }
        ];
        
        displayTransactions(mockTransactions);
        showNotification('ℹ️ Transacciones de demostración cargadas', 'info');
        
    } catch (error) {
        showNotification(`❌ Error cargando transacciones: ${error.message}`, 'error');
    } finally {
        showLoading('transactionsLoading', false);
    }
}

// Cargar datos del dashboard
async function loadDashboardData() {
    // Simular estadísticas (en un sistema real harías peticiones a la API)
    document.getElementById('stat-completed').textContent = '12';
    document.getElementById('stat-pending').textContent = '3';
    document.getElementById('stat-failed').textContent = '1';
    document.getElementById('stat-total').textContent = 'Bs 2,450.75';
    
    // Cargar actividad reciente
    loadTransactions();
}

// Mostrar transacciones en la lista
function displayTransactions(transactions) {
    const container = document.getElementById('transactionsList') || 
                     document.getElementById('recent-activity');
    
    if (!container) return;
    
    if (transactions.length === 0) {
        container.innerHTML = `
            <div style="text-align: center; color: #666; padding: 40px;">
                <i class="fas fa-inbox" style="font-size: 3em; margin-bottom: 15px; opacity: 0.5;"></i>
                <p>No hay transacciones para mostrar</p>
            </div>
        `;
        return;
    }
    
    container.innerHTML = transactions.map(transaction => `
        <div class="transaction-item">
            <div class="transaction-info">
                <h4>${transaction.reference}</h4>
                <div class="transaction-meta">
                    ${new Date(transaction.created_at).toLocaleString()} • 
                    ${transaction.transaction_id}
                </div>
            </div>
            <div style="text-align: right;">
                <div class="transaction-amount">Bs ${transaction.amount}</div>
                <div class="status ${transaction.status}">${transaction.status}</div>
            </div>
        </div>
    `).join('');
}

// Mostrar bancos en la lista
function displayBanks(banks) {
    const container = document.getElementById('banksList');
    if (!container) return;
    
    container.innerHTML = banks.map(bank => `
        <div class="transaction-item">
            <div class="transaction-info">
                <h4>${bank.name}</h4>
                <div class="transaction-meta">Código: ${bank.code}</div>
            </div>
            <div class="status ${bank.is_active ? 'completed' : 'failed'}">
                ${bank.is_active ? 'Activo' : 'Inactivo'}
            </div>
        </div>
    `).join('');
}

// Mostrar instrucciones de pago
function showPaymentInstructions(instructions) {
    const modal = document.createElement('div');
    modal.style.cssText = `
        position: fixed; top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(0,0,0,0.8); display: flex; align-items: center;
        justify-content: center; z-index: 1000; padding: 20px;
    `;
    
    modal.innerHTML = `
        <div style="background: white; padding: 30px; border-radius: 15px; max-width: 500px; width: 100%;">
            <h3 style="color: #2b2d42; margin-bottom: 20px;">📱 Instrucciones de Pago</h3>
            <div style="background: #f8f9fa; padding: 20px; border-radius: 10px; margin-bottom: 20px;">
                <h4 style="color: #4361ee; margin-bottom: 15px;">${instructions.name}</h4>
                <ol style="text-align: left; color: #666;">
                    ${instructions.steps.map(step => `<li style="margin-bottom: 10px;">${step}</li>`).join('')}
                </ol>
                ${instructions.help ? `<p style="color: #f72585; margin-top: 15px;"><strong>💡 ${instructions.help}</strong></p>` : ''}
            </div>
            <button onclick="this.parentElement.parentElement.remove()" style="
                background: #4361ee; color: white; border: none; padding: 12px 30px;
                border-radius: 8px; cursor: pointer; width: 100%; font-size: 16px;
            ">Cerrar</button>
        </div>
    `;
    
    document.body.appendChild(modal);
}

// Mostrar resultado del pago
function showPaymentResult(data, isSuccess) {
    const container = document.getElementById('paymentResult');
    container.className = `result ${isSuccess ? 'success' : 'error'}`;
    
    let html = `<strong>${isSuccess ? '✅ Éxito' : '❌ Error'}</strong><br>`;
    html += `<pre>${JSON.stringify(data, null, 2)}</pre>`;
    
    if (isSuccess && data.data && data.data.transaction_id) {
        html += `<button class="btn" onclick="copyToClipboard('${data.data.transaction_id}')" style="margin-top: 10px;">
            <i class="fas fa-copy"></i> Copiar Transaction ID
        </button>`;
    }
    
    container.innerHTML = html;
}

// Utilidades
function showLoading(elementId, show) {
    const element = document.getElementById(elementId);
    if (element) {
        element.style.display = show ? 'block' : 'none';
    }
}

function showNotification(message, type = 'info', data = null) {
    // Crear notificación
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed; top: 20px; right: 20px; padding: 15px 20px;
        border-radius: 10px; color: white; z-index: 10000;
        background: ${type === 'success' ? '#4cc9f0' : type === 'error' ? '#f72585' : '#4361ee'};
        box-shadow: 0 5px 15px rgba(0,0,0,0.2); animation: slideIn 0.3s;
        max-width: 400px; word-wrap: break-word;
    `;
    
    let content = `
        <i class="fas fa-${type === 'success' ? 'check' : type === 'error' ? 'exclamation-triangle' : 'info'}"></i>
        ${message}
    `;
    
    if (data && data.error) {
        content += `<br><small>${data.error}</small>`;
    }
    
    notification.innerHTML = content;
    document.body.appendChild(notification);
    
    // Remover después de 5 segundos
    setTimeout(() => {
        notification.remove();
    }, 5000);
}

function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        showNotification('✅ Copiado al portapapeles', 'success');
    });
}

function generateTestData() {
    document.getElementById('orderId').value = `TEST-${Date.now()}`;
    document.getElementById('amount').value = (Math.random() * 200 + 50).toFixed(2);
    document.getElementById('payerDocument').value = 'V' + Math.floor(10000000 + Math.random() * 90000000);
    document.getElementById('payerPhone').value = '0414' + Math.floor(1000000 + Math.random() * 9000000);
    document.getElementById('payerName').value = 'Usuario ' + Math.floor(Math.random() * 1000);
}

// Añadir estilos CSS para las animaciones
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
`;
document.head.appendChild(style);