<?php
/**
 * Layout específico para WebTrader - Solo para clientes
 */
// Incluir helpers para rutas dinámicas
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/modules/shared/helpers.php';

// Modo invitado: sin sesión
$guestMode = (!isset($_SESSION['client_id']) || !$_SESSION['client_id']);

if ($guestMode) {
    // No redirigir: presentar vista pública con CTA
    $client = null;
    $account_info = [];
    $webtraderConfig = [ 'accounts' => [] ];
} else {
    // Verificar cliente autenticado y activo
    $db = getDB();
    $client = $db->selectOne(
        "SELECT id, email, first_name, last_name, status, desk_id 
         FROM clients 
         WHERE id = ? AND status = 'active'",
        [$_SESSION['client_id']]
    );
    if (!$client) {
        session_destroy();
        header('Location: ' . module_url('client_portal/login.php') . '?error=account_inactive');
        exit;
    }
    // Cargar cuentas del cliente para header y config
    $accounts = $db->select(
        "SELECT account_number, account_type, currency, balance, equity, margin, free_margin, margin_level
         FROM trading_accounts WHERE client_id = ? AND status = 'active' ORDER BY created_at DESC",
        [$client['id']]
    );
    if (!$accounts || count($accounts) === 0) {
        $accounts = $db->select(
            "SELECT account_number, account_type, currency, balance,
                    balance AS equity, 0 AS margin, balance AS free_margin, 0 AS margin_level
             FROM client_accounts WHERE client_id = ? AND status = 'active' ORDER BY created_at DESC",
            [$client['id']]
        );
    }
    $account_info = $accounts ? $accounts[0] : [
        'account_number' => null,
        'account_type' => 'standard',
        'currency' => 'USD',
        'balance' => 0.00,
        'equity' => 0.00,
        'margin' => 0.00,
        'free_margin' => 0.00,
        'margin_level' => 0.00,
    ];
    $webtraderConfig = [ 'accounts' => $accounts ];
    // Presencia inmediata (server-side)
    try {
        $pdoW = $db->getConnection();
        try { $pdoW->query("SHOW COLUMNS FROM clients LIKE 'last_seen'"); }
        catch (Throwable $__) { $pdoW->exec("ALTER TABLE clients ADD COLUMN last_seen DATETIME NULL"); }
        $pdoW->prepare('UPDATE clients SET last_seen = NOW() WHERE id = ?')->execute([ (int)$_SESSION['client_id'] ]);
        $pdoW->prepare('CREATE TABLE IF NOT EXISTS client_presence (client_id INT PRIMARY KEY, last_seen DATETIME NULL, source VARCHAR(20) NULL, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, FOREIGN KEY (client_id) REFERENCES clients(id) ON DELETE CASCADE)')->execute();
        $pdoW->prepare('INSERT INTO client_presence (client_id,last_seen,source,updated_at) VALUES (?,?,"webtrader",NOW()) ON DUPLICATE KEY UPDATE last_seen=VALUES(last_seen), source=VALUES(source), updated_at=NOW()')->execute([ (int)$_SESSION['client_id'], date('Y-m-d H:i:s') ]);
    } catch (Throwable $__) {}
}

// Definir constantes si no existen
if (!defined('APP_NAME')) {
    define('APP_NAME', 'ProfixCRM WebTrader');
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo isset($page_title) ? $page_title . ' - ' . APP_NAME : APP_NAME; ?></title>
    <!-- Establecer base para rutas relativas del módulo -->
    <base href="/modules/webtrader/">
    

    
    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <!-- Chart.js date adapter for time scales -->
    <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns"></script>
    <!-- Financial charts (candlestick/ohlc) plugin -->
    <script src="https://cdn.jsdelivr.net/npm/chartjs-chart-financial"></script>
    <!-- Performance: preconnect to data providers -->
    <link rel="preconnect" href="https://api.finage.co.uk">
    <link rel="dns-prefetch" href="//api.finage.co.uk">
    <link rel="preconnect" href="https://xs68rzvrjn.finage.ws:7003">
    <link rel="dns-prefetch" href="//xs68rzvrjn.finage.ws">
    <!-- Country flags removed -->

    <link rel="stylesheet" href="webtrader_styles.css">
</head>
<body class="webtrader-body <?php echo !empty($webtraderConfig['accounts']) ? 'has-header-account-selector' : ''; ?>">
    <?php if ($guestMode): ?>
    <!-- Banner de invitado removido por solicitud: no mostrar CTA ni textos promocionales -->
    <?php endif; ?>
    <!-- WebTrader Header -->
    <header class="webtrader-header">
        <div class="header-brand">
            <div class="brand-logo">
                <i class="fas fa-chart-line"></i>
                <!-- Modales -->
        <!-- Modal de Perfil -->
        <div id="profileModal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3><i class="fas fa-user"></i> Mi Perfil</h3>
                    <button class="close-modal" onclick="closeModal('profileModal')">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="profile-content">
                        <div class="profile-section">
                            <h4>Información Personal</h4>
                            <div class="form-group">
                                <label>Nombre Completo</label>
                                <input type="text" value="Juan Pérez" readonly>
                            </div>
                            <div class="form-group">
                                <label>Email</label>
                                <input type="email" value="juan.perez@email.com" readonly>
                            </div>
                            <div class="form-group">
                                <label>Teléfono</label>
                                <input type="tel" value="+1 234 567 8900" readonly>
                            </div>
                            <div class="form-group">
                                <label>País</label>
                                <input type="text" value="México" readonly>
                            </div>
                        </div>
                        
                        <div class="profile-section">
                            <h4>Información de Cuenta</h4>
                            <div class="account-stats">
                                <div class="stat-item">
                                    <span class="label">Número de Cuenta</span>
                                    <span class="value">#MT5-123456</span>
                                </div>
                                <div class="stat-item">
                                    <span class="label">Tipo de Cuenta</span>
                                    <span class="value">Standard</span>
                                </div>
                                <div class="stat-item">
                                    <span class="label">Apalancamiento</span>
                                    <span class="value">1:100</span>
                                </div>
                                <div class="stat-item">
                                    <span class="label">Fecha de Registro</span>
                                    <span class="value">15 Enero 2024</span>
                                </div>
                                <div class="stat-item">
                                    <span class="label">Estado de Verificación</span>
                                    <span class="value" style="color: #00d4aa;">Verificado</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Modal de Historial -->
        <div id="historyModal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3><i class="fas fa-history"></i> Historial de Trading</h3>
                    <button class="close-modal" onclick="closeModal('historyModal')">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="history-content">
                        <div class="history-filters">
                            <div class="form-group">
                                <label>Filtrar por período</label>
                                <select>
                                    <option>Últimos 7 días</option>
                                    <option>Último mes</option>
                                    <option>Últimos 3 meses</option>
                                    <option>Todo el historial</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="history-table">
                            <table>
                                <thead>
                                    <tr>
                                        <th>Fecha</th>
                                        <th>Símbolo</th>
                                        <th>Tipo</th>
                                        <th>Volumen</th>
                                        <th>Precio</th>
                                        <th>P&L</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>2024-01-20 14:30</td>
                                        <td>EURUSD</td>
                                        <td class="type-buy">BUY</td>
                                        <td>0.10</td>
                                        <td>1.0850</td>
                                        <td class="pnl profit">+$25.50</td>
                                    </tr>
                                    <tr>
                                        <td>2024-01-20 12:15</td>
                                        <td>GBPUSD</td>
                                        <td class="type-sell">SELL</td>
                                        <td>0.05</td>
                                        <td>1.2650</td>
                                        <td class="pnl loss">-$12.30</td>
                                    </tr>
                                    <tr>
                                        <td>2024-01-19 16:45</td>
                                        <td>USDJPY</td>
                                        <td class="type-buy">BUY</td>
                                        <td>0.20</td>
                                        <td>148.50</td>
                                        <td class="pnl profit">+$45.80</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Modal de Reportes -->
        <div id="reportsModal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3><i class="fas fa-download"></i> Descargar Reportes</h3>
                    <button class="close-modal" onclick="closeModal('reportsModal')">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>Tipo de Reporte</label>
                        <select id="reportType">
                            <option value="trading">Historial de Trading</option>
                            <option value="account">Estado de Cuenta</option>
                            <option value="transactions">Transacciones</option>
                            <option value="performance">Análisis de Rendimiento</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Período</label>
                        <select id="reportPeriod">
                            <option value="week">Última semana</option>
                            <option value="month">Último mes</option>
                            <option value="quarter">Último trimestre</option>
                            <option value="year">Último año</option>
                            <option value="custom">Personalizado</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Formato</label>
                        <select id="reportFormat">
                            <option value="pdf">PDF</option>
                            <option value="excel">Excel</option>
                            <option value="csv">CSV</option>
                        </select>
                    </div>
                    
                    <div class="form-actions">
                        <button class="btn btn-secondary" onclick="closeModal('reportsModal')">Cancelar</button>
                        <button class="btn btn-primary" onclick="downloadReport()">
                            <i class="fas fa-download"></i> Descargar
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Modal de Configuración -->
        <div id="settingsModal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3><i class="fas fa-cog"></i> Configuración de Cuenta</h3>
                    <button class="close-modal" onclick="closeModal('settingsModal')">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="settings-content">
                        <div class="settings-section account-selector-section">
                            <h4>Seleccionar cuenta activa</h4>
                            <div class="form-group">
                                <label for="accountSelector">Cuenta</label>
                                <select id="accountSelector">
                                    <?php if (!empty($webtraderConfig['accounts'])): ?>
                                        <?php foreach ($webtraderConfig['accounts'] as $acc): ?>
                                            <option value="<?php echo htmlspecialchars($acc['account_number']); ?>">
                                                #<?php echo htmlspecialchars($acc['account_number']); ?> · <?php echo htmlspecialchars(ucfirst($acc['account_type'])); ?> · <?php echo htmlspecialchars($acc['currency']); ?> · Bal: <?php echo number_format((float)$acc['balance'], 2); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <option value="">Sin cuentas activas</option>
                                    <?php endif; ?>
                                </select>
                                <small class="form-text">Esta selección filtra posiciones, órdenes y estado de cuenta.</small>
                            </div>
                        </div>
                        <div class="settings-section">
                            <h4>Preferencias de Trading</h4>
                            <div class="form-group">
                                <label>Apalancamiento Máximo</label>
                                <select>
                                    <option>1:50</option>
                                    <option selected>1:100</option>
                                    <option>1:200</option>
                                    <option>1:500</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>
                                    <input type="checkbox" checked> Confirmación de órdenes
                                </label>
                                <small class="form-text">Solicitar confirmación antes de ejecutar órdenes</small>
                            </div>
                            <div class="form-group">
                                <label>
                                    <input type="checkbox"> Auto-cerrar posiciones en pérdida
                                </label>
                                <small class="form-text">Cerrar automáticamente cuando se alcance el stop loss</small>
                            </div>
                        </div>
                        
                        <div class="settings-section">
                            <h4>Notificaciones</h4>
                            <div class="form-group">
                                <label>
                                    <input type="checkbox" checked> Notificaciones por email
                                </label>
                            </div>
                            <div class="form-group">
                                <label>
                                    <input type="checkbox" checked> Alertas de precio
                                </label>
                            </div>
                            <div class="form-group">
                                <label>
                                    <input type="checkbox"> Notificaciones push
                                </label>
                            </div>
                        </div>
                        
                        <div class="settings-section">
                            <h4>Seguridad</h4>
                            <div class="form-group">
                                <label>
                                    <input type="checkbox" checked> Autenticación de dos factores
                                </label>
                                <small class="form-text">Recomendado para mayor seguridad</small>
                            </div>
                            <div class="form-group">
                                <label>Tiempo de sesión (minutos)</label>
                                <select>
                                    <option>15</option>
                                    <option selected>30</option>
                                    <option>60</option>
                                    <option>120</option>
                                </select>
                            </div>
                        </div>

                        <div class="settings-section">
                            <h4>Cambiar Contraseña</h4>
                            <div class="form-group">
                                <label for="wtCurrentPassword">Contraseña actual</label>
                                <input type="password" id="wtCurrentPassword" autocomplete="current-password" placeholder="********">
                            </div>
                            <div class="form-group">
                                <label for="wtNewPassword">Nueva contraseña</label>
                                <input type="password" id="wtNewPassword" autocomplete="new-password" placeholder="********">
                            </div>
                            <div class="form-group">
                                <label for="wtConfirmPassword">Confirmar nueva contraseña</label>
                                <input type="password" id="wtConfirmPassword" autocomplete="new-password" placeholder="********">
                                <small class="form-text" id="wtPwdMsg" style="display:none"></small>
                            </div>
                            <div class="form-actions">
                                <button class="btn btn-primary" id="wtChangePwdBtn"><i class="fas fa-key"></i> Actualizar Contraseña</button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-actions">
                        <button class="btn btn-secondary" onclick="closeModal('settingsModal')">Cancelar</button>
                        <button class="btn btn-success" onclick="saveSettings()">
                            <i class="fas fa-save"></i> Guardar Cambios
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Modal de Error de Orden -->
        <div id="orderErrorModal" class="modal" aria-labelledby="orderErrorTitle" role="dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 id="orderErrorTitle"><i class="fas fa-exclamation-circle"></i> Error al ejecutar la orden</h3>
                    <button class="close-modal" onclick="closeModal('orderErrorModal')" aria-label="Cerrar">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>Mensaje</label>
                        <div id="orderErrorMessage"></div>
                    </div>
                    <div class="form-group">
                        <label>Detalles</label>
                        <pre id="orderErrorDetails" style="white-space:pre-wrap"></pre>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeModal('orderErrorModal')">Cerrar</button>
                </div>
            </div>
        </div>

        <!-- Modal Confirmación Quick Order -->
        <div id="quickOrderConfirmModal" class="modal" aria-labelledby="quickOrderTitle" role="dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 id="quickOrderTitle"><i class="fas fa-check-circle"></i> Confirmar operación</h3>
                    <button class="close-modal" onclick="closeModal('quickOrderConfirmModal')" aria-label="Cerrar">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>Símbolo</label>
                        <div id="qoSymbol">—</div>
                    </div>
                    <div class="form-group">
                        <label>Dirección</label>
                        <div id="qoSide">—</div>
                    </div>
                    <div class="form-group">
                        <label>Volumen</label>
                        <div id="qoVolume">—</div>
                    </div>
                    <div class="form-group">
                        <label>Precio</label>
                        <div id="qoPrice">—</div>
                    </div>
                    <div class="form-group" style="margin-top:8px">
                        <label class="wt-checkbox"><input type="checkbox" id="qoDontShow"><span class="checkbox-ui" aria-hidden="true"></span> No mostrar más</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" id="qoCancelBtn" onclick="closeModal('quickOrderConfirmModal')">Cancelar</button>
                    <button class="btn btn-primary" id="qoConfirmBtn">Confirmar</button>
                </div>
            </div>
        </div>

        <!-- Modal de Advertencias de Orden -->
        <div id="orderWarningModal" class="modal" aria-labelledby="orderWarnTitle" role="dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 id="orderWarnTitle"><i class="fas fa-info-circle"></i> Orden ejecutada con advertencias</h3>
                    <button class="close-modal" onclick="closeModal('orderWarningModal')" aria-label="Cerrar">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>Mensaje</label>
                        <div id="orderWarnMessage"></div>
                    </div>
                    <div class="form-group">
                        <label>Detalles</label>
                        <pre id="orderWarnDetails" style="white-space:pre-wrap"></pre>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeModal('orderWarningModal')">Cerrar</button>
                </div>
            </div>
        </div>

        <!-- Modal Mercado Cerrado -->
        <div id="marketClosedModal" class="modal" aria-labelledby="marketClosedTitle" role="dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 id="marketClosedTitle"><i class="fas fa-store"></i> Mercado cerrado</h3>
                    <button class="close-modal" onclick="closeModal('marketClosedModal')" aria-label="Cerrar">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <div id="marketClosedMessage">Este activo no está disponible para operar en este momento.</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeModal('marketClosedModal')">Entendido</button>
                </div>
            </div>
        </div>

        <!-- Modal de Depósito -->
        <div id="depositModal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3><i class="fas fa-plus-circle"></i> Realizar Depósito</h3>
                    <button class="close-modal" onclick="closeModal('depositModal')">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="balance-info">
                        <div class="balance-item">
                            <span class="label">Balance Actual</span>
                            <span class="value">$10,250.00</span>
                        </div>
                        <div class="balance-item">
                            <span class="label">Equity</span>
                            <span class="value">$10,387.50</span>
                        </div>
                    </div>
                    
                    <form class="deposit-form">
                        <div class="form-group">
                            <label>Método de Pago</label>
                            <div class="method-tiles" id="depositMethods"></div>
                        </div>
                        <!-- País de operación eliminado -->
                        
                        <div class="form-group">
                            <label>Monto a Depositar</label>
                            <input type="number" id="depositAmount" placeholder="0.00" min="10" step="0.01">
                            <small class="form-text" id="depositMinText">Monto mínimo: 10 USD</small>
                        </div>
                        
                    <div class="deposit-info">
                        <div class="info-item">
                            <i class="fas fa-clock"></i>
                            <span>Procesamiento instantáneo para tarjetas</span>
                        </div>
                        <div class="info-item">
                            <i class="fas fa-shield-alt"></i>
                            <span>Transacciones 100% seguras y encriptadas</span>
                        </div>
                        <div class="info-item">
                            <i class="fas fa-percent"></i>
                            <span>Sin comisiones por depósito</span>
                        </div>
                    </div>
                    
                        
                        <div class="form-actions">
                            <button type="button" class="btn btn-secondary" onclick="closeModal('depositModal')">Cancelar</button>
                            <button type="submit" class="btn btn-success" onclick="processDeposit(event)">
                                <i class="fas fa-credit-card"></i> Procesar Depósito
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Modal de Retiro -->
        <div id="withdrawModal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3><i class="fas fa-minus-circle"></i> Solicitar Retiro</h3>
                    <button class="close-modal" onclick="closeModal('withdrawModal')">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="balance-info">
                        <div class="balance-item">
                            <span class="label">Balance Disponible</span>
                            <span class="value">$10,250.00</span>
                        </div>
                        <div class="balance-item">
                            <span class="label">Margen Usado</span>
                            <span class="value">$1,250.00</span>
                        </div>
                        <div class="balance-item">
                            <span class="label">Disponible para Retiro</span>
                            <span class="value">$9,000.00</span>
                        </div>
                    </div>
                    
                    <form class="withdraw-form">
                        <div class="form-group">
                            <label>Método de Retiro</label>
                            <div class="method-tiles" id="withdrawMethods">
                                <label class="method-tile" data-value="bank"><input class="method-input" type="radio" name="withdrawMethod" value="bank"><i class="fas fa-university"></i><span>Transferencia</span></label>
                                <label class="method-tile" data-value="card"><input class="method-input" type="radio" name="withdrawMethod" value="card"><i class="fas fa-credit-card"></i><span>Tarjeta</span></label>
                                <label class="method-tile" data-value="paypal"><input class="method-input" type="radio" name="withdrawMethod" value="paypal"><i class="fab fa-paypal"></i><span>PayPal</span></label>
                                <label class="method-tile" data-value="crypto"><input class="method-input" type="radio" name="withdrawMethod" value="crypto"><i class="fas fa-coins"></i><span>Cripto</span></label>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label>Monto a Retirar</label>
                            <input type="number" id="withdrawAmount" placeholder="0.00" min="50" max="9000" step="0.01">
                            <small class="form-text">Monto mínimo: $50.00 | Máximo disponible: $9,000.00</small>
                        </div>
                        
                        <div class="withdraw-info">
                            <div class="info-item">
                                <i class="fas fa-clock"></i>
                                <span>Procesamiento en 1-3 días hábiles</span>
                            </div>
                            <div class="info-item">
                                <i class="fas fa-shield-alt"></i>
                                <span>Verificación de identidad requerida</span>
                            </div>
                            <div class="info-item">
                                <i class="fas fa-exclamation-triangle"></i>
                                <span>Comisión del 2% para retiros menores a $500</span>
                            </div>
                        </div>
                        <div class="txn-recent" id="withdrawRecent">
                            <div class="txn-title">Movimientos recientes</div>
                            <div class="txn-list"></div>
                        </div>
                        
                        <div class="form-actions">
                            <button type="button" class="btn btn-secondary" onclick="closeModal('withdrawModal')">Cancelar</button>
                            <button type="submit" class="btn btn-warning" onclick="processWithdraw(event)">
                                <i class="fas fa-money-bill-wave"></i> Solicitar Retiro
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
        <!-- Modal de Recomendaciones de Margen -->
        <div id="mlRecommendationsModal" class="modal" aria-labelledby="mlRecTitle" aria-modal="true" role="dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 id="mlRecTitle">Recomendaciones de Margen</h3>
                    <button class="close-modal" onclick="closeModal('mlRecommendationsModal')" aria-label="Cerrar">&times;</button>
                </div>
                <div class="modal-body">
                    <p id="mlRecIntro">Te mostramos acciones sugeridas según tu nivel de margen.</p>
                    <ul id="mlRecList" class="rec-list">
                        <li>Reducir tamaño de nuevas órdenes para controlar el riesgo.</li>
                        <li>Revisar posiciones con pérdidas y considerar cerrarlas.</li>
                        <li>Agregar fondos si planeas incrementar exposición.</li>
                    </ul>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal('mlRecommendationsModal')">Cerrar</button>
                </div>
            </div>
        </div>
            <div class="brand-text">WebTrader Pro</div>
        </div>
        
        <!-- Control de cuenta (fuera de KPIs) -->
        <!-- account-control eliminado por solicitud -->

        <div class="account-summary" aria-label="KPIs de cuenta">
            <div class="account-item">
                <div class="label">Beneficio</div>
                <div class="value profit">$<?php echo number_format($account_info['profit_loss'] ?? 0, 2); ?></div>
            </div>
            <div class="account-item">
                <div class="label">Capital</div>
                <div class="value equity">$<?php echo number_format($account_info['equity'] ?? 0, 2); ?></div>
            </div>
            <div class="account-item">
                <div class="label">Balance</div>
                <div class="value balance">$<?php echo number_format($account_info['balance'] ?? 0, 2); ?></div>
            </div>
            <div class="account-item">
                <div class="label">Fondos libres</div>
                <div class="value free-margin">$<?php echo number_format(($account_info['free_margin'] ?? (($account_info['equity'] ?? 0) - ($account_info['margin'] ?? 0))), 2); ?></div>
            </div>
            <div class="account-item">
                <div class="label">Margen</div>
                <div class="value margin">$<?php echo number_format($account_info['margin'] ?? 0, 2); ?></div>
            </div>
            <div class="account-item">
                <div class="label">Nivel de margen</div>
                <div class="value margin-level"><?php echo number_format(($account_info['margin'] ?? 0) > 0 ? ((($account_info['equity'] ?? 0)/($account_info['margin'] ?? 1))*100) : 0, 2); ?>%</div>
            </div>
        </div>
        
        <div class="header-right">
            <!-- Estado de conexión (badge de lujo) -->
            <div class="status-area">
                <div class="connection-pill disconnected" id="headerConnectionStatus" title="Estado del servidor">
                    <i class="fas fa-plug"></i>
                    <span class="status-text">Desconectado</span>
                    <span class="latency" id="connectionLatency">—</span>
                </div>
            </div>
            
            <div class="header-actions">
                <!-- Botón de Depósito reinstalado -->
                <div class="trading-actions">
                    <button class="btn btn-lg btn-success action-btn deposit-btn btn-unified" id="depositBtn" title="Realizar Depósito" aria-label="Realizar Depósito" onclick="showDeposit()">
                        <i class="fas fa-plus-circle"></i>
                        <span>Depósito</span>
                    </button>
                </div>
                
                <!-- Botones de Herramientas -->
                <div class="tool-actions">
                    <button class="header-btn btn-icon" id="alertsBtn" title="Alertas de Precio">
                        <i class="fas fa-bell"></i>
                        <span class="alert-badge" id="alertCount">0</span>
                    </button>

                    <!-- Toggle de Tema -->
                    <button class="header-btn btn-icon" id="themeToggle" title="Cambiar tema">
                        <i id="themeIcon" class="fas fa-sun"></i>
                    </button>

                    <button class="header-btn btn-icon" id="settingsBtn" title="Configuración">
                        <i class="fas fa-cog"></i>
                    </button>
                </div>
                
                <!-- Menú de Usuario Mejorado -->
                <div class="user-menu">
                    <button class="user-menu-btn" id="userMenuBtn" aria-haspopup="menu" aria-expanded="false" aria-controls="userDropdown">
                        <div class="user-avatar">
                            <i class="fas fa-user-circle"></i>
                        </div>
                        <div class="user-info">
                            <span class="user-name"><?php 
                                $name = trim((($client['first_name'] ?? '') . ' ' . ($client['last_name'] ?? '')));
                                echo htmlspecialchars($name !== '' ? $name : 'Invitado');
                            ?></span>
                            <span class="user-email"><?php echo htmlspecialchars($client['email'] ?? '—'); ?></span>
                        </div>
                        <i class="fas fa-chevron-down dropdown-arrow"></i>
                    </button>
                    
                    <div class="user-dropdown" id="userDropdown" role="menu" aria-label="Menú de usuario">
                        <div class="dropdown-header">
                            <div class="user-avatar-large">
                                <i class="fas fa-user-circle"></i>
                            </div>
                            <div class="user-details">
                                <div class="user-name"><?php 
                                    $name = trim((($client['first_name'] ?? '') . ' ' . ($client['last_name'] ?? '')));
                                    echo htmlspecialchars($name !== '' ? $name : 'Invitado');
                                ?></div>
                                <div class="user-email"><?php echo htmlspecialchars($client['email'] ?? '—'); ?></div>
                            </div>
                        </div>
                        
                        <div class="dropdown-divider"></div>
                        
                        <!-- Preferencias rápidas con checkboxes accesibles -->
                        <div class="dropdown-item" role="none">
                            <label class="wt-checkbox" role="menuitemcheckbox">
                                <input type="checkbox" id="denseModeToggle" aria-checked="false" />
                                <span class="checkbox-ui" aria-hidden="true"></span>
                                <span>Modo denso en Market Watch</span>
                            </label>
                        </div>
                        <div class="dropdown-item" role="none">
                            <label class="wt-checkbox" role="menuitemcheckbox">
                                <input type="checkbox" id="soundAlertsToggle" aria-checked="false" />
                                <span class="checkbox-ui" aria-hidden="true"></span>
                                <span>Sonido en alertas</span>
                            </label>
                        </div>
                        
                        <div class="dropdown-divider"></div>
                        
                        <a href="<?php echo module_url('client_portal', 'logout.php'); ?>" class="dropdown-item logout logout-blue">
                            <i class="fas fa-sign-out-alt"></i>
                            <span>Cerrar Sesión</span>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </header>

    <!-- WebTrader Main Content -->
    <main class="webtrader-main">
        <?php 
        // Incluir el contenido específico del WebTrader
        if (file_exists('webtrader_content.php')) {
            include 'webtrader_content.php';
        }
        ?>
    </main>

    <!-- Panel lateral: Order Ticket -->
    <aside id="orderTicket" class="order-ticket" aria-hidden="true">
        <div class="order-ticket-header">
            <h4>Order Ticket</h4>
            <button id="orderTicketCloseBtn" class="close-modal" aria-label="Cerrar">
                &times;
            </button>
        </div>
        <div class="order-ticket-body">
            <form id="orderForm">
                <div class="form-row">
                    <label for="orderSymbol">Símbolo</label>
                    <select id="orderSymbol" name="symbol">
                        <option>EURUSD</option>
                        <option>GBPUSD</option>
                        <option>USDJPY</option>
                        <option>USDCAD</option>
                        <option>USDCHF</option>
                    </select>
                </div>
                <div class="form-row">
                    <label for="orderSide">Dirección</label>
                    <div class="side-toggle">
                        <input type="radio" id="sideBuy" name="side" value="BUY" checked>
                        <label for="sideBuy" class="btn btn-success">Buy</label>
                        <input type="radio" id="sideSell" name="side" value="SELL">
                        <label for="sideSell" class="btn btn-outline-danger">Sell</label>
                    </div>
                </div>
                <div class="form-row">
                    <label for="orderType">Tipo</label>
                    <select id="orderType" name="type">
                        <option value="market" selected>Market</option>
                        <option value="limit">Limit</option>
                        <option value="stop">Stop</option>
                    </select>
                </div>
                <div class="form-row">
                    <label for="orderVolume">Volumen</label>
                    <input id="orderVolume" name="volume" type="number" step="0.01" min="0.01" value="0.10">
                </div>
                <div class="form-row">
                    <label for="orderPrice">Precio</label>
                    <input id="orderPrice" name="price" type="number" step="0.00001" placeholder="Auto para Market">
                </div>
                <div class="form-row grid-2">
                    <div>
                        <label for="orderSL">Stop Loss</label>
                        <input id="orderSL" name="stop_loss" type="number" step="0.00001">
                    </div>
                    <div>
                        <label for="orderTP">Take Profit</label>
                        <input id="orderTP" name="take_profit" type="number" step="0.00001">
                    </div>
                </div>
                <div class="order-summary">
                    <div class="summary-item">
                        <span>Margin Requerido:</span>
                        <span id="required-margin">$0.00</span>
                    </div>
                    <div class="summary-item">
                        <span>Valor del Pip:</span>
                        <span id="pip-value">$0.00</span>
                    </div>
                </div>
                <div class="order-actions">
                    <button type="button" class="btn btn-secondary" id="orderCancelBtn">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Ejecutar Orden</button>
                </div>
            </form>
        </div>
    </aside>

    <!-- Placeholder para compatibilidad con JS existente -->
    <div id="orderModal" style="display:none"></div>

    <!-- WebTrader Footer -->
    <footer class="webtrader-footer">
        <div class="footer-left">
            <span class="connection-status" id="connectionStatus">
                <i class="fas fa-circle connected"></i>
                Conectado
            </span>
            <span class="server-time" id="serverTime">
                <?php echo date('H:i:s T'); ?>
            </span>
        </div>
        
        <div class="footer-center">
            <span class="market-status" id="marketStatus">
                <i class="fas fa-clock"></i>
                Mercado Abierto
            </span>
        </div>
        
        <div class="footer-right">
            <span class="version">
                WebTrader v1.0
            </span>
        </div>
    </footer>

    <!-- JavaScript Files -->
    <script src="/simple_crm/modules/webtrader/js/websocket-client.js"></script>
    <script src="webtrader_app.js"></script>
    <script>
        // Inicializar datos del cliente
        window.clientData = {
            id: <?php echo json_encode($_SESSION['client_id']); ?>,
            name: <?php echo json_encode($_SESSION['client_name'] ?? 'Cliente'); ?>,
            email: <?php echo json_encode($_SESSION['client_email'] ?? ''); ?>,
            status: <?php echo json_encode($_SESSION['client_status'] ?? 'active'); ?>
        };
        
        // Actualizar tiempo del servidor cada segundo
        function updateServerTime() {
            const now = new Date();
            const timeString = now.toLocaleString('es-ES', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
            
            const timeElement = document.getElementById('server-time');
            if (timeElement) {
                timeElement.textContent = timeString;
            }
        }
        
        // Inicializar cuando el DOM esté listo
        document.addEventListener('DOMContentLoaded', function() {
            // Configuración del cliente desde PHP
            window.webtraderConfig = <?php echo json_encode($webtraderConfig ?? []); ?>;
            window.webtraderConfig.mw_smooth_steps = 12;
            
            // Actualizar tiempo inicial
            updateServerTime();
            setInterval(updateServerTime, 1000);
            
            // Inicializar WebSocket Client con URL de configuración
        // Construir URL de WebSocket de forma dinámica según el entorno
        const wsProto = window.location.protocol === 'https:' ? 'wss' : 'ws';
        const wsHost = window.location.hostname;
        const wsPort = window.webtraderConfig.websocket_port || 8082;
        let wsUrl = window.webtraderConfig.websocket_url || `${wsProto}://${wsHost}:${wsPort}`;
        <?php
        require_once BASE_PATH . '/modules/webtrader/finage_api.php';
        $api = getFinageAPI();
        $subs = $api->getWebSocketSubscriptions(true, true, false, false, false);
        $finageWsUrl = null;
        $stockSymbols = [];
        if (is_array($subs) && count($subs) > 0) {
            foreach ($subs as $s) {
                // Preferir servidor de US Stocks si disponible
                if (strpos(($s['url'] ?? ''), 'xs68rzvrjn.finage.ws:7003') !== false) {
                    $finageWsUrl = $s['url'] . '?token=' . $s['token'];
                    $stockSymbols = $s['symbols'] ?? [];
                    break;
                }
            }
            // Fallback: usar primer sub si no se encontró el de stocks
            if (!$finageWsUrl) {
                $finageWsUrl = $subs[0]['url'] . '?token=' . $subs[0]['token'];
                $stockSymbols = $subs[0]['symbols'] ?? [];
            }
        }
        ?>
        <?php if (!empty($finageWsUrl)) { ?>
        window.webtraderConfig.websocket_mode = 'finage';
        window.webtraderConfig.auto_subscribe = false;
        window.wsClients = [];
        <?php
            $idx = 0;
            foreach ($subs as $s) {
                $url = $s['url'] . '?token=' . $s['token'];
                $symbolsJson = json_encode($s['symbols'] ?? []);
                echo "window.wsClients.push(new WebSocketClient('{$url}'));\n";
                echo "window.wsClients[{$idx}].__symbols = {$symbolsJson};\n";
                $idx++;
            }
        ?>
        // Compatibilidad: usar el primero como principal
        window.wsClient = window.wsClients[0];
        <?php } else { ?>
        window.wsClient = new WebSocketClient(wsUrl);
        window.wsClients = [window.wsClient];
        <?php } ?>
            
            // Configurar eventos WebSocket
            window.wsClient.on('connected', function() {
                console.log('WebSocket conectado exitosamente');
                showNotification('Conectado al servidor en tiempo real', 'success');
                const headerStatus = document.getElementById('headerConnectionStatus');
                if (headerStatus) {
                    headerStatus.classList.remove('disconnected');
                    headerStatus.classList.add('connected');
                    const statusText = headerStatus.querySelector('.status-text');
                    if (statusText) statusText.textContent = 'Conectado';
                }
                // Iniciar medición de latencia
                const latEl = document.getElementById('connectionLatency');
                if (latEl) {
                    window.__wtPingStart = null;
                    if (window.__wtPingInterval) clearInterval(window.__wtPingInterval);
                    window.__wtPingInterval = setInterval(() => {
                        window.__wtPingStart = performance.now();
                        try { window.wsClient.ping(); } catch (e) {}
                    }, 5000);
                }
            });
            
            window.wsClient.on('disconnected', function() {
                console.log('WebSocket desconectado');
                showNotification('Desconectado del servidor', 'warning');
                const headerStatus = document.getElementById('headerConnectionStatus');
                if (headerStatus) {
                    headerStatus.classList.remove('connected');
                    headerStatus.classList.add('disconnected');
                    const statusText = headerStatus.querySelector('.status-text');
                    if (statusText) statusText.textContent = 'Desconectado';
                }
                const latEl = document.getElementById('connectionLatency');
                if (latEl) {
                    latEl.textContent = '—';
                    if (window.__wtPingInterval) clearInterval(window.__wtPingInterval);
                }
            });
            
            window.wsClient.on('authenticated', function() {
                console.log('WebSocket autenticado');
                // Suscribirse a símbolos por defecto del cliente
                const symbols = window.webtraderConfig.default_symbols || ['EURUSD', 'GBPUSD'];
                symbols.forEach(symbol => {
                    window.wsClient.subscribe('prices', symbol);
                });
                // Suscribir cuenta activa del cliente (enviamos account_number como 'symbol')
                let activeAcc = null;
                try {
                    activeAcc = (typeof localStorage !== 'undefined' && localStorage.getItem('webtrader-active-account')) || null;
                } catch (e) {}
                if (!activeAcc && Array.isArray(window.webtraderConfig.accounts) && window.webtraderConfig.accounts[0]) {
                    activeAcc = window.webtraderConfig.accounts[0].account_number || null;
                }
                window.wsClient.subscribe('account', activeAcc);
            });

            // Actualizar latencia cuando llegue pong
            if (window.wsClient && typeof window.wsClient.on === 'function') {
                window.wsClient.on('pong', function() {
                    const latEl = document.getElementById('connectionLatency');
                    if (!latEl || !window.__wtPingStart) return;
                    const ms = Math.round(performance.now() - window.__wtPingStart);
                    latEl.textContent = ms + ' ms';
                });
            }
            
            // Inicializar WebTrader con configuración del cliente (evitar doble instancia)
            if (typeof WebTraderApp !== 'undefined') {
                if (!window.webTraderApp) {
                    window.webTraderApp = new WebTraderApp(window.webtraderConfig);
                }
                // Conectar múltiples WebSockets con WebTrader
                if (window.wsClients && window.webTraderApp && typeof window.webTraderApp.setWebSocketClients === 'function') {
                    window.webTraderApp.setWebSocketClients(window.wsClients);
                } else if (window.wsClient && window.webTraderApp && typeof window.webTraderApp.setWebSocketClient === 'function') {
                    window.webTraderApp.setWebSocketClient(window.wsClient);
                }
                if (typeof window.webTraderApp.initializeAlertBadge === 'function') {
                    window.webTraderApp.initializeAlertBadge();
                }
            }
            
            // Manejar menú de usuario (usar clase 'show' para CSS de transición)
            const userMenuBtn = document.getElementById('userMenuBtn');
            const userDropdown = document.getElementById('userDropdown');
            if (userMenuBtn && userDropdown) {
                userMenuBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    const isOpen = userDropdown.classList.contains('show');
                    userDropdown.classList.toggle('show', !isOpen);
                    userMenuBtn.setAttribute('aria-expanded', (!isOpen).toString());
                });
                // Cerrar al hacer clic fuera
                document.addEventListener('click', function(e) {
                    const clickedInsideDropdown = userDropdown.contains(e.target);
                    const clickedButton = userMenuBtn.contains(e.target);
                    if (!clickedInsideDropdown && !clickedButton && userDropdown.classList.contains('show')) {
                        userDropdown.classList.remove('show');
                        userMenuBtn.setAttribute('aria-expanded', 'false');
                    }
                });
                // Cerrar con tecla ESC
                document.addEventListener('keydown', function(e) {
                    if (e.key === 'Escape' && userDropdown.classList.contains('show')) {
                        userDropdown.classList.remove('show');
                        userMenuBtn.setAttribute('aria-expanded', 'false');
                    }
                });
            }
        });
        
        // Función para mostrar notificaciones
        function showNotification(message, type = 'info') {
            const notification = document.createElement('div');
            notification.className = `notification notification-${type}`;
            notification.textContent = message;
            
            // Estilos inline para la notificación
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 12px 20px;
                border-radius: 4px;
                color: white;
                font-weight: 500;
                z-index: 10000;
                opacity: 0;
                transition: opacity 0.3s ease;
            `;
            
            // Colores según el tipo
            const colors = {
                success: '#28a745',
                warning: '#ffc107',
                error: '#dc3545',
                info: '#17a2b8'
            };
            
            notification.style.backgroundColor = colors[type] || colors.info;
            
            document.body.appendChild(notification);
            
            // Mostrar con animación
            setTimeout(() => {
                notification.style.opacity = '1';
            }, 100);
            
            // Ocultar después de 3 segundos
            setTimeout(() => {
                notification.style.opacity = '0';
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 300);
            }, 3000);
        }
    </script>
    <script>
        // Efecto ripple para botones de acción y header
        document.addEventListener('DOMContentLoaded', function() {
            const targets = document.querySelectorAll('.action-btn, .header-btn');
            targets.forEach(btn => {
                btn.addEventListener('click', function(e) {
                    const rect = btn.getBoundingClientRect();
                    const circle = document.createElement('span');
                    circle.className = 'ripple-circle';
                    const size = Math.max(rect.width, rect.height);
                    const x = e.clientX - rect.left - size / 2;
                    const y = e.clientY - rect.top - size / 2;
                    circle.style.width = circle.style.height = size + 'px';
                    circle.style.left = x + 'px';
                    circle.style.top = y + 'px';
                    btn.appendChild(circle);
                    setTimeout(() => { if (circle.parentNode) circle.parentNode.removeChild(circle); }, 500);
                });
            });
        });
    </script>
<script>
            // Funciones globales para los modales
            function openModal(modalId) {
                if (window.webTraderApp) {
                    window.webTraderApp.openModal(modalId);
                }
            }

            function closeModal(modalId) {
                if (window.webTraderApp) {
                    window.webTraderApp.closeModal(modalId);
                }
            }

            function showProfile() {
                if (window.webTraderApp) {
                    window.webTraderApp.showProfile();
                }
            }

            function showHistory() {
                if (window.webTraderApp) {
                    window.webTraderApp.showHistory();
                }
            }

            function showReports() {
                if (window.webTraderApp) {
                    window.webTraderApp.showReports();
                }
            }

            function showSettings() {
                if (window.webTraderApp) {
                    window.webTraderApp.showSettings();
                }
            }

            function showDeposit() {
                if (window.webTraderApp) {
                    window.webTraderApp.showDeposit();
                    return;
                }
                var modal = document.getElementById('depositModal');
                if (modal) {
                    modal.classList.add('active');
                    document.body.style.overflow = 'hidden';
                    document.body.classList.add('modal-open');
                    var tiles = document.getElementById('depositMethods');
                    if (tiles && tiles.getAttribute('data-loaded') !== '1') tiles.innerHTML = '<div class="skeleton" style="height:96px;border-radius:8px"></div>';
                    var minEl = document.getElementById('depositMinText');
                    if (minEl) minEl.textContent = 'Monto mínimo: 10 USD';
                    var amt = document.getElementById('depositAmount');
                    if (amt) amt.placeholder = '0.00 USD';
                    // Cargar métodos inmediatamente desde BD (fallback)
                    (function(){
                        var cur = 'USD';
                        try { if (window.webTraderApp && window.webTraderApp.accountData && window.webTraderApp.accountData.account && window.webTraderApp.accountData.account.currency) cur = String(window.webTraderApp.accountData.account.currency).toUpperCase(); } catch(_){}
                        if (!tiles || tiles.getAttribute('data-loaded') === '1') return;
                        fetch('api/payment_methods.php?type=deposit&currency=' + encodeURIComponent(cur))
                          .then(function(r){ return r.json(); })
                          .then(function(j){
                              var methods = (j && j.success && Array.isArray(j.methods)) ? j.methods : [];
                              if (!tiles) return;
                              if (!methods.length) { tiles.innerHTML = '<div class="alert alert-info">No hay métodos activos configurados.</div>'; return; }
                              var html = methods.map(function(m){
                                  var val = String(m.provider_key || m.name || '').toLowerCase();
                                  var title = m.display_name || m.name || val;
                                  var logo = m.logo_path || '';
                                  var imgHtml = logo ? ('<img class="method-logo" src="'+logo+'" alt="'+title+'"/>') : '<i class="fas fa-credit-card"></i>';
                                  var curChip = '<span class="badge badge-info">'+cur+'</span>';
                                  return '<label class="method-tile" data-value="'+val+'"><input class="method-input" type="radio" name="depositMethod" value="'+val+'">'+imgHtml+'<span>'+title+'</span>'+curChip+'</label>';
                              }).join('');
                              tiles.innerHTML = html;
                              tiles.setAttribute('data-loaded','1');
                              tiles.querySelectorAll('.method-tile').forEach(function(el){
                                  el.addEventListener('click', function(){
                                      var inp = el.querySelector('input.method-input');
                                      if (inp) { inp.checked = true; }
                                      tiles.querySelectorAll('.method-tile').forEach(function(x){ x.classList.remove('selected'); });
                                      el.classList.add('selected');
                                      // Limpiar errores si existían
                                      var modalNode = document.getElementById('depositModal');
                                      modalNode && modalNode.querySelectorAll('.inline-error').forEach(function(n){ n.remove(); });
                                      // Habilitar botón si el monto es válido
                                      var amountVal = parseFloat((document.getElementById('depositAmount')||{}).value || '0');
                                      var submitBtn = document.querySelector('#depositModal .form-actions .btn-success');
                                      if (submitBtn) submitBtn.disabled = !(Number.isFinite(amountVal) && amountVal >= 10);
                                  });
                           });
                          })
                          .catch(function(){ if (tiles) tiles.innerHTML = '<div class="alert alert-error">Error cargando métodos</div>'; });
                    })();
                    // País de operación (Suramérica) - fallback inmediato
                    (function(){
                        var container = document.getElementById('depositCountrySelect');
                        if (!container) return;
                        var countries = [
                          {code:'MX',name:'Mexico',colors:['#006341','#FFFFFF','#CE1126']},
                          {code:'AR',name:'Argentina',colors:['#75AADB','#FFFFFF','#75AADB']},
                          {code:'BR',name:'Brazil',colors:['#009b3a','#fedf00','#002776']},
                          {code:'CL',name:'Chile',colors:['#0039A6','#FFFFFF','#D52B1E']},
                          {code:'CO',name:'Colombia',colors:['#FCD116','#003087','#C8102E']},
                          {code:'PE',name:'Peru',colors:['#D91023','#FFFFFF','#D91023']},
                          {code:'EC',name:'Ecuador',colors:['#FCD116','#003087','#C8102E']},
                          {code:'BO',name:'Bolivia',colors:['#D52B1E','#FCD116','#009B3A']},
                          {code:'UY',name:'Uruguay',colors:['#FFFFFF','#0038A8','#FFFFFF']}
                        ];
                        var html = countries.map(function(c){
                          var img = '<img class="flag-svg" src="assets/currency/'+c.name.toUpperCase()+'.svg" alt="'+c.name+'"/>';
                          return '<label class="country-chip" data-code="'+c.code+'"><input type="radio" name="depositCountry" value="'+c.code+'">'+img+'<span>'+c.name+'</span></label>';
                        }).join('');
                        container.innerHTML = html;
                        container.setAttribute('data-ready','1');
                        container.querySelectorAll('.country-chip').forEach(function(el){
                          el.addEventListener('click', function(){
                            var inp = el.querySelector('input[type="radio"]');
                            if (inp) inp.checked = true;
                            container.querySelectorAll('.country-chip').forEach(function(x){ x.classList.remove('selected'); });
                            el.classList.add('selected');
                          });
                        });
                      })();
                    // Sin reintentos: evitar re-render y parpadeos
                }
            }

            function showWithdraw() {
                if (window.webTraderApp) {
                    window.webTraderApp.showWithdraw();
                }
            }

            function downloadReport() {
                if (window.webTraderApp) {
                    window.webTraderApp.downloadReport();
                }
            }

            function saveSettings() {
                if (window.webTraderApp) {
                    window.webTraderApp.saveSettings();
                }
            }

            function processDeposit(event) {
                if (window.webTraderApp) {
                    window.webTraderApp.processDeposit(event);
                }
            }

            function processWithdraw(event) {
                if (window.webTraderApp) {
                    window.webTraderApp.processWithdraw(event);
                }
            }
        </script>
        <script>
            // Accesibilidad del menú de usuario y feedback visual
            (function(){
                const menuBtn = document.getElementById('userMenuBtn');
                const menu = document.getElementById('userDropdown');
                if (!menuBtn || !menu) return;
                function closeMenu(){ menu.classList.remove('show'); menuBtn.setAttribute('aria-expanded','false'); }
                function openMenu(){ menu.classList.add('show'); menuBtn.setAttribute('aria-expanded','true'); }
                menuBtn.addEventListener('click',function(){ menu.classList.contains('show') ? closeMenu() : openMenu(); });
                document.addEventListener('keydown',function(ev){ if(ev.key==='Escape') closeMenu(); });
                document.addEventListener('click',function(ev){ if(!menu.contains(ev.target) && !menuBtn.contains(ev.target)) closeMenu(); });
            })();

            // Checkboxes profesionales con persistencia
            (function(){
                function setChecked(el, checked){ if(!el) return; el.checked = checked; el.setAttribute('aria-checked', checked ? 'true':'false'); el.closest('.wt-checkbox')?.classList.toggle('checked', !!checked); }
                const denseToggle = document.getElementById('denseModeToggle');
                const soundToggle = document.getElementById('soundAlertsToggle');
                setChecked(denseToggle, localStorage.getItem('wt_dense') === '1');
                setChecked(soundToggle, localStorage.getItem('wt_sound') === '1');
                denseToggle?.addEventListener('change',function(){ const on = this.checked; localStorage.setItem('wt_dense', on ? '1':'0'); document.querySelector('.market-watch')?.classList.toggle('dense', on); });
                soundToggle?.addEventListener('change',function(){ const on = this.checked; localStorage.setItem('wt_sound', on ? '1':'0'); });
            })();

            // Validación en tiempo real para formularios del header (depósito/retiro)
            (function(){
                function attachValidation(modalId){
                    const modal = document.getElementById(modalId);
                    if (!modal) return;
                    const input = modal.querySelector('input[name="amount"], input.amount');
                    let error = modal.querySelector('.input-error');
                    if (!input) return;
                    if (!error){ error = document.createElement('div'); error.className = 'input-error'; error.setAttribute('aria-live','polite'); error.style.display = 'none'; input.parentElement?.appendChild(error); }
                    const setError = (msg)=>{ error.textContent = msg; error.style.display = msg ? 'block':'none'; };
                    input.addEventListener('input', function(){
                        const val = parseFloat(this.value);
                        if (!this.value) return setError('Requerido');
                        if (!Number.isFinite(val)) return setError('Número inválido');
                        if (val <= 0) return setError('Debe ser mayor a 0');
                        setError('');
                    });
                }
                attachValidation('depositModal');
                attachValidation('withdrawModal');
            })();
        </script>
</body>
<script>
(function(){
  function ping(){ try{ fetch('<?php echo module_url('api/client_presence.php'); ?>', { method:'POST' }).catch(function(){}); }catch(e){} }
  ping();
  setInterval(ping, 60000);
})();
</script>
</html>
