<?php
/**
 * Contenido de Leads para layout corporativo
 * Usa variables definidas en index.php: $leads, $stats, filtros y helpers
 */
// Helper para clases de badge de estado
function statusBadgeClasses($status) {
    $map = [
        'new' => 'bg-blue-100 text-blue-800',
        'contacted' => 'bg-yellow-100 text-yellow-800',
        'qualified' => 'bg-green-100 text-green-800',
        'demo_scheduled' => 'bg-purple-100 text-purple-800',
        'demo_completed' => 'bg-indigo-100 text-indigo-800',
        'deposit_pending' => 'bg-orange-100 text-orange-800',
        'deposited' => 'bg-emerald-100 text-emerald-800',
        'active_trader' => 'bg-teal-100 text-teal-800',
        'inactive' => 'bg-gray-100 text-gray-800',
        'closed_lost' => 'bg-red-100 text-red-800'
    ];
    return $map[$status] ?? 'bg-gray-100 text-gray-800';
}

// Helper para etiqueta amigable del status en el filtro
function statusLabel($status) {
    $labels = [
        'new' => 'Nuevo',
        'contacted' => 'Contactado',
        'qualified' => 'Calificado',
        'demo_scheduled' => 'Demo Programado',
        'demo_completed' => 'Demo Completado',
        'deposit_pending' => 'Depósito Pendiente',
        'deposited' => 'Con Depósito',
        'active_trader' => 'Trader Activo',
        'inactive' => 'Inactivo',
        'closed_lost' => 'Perdido',
        'converted' => 'Convertido'
    ];
    if (isset($labels[$status])) return $labels[$status];
    // Fallback: capitalizar y reemplazar guiones bajos por espacios
    $label = ucwords(str_replace('_', ' ', (string)$status));
    return $label;
}
?>

<?php
// Helpers de enmascarado
function maskGeneric($value, $first = 3, $last = 2) {
    $v = (string)$value;
    $len = strlen($v);
    if ($len <= ($first + $last)) { return str_repeat('*', max(0, $len)); }
    $start = substr($v, 0, $first);
    $end = substr($v, -$last);
    return $start . str_repeat('*', $len - ($first + $last)) . $end;
}

function maskEmail($email, $first = 3, $last = 2) {
    $e = (string)$email;
    if (strpos($e, '@') === false) { return maskGeneric($e, $first, $last); }
    list($local, $domain) = explode('@', $e, 2);
    $localMasked = maskGeneric($local, $first, $last);
    // Mantener estructura del dominio, pero ocultar casi todo excepto los Ãºltimos 2 caracteres
    $domainLen = strlen($domain);
    if ($domainLen <= $last) {
        $domainMasked = str_repeat('*', max(0, $domainLen));
    } else {
        $domainMasked = str_repeat('*', $domainLen - $last) . substr($domain, -$last);
    }
    return $localMasked . '@' . $domainMasked;
}

function maskPhone($phone, $first = 3, $last = 2) {
    $digits = preg_replace('/\D+/', '', (string)$phone);
    $len = strlen($digits);
    if ($len === 0) { return ''; }
    $visibleStart = min($first, max(0, $len));
    $visibleEnd = min($last, max(0, $len - $visibleStart));
    $start = substr($digits, 0, $visibleStart);
    $end = substr($digits, -$visibleEnd);
    $maskedMid = str_repeat('*', max(0, $len - ($visibleStart + $visibleEnd)));
    return $start . $maskedMid . $end;
}
?>

<div class="leads-container">
    <div class="roles-header">
        <div class="header-left">
            <h1 class="page-title">
                <svg class="title-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/>
                    <circle cx="9" cy="7" r="4"/>
                    <path d="m22 2-5 10-5-5-5 10"/>
                </svg>
                Gestión de Leads
            </h1>
            <p class="page-subtitle">Administra y da seguimiento a tus prospectos de trading</p>
            <?php
            // Aviso de error si la vista de perfil redirige por id inválido o lead no encontrado
            $error_reason = isset($_GET['error']) ? trim($_GET['error']) : '';
            $error_lead_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
            if ($error_reason === 'invalid_id' || $error_reason === 'not_found'):
            ?>
            <div class="lead-error-banner" style="background:#FFF3CD;color:#856404;border:1px solid #FFE8A1;padding:10px 12px;border-radius:8px;margin-top:12px;display:flex;align-items:center;gap:8px;">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="12" cy="12" r="10"/>
                    <line x1="12" y1="8" x2="12" y2="12"/>
                    <line x1="12" y1="16" x2="12" y2="16"/>
                </svg>
                <span>
                    <?php if ($error_reason === 'invalid_id'): ?>
                        ID de lead inválido.
                    <?php elseif ($error_reason === 'not_found'): ?>
                        No se encontró el lead<?php echo $error_lead_id > 0 ? " (id $error_lead_id)" : ''; ?>.
                    <?php endif; ?>
                </span>
            </div>
            <?php endif; ?>
        </div>
        <div class="header-actions">
            <?php
            // Determinar permisos de crear e importar
            $canCreateLead = function_exists('userHasPermissionByName') ? userHasPermissionByName($pdo, 'leads.create', $current_user_id) : true;
            $canImportLeads = function_exists('userHasPermissionByName') ? userHasPermissionByName($pdo, 'leads.import', $current_user_id) : true;
            ?>
            <?php if ($canImportLeads): ?>
            <button class="btn-secondary" onclick="openImportModal()">
                <svg class="btn-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                    <polyline points="7,10 12,15 17,10"/>
                    <line x1="12" y1="15" x2="12" y2="3"/>
                </svg>
                <span class="btn-label">Importar leads</span>
            </button>
            <?php endif; ?>
            <a href="<?php echo route_url(['module'=>'clients']); ?>" class="btn-secondary">
                <svg class="btn-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/>
                    <circle cx="9" cy="7" r="4"/>
                </svg>
                <span class="btn-label">Ver Clientes</span>
            </a>
            <?php if ($canCreateLead): ?>
            <button class="btn-primary" onclick="openCreateModal()">
                <svg class="btn-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="12" y1="5" x2="12" y2="19"/>
                    <line x1="5" y1="12" x2="19" y2="12"/>
                </svg>
                <span class="btn-label">Nuevo lead</span>
            </button>
            <?php endif; ?>
        </div>
    </div>

    <div class="stats-grid">
        <div class="stat-card" data-stat-key="total">
            <div class="stat-icon bg-blue-500">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/>
                    <circle cx="9" cy="7" r="4"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo number_format($stats['total']); ?></div>
                <div class="stat-label">Total Leads</div>
            </div>
        </div>
        <div class="stat-card" data-stat-key="new">
            <div class="stat-icon bg-yellow-500">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="12" cy="12" r="10"/>
                    <path d="M12 6v6l4 2"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo number_format($stats['new']); ?></div>
                <div class="stat-label">Nuevos</div>
            </div>
        </div>
        <div class="stat-card" data-stat-key="qualified">
            <div class="stat-icon bg-green-500">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M9 12l2 2 4-4"/>
                    <circle cx="12" cy="12" r="10"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo number_format($stats['qualified']); ?></div>
                <div class="stat-label">Calificados</div>
            </div>
        </div>
        <div class="stat-card" data-stat-key="deposited">
            <div class="stat-icon bg-emerald-500">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="12" y1="1" x2="12" y2="23"/>
                    <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo number_format($stats['deposited']); ?></div>
                <div class="stat-label">Con Depósito</div>
            </div>
        </div>
        <div class="stat-card" data-stat-key="active_traders">
            <div class="stat-icon bg-teal-500">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="22,12 18,12 15,21 9,3 6,12 2,12"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo number_format($stats['active_traders']); ?></div>
                <div class="stat-label">Traders Activos</div>
            </div>
        </div>
    </div>

    <div class="filters-section">
        <form method="GET" class="filters-form">
            <input type="hidden" name="module" value="leads">
            <div class="search-box">
                <svg class="search-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="11" cy="11" r="8"/>
                    <path d="m21 21-4.35-4.35"/>
                </svg>
                <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Buscar por nombre, email, telÃ©fono o empresa..." class="search-input">
            </div>
            <div class="filter-group">
                <select name="status" class="filter-select">
                    <option value="">Todos los estados</option>
                    <?php foreach (($statuses ?? []) as $st): ?>
                        <option value="<?php echo htmlspecialchars($st); ?>" <?php echo ($status_filter === $st) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars(statusLabel($st)); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <select name="priority" class="filter-select">
                    <option value="">Todas las prioridades</option>
                    <option value="low" <?php echo $priority_filter === 'low' ? 'selected' : ''; ?>>Baja</option>
                    <option value="medium" <?php echo $priority_filter === 'medium' ? 'selected' : ''; ?>>Media</option>
                    <option value="high" <?php echo $priority_filter === 'high' ? 'selected' : ''; ?>>Alta</option>
                    <option value="urgent" <?php echo $priority_filter === 'urgent' ? 'selected' : ''; ?>>Urgente</option>
                </select>
                <?php if (!empty($countries)): ?>
                <?php
                    $selectedCountries = $country_filters ?? [];
                    $countryLabel = 'Todos los paÃ­ses';
                    if (is_array($selectedCountries) && count($selectedCountries) === 1) {
                        $countryLabel = htmlspecialchars($selectedCountries[0]);
                    } elseif (is_array($selectedCountries) && count($selectedCountries) > 1) {
                        $countryLabel = count($selectedCountries) . ' seleccionados';
                    }
                ?>
                <div class="filter-multiselect" id="countryMultiselect">
                    <div class="filter-select multiselect-trigger" role="button" aria-haspopup="listbox" aria-expanded="false" onclick="toggleCountryDropdown(event)">
                        <span id="countryLabel"><?php echo $countryLabel; ?></span>
                        <svg class="caret" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>
                    </div>
                    <div class="multiselect-dropdown" id="countryDropdown" style="display:none;">
                        <div class="multiselect-options">
                            <?php foreach ($countries as $c): $cn = trim($c['country']); if ($cn === '') continue; $isSel = in_array($cn, $selectedCountries ?? [], true); ?>
                                <label class="multiselect-option">
                                    <input type="checkbox" value="<?php echo htmlspecialchars($cn); ?>" <?php echo $isSel ? 'checked' : ''; ?>>
                                    <span><?php echo htmlspecialchars($cn); ?></span>
                                </label>
                            <?php endforeach; ?>
                        </div>
                        <div class="multiselect-actions">
                            <button type="button" class="btn-secondary" onclick="clearCountrySelection()">Limpiar</button>
                            <button type="button" class="btn-primary" onclick="applyCountrySelection()">Aplicar</button>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                <!-- Se elimina filtro de experiencia para alinear con esquema actual -->
                <?php if (!empty($desks)): ?>
                <select name="desk" class="filter-select">
                    <option value="">Todos los escritorios</option>
                    <?php foreach ($desks as $desk): ?>
                        <option value="<?php echo $desk['id']; ?>" <?php echo $desk_filter == $desk['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($desk['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <?php endif; ?>
                <?php if (!empty($users)): ?>
                <select name="assigned" class="filter-select">
                    <option value="">Todos los agentes</option>
                    <?php foreach ($users as $user): ?>
                        <option value="<?php echo $user['id']; ?>" <?php echo $assigned_filter == $user['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <?php endif; ?>
                <select name="online" class="filter-select">
                    <option value="">Todos (Online/Offline)</option>
                    <option value="online" <?php echo ($online_filter ?? '') === 'online' ? 'selected' : ''; ?>>Online</option>
                    <option value="offline" <?php echo ($online_filter ?? '') === 'offline' ? 'selected' : ''; ?>>Offline</option>
                </select>
            </div>
            <div class="filter-actions">
                <button type="submit" class="btn-primary">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <polygon points="22,3 2,3 10,12.46 10,19 14,21 14,12.46"/>
                    </svg>
                    Filtrar
                </button>
                <a href="?module=leads" class="btn-secondary">Limpiar</a>
            </div>
        </form>
    </div>

    <div class="table-container">
        <div class="table-header">
            <div class="table-title">
                <h3>Lista de Leads (<?php echo number_format($total_leads); ?> resultados)</h3>
            </div>
            <div class="table-actions">
                <button class="btn-ghost" onclick="exportLeads()">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-15"/>
                        <polyline points="17,10 12,5 7,10"/>
                        <line x1="12" y1="16" x2="12" y2="5"/>
                    </svg>
                    Exportar
                </button>
            </div>
        </div>

        <?php if (empty($leads)): ?>
            <div class="empty-state">
                <div class="empty-icon">
                    <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1">
                        <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/>
                        <circle cx="9" cy="7" r="4"/>
                        <path d="m22 2-5 10-5-5-5 10"/>
                    </svg>
                </div>
                <h3>No se encontraron leads</h3>
                <p>No hay leads que coincidan con los filtros seleccionados.</p>
                <button class="btn-primary" onclick="openCreateModal()">Crear primer lead</button>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="leads-table data-table">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="selectAll" onchange="toggleSelectAll()"></th>
                            <th class="sortable <?php echo $sort_by === 'first_name' ? 'sorted-' . strtolower($sort_order) : ''; ?>" onclick="sortTable('first_name')">Nombre
                                <svg class="sort-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 9l4-4 4 4"/><path d="M16 15l-4 4-4-4"/></svg>
                            </th>
                            <th class="sortable <?php echo $sort_by === 'last_name' ? 'sorted-' . strtolower($sort_order) : ''; ?>" onclick="sortTable('last_name')">Apellido
                                <svg class="sort-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 9l4-4 4 4"/><path d="M16 15l-4 4-4-4"/></svg>
                            </th>
                            <th class="sortable <?php echo $sort_by === 'email' ? 'sorted-' . strtolower($sort_order) : ''; ?>" onclick="sortTable('email')">Email
                                <svg class="sort-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 9l4-4 4 4"/><path d="M16 15l-4 4-4-4"/></svg>
                            </th>
                            <th>Teléfono</th>
                            <th>País</th>
                            <th>Desk</th>
                            <th>Asignado a</th>
                            <th class="sortable <?php echo $sort_by === 'updated_at' ? 'sorted-' . strtolower($sort_order) : ''; ?>">
                                <?php 
                                $nextOrder = ($sort_by === 'updated_at' && strtoupper($sort_order) === 'ASC') ? 'DESC' : 'ASC';
                                $sortUrl = '?module=leads&' . http_build_query(array_merge($_GET, ['sort' => 'updated_at', 'order' => $nextOrder, 'page' => 1]));
                                ?>
                                <a href="<?php echo htmlspecialchars($sortUrl); ?>" class="sort-link">Última actualización</a>
                            </th>
                            <th>Last Note</th>
                            <th>Estado</th>
                            <th>Online</th>
                            <th>Acciones</th>
                            
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($leads as $lead): ?>
                        <tr data-lead-id="<?php echo $lead['id']; ?>">
                            <td><input type="checkbox" class="rowCheckbox" value="<?php echo $lead['id']; ?>"></td>
                            <td class="lead-first-name" style="cursor:pointer">
                                <a href="<?php echo route_url(['module' => 'leads', 'action' => 'view', 'id' => (int)$lead['id']]); ?>" class="lead-name-link"><?php echo htmlspecialchars($lead['first_name']); ?></a>
                            </td>
                            <td class="lead-last-name" style="cursor:pointer">
                                <a href="<?php echo route_url(['module' => 'leads', 'action' => 'view', 'id' => (int)$lead['id']]); ?>" class="lead-name-link"><?php echo htmlspecialchars($lead['last_name']); ?></a>
                            </td>
                            <?php 
$canViewEmailFull = function_exists('userHasPermissionByName')
    ? (userHasPermissionByName($pdo, 'lead_email_mask', $current_user_id)
        || userHasPermissionByName($pdo, 'leads.view_email_full', $current_user_id))
    : false;
$canViewPhoneFull = function_exists('userHasPermissionByName')
    ? (userHasPermissionByName($pdo, 'lead_number_mask', $current_user_id)
        || userHasPermissionByName($pdo, 'leads.view_phone_full', $current_user_id))
    : false;
                                $emailDisplay = $canViewEmailFull ? ($lead['email'] ?? '') : maskEmail($lead['email'] ?? '');
                                $phoneDisplay = $canViewPhoneFull ? ($lead['phone'] ?? '') : maskPhone($lead['phone'] ?? '');
                            ?>
                            <td class="lead-email"><?php echo htmlspecialchars($emailDisplay); ?></td>
                            <td class="lead-phone"><?php echo htmlspecialchars($phoneDisplay); ?></td>
                            <td class="lead-country"><?php echo htmlspecialchars($lead['country'] ?? ''); ?></td>
                            <td class="lead-desk"><?php echo htmlspecialchars($lead['desk_name'] ?? ''); ?></td>
                            <td class="lead-assigned">
                                <div class="assigned-user">
                                    <div class="assigned-user-info">
                                        <div class="assigned-name"><?php echo htmlspecialchars($lead['assigned_user_name'] ?? $lead['assigned_user'] ?? 'Sin asignar'); ?></div>
                                        <div class="assigned-desk"><?php echo htmlspecialchars($lead['desk_name'] ?? ''); ?></div>
                                    </div>
                                </div>
                            </td>
                            <td class="lead-updated">
                                <span class="date-value"><?php echo date('d/m/Y', strtotime($lead['updated_at'] ?? $lead['created_at'])); ?></span>
                            </td>
                            <td class="lead-last-note"><?php echo htmlspecialchars($lead['last_note'] ?? ''); ?></td>
                            <td class="lead-status">
                                <span class="status-badge <?php echo statusBadgeClasses($lead['status'] ?? ''); ?>"><?php echo htmlspecialchars($lead['status'] ?? ''); ?></span>
                            </td>
                            <td class="lead-online">
                                <?php if (!empty($lead['is_online'])): ?>
                                    <span class="status-badge bg-emerald-100 text-emerald-800">ONLINE</span>
                                <?php else: ?>
                                    <span class="status-badge bg-gray-100 text-gray-800">OFFLINE</span>
                                <?php endif; ?>
                            </td>
                            <td class="lead-actions">
                                <?php if (($lead['status'] ?? '') !== 'converted'): ?>
                                    <a href="<?php echo module_url('leads/convert_to_client.php'); ?>?lead_id=<?php echo (int)$lead['id']; ?>" class="btn btn-primary btn-size-sm">Convertir</a>
                                <?php else: ?>
                                    <span class="status-badge bg-teal-100 text-teal-800">Convertido</span>
                                <?php endif; ?>
                            </td>
                            
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>

    <script>
    // Actualizar dinámicamente el filtro de estados según el desk seleccionado
    document.addEventListener('DOMContentLoaded', function(){
        var form = document.querySelector('.filters-form');
        if (!form) return;
        var deskSel = form.querySelector('select[name="desk"]');
        var statusSel = form.querySelector('select[name="status"]');
        if (!deskSel || !statusSel) return;

        async function updateStatusOptions(deskId){
            var current = statusSel.value;
            // Reiniciar opciones con el placeholder
            statusSel.innerHTML = '<option value="">Todos los estados</option>';
            if (!deskId) {
                // Sin desk: mantener los estados ya renderizados por el servidor en carga inicial
                return;
            }
            try {
                var resp = await fetch('/modules/leads/get_desk_statuses.php?desk_id=' + encodeURIComponent(deskId));
                var data = await resp.json();
                if (data && data.success && Array.isArray(data.statuses)) {
                    data.statuses.forEach(function(s){
                        var opt = document.createElement('option');
                        opt.value = s;
                        opt.textContent = String(s).replace(/_/g, ' ');
                        if (s === current) opt.selected = true;
                        statusSel.appendChild(opt);
                    });
                }
            } catch (e) {
                // Silencioso: si falla, el usuario puede usar el listado inicial del servidor
            }
        }

        deskSel.addEventListener('change', function(){
            updateStatusOptions(deskSel.value);
        });

        // Al cargar: si hay un desk elegido, sincronizar estados con ese desk
        if (deskSel.value) {
            updateStatusOptions(deskSel.value);
        }
    });
    </script>

    <div class="pagination-container">
        <?php
            $showing_start = (($page - 1) * $per_page) + 1;
            $showing_end = min($page * $per_page, $total_leads);
        ?>
        <div class="pagination-info">
            Mostrando <?php echo $showing_start; ?> - <?php echo $showing_end; ?> de <?php echo (int)$total_leads; ?>
        </div>
        <div class="pagination-size">
            <div class="page-size-label">
                <svg class="size-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M7 8h10"/></svg>
                Registros por pÃ¡gina
            </div>
            <div class="page-size-group" role="group" aria-label="Seleccionar registros por pÃ¡gina">
                <button type="button" class="size-pill <?php echo $per_page == 10 ? 'active' : ''; ?>" onclick="changePerPageValue(10)">10</button>
                <button type="button" class="size-pill <?php echo $per_page == 25 ? 'active' : ''; ?>" onclick="changePerPageValue(25)">25</button>
                <button type="button" class="size-pill <?php echo $per_page == 100 ? 'active' : ''; ?>" onclick="changePerPageValue(100)">100</button>
            </div>
            <select id="perPageSelect" class="filter-select" onchange="changePerPage(this)" aria-hidden="true" style="display:none;">
                <option value="10" <?php echo $per_page == 10 ? 'selected' : ''; ?>>10</option>
                <option value="25" <?php echo $per_page == 25 ? 'selected' : ''; ?>>25</option>
                <option value="100" <?php echo $per_page == 100 ? 'selected' : ''; ?>>100</option>
            </select>
        </div>

        <?php if ($total_pages > 1): ?>
        <div class="pagination">
            <?php
                // ConstrucciÃ³n profesional de paginaciÃ³n con ventana compacta
                $query_base = $_GET;
                // Prev
                $prev_page = max(1, $page - 1);
                $prev_url = route_url(array_merge($query_base, ['module' => 'leads', 'page' => $prev_page]));
            ?>
            <a href="<?php echo htmlspecialchars($prev_url); ?>" class="pagination-btn <?php echo $page == 1 ? 'disabled' : ''; ?>">Anterior</a>

            <?php
                $start = max(1, $page - 2);
                $end = min($total_pages, $page + 2);

                // Mostrar primer pÃ¡gina si la ventana no la incluye
                if ($start > 1) {
                    $first_url = route_url(array_merge($query_base, ['module' => 'leads', 'page' => 1]));
                    echo '<a href="' . htmlspecialchars($first_url) . '" class="pagination-btn">1</a>';
                    if ($start > 2) {
                        echo '<span class="pagination-ellipsis">â€¦</span>';
                    }
                }

                for ($i = $start; $i <= $end; $i++) {
                    $page_url = route_url(array_merge($query_base, ['module' => 'leads', 'page' => $i]));
                    $active = $i === $page ? 'active' : '';
                    echo '<a href="' . htmlspecialchars($page_url) . '" class="pagination-btn ' . $active . '">' . $i . '</a>';
                }

                // Mostrar Ãºltima pÃ¡gina si la ventana no la incluye
                if ($end < $total_pages) {
                    if ($end < $total_pages - 1) {
                        echo '<span class="pagination-ellipsis">â€¦</span>';
                    }
                    $last_url = route_url(array_merge($query_base, ['module' => 'leads', 'page' => $total_pages]));
                    echo '<a href="' . htmlspecialchars($last_url) . '" class="pagination-btn">' . (int)$total_pages . '</a>';
                }

                // Next
                $next_page = min($total_pages, $page + 1);
                $next_url = route_url(array_merge($query_base, ['module' => 'leads', 'page' => $next_page]));
            ?>
            <a href="<?php echo htmlspecialchars($next_url); ?>" class="pagination-btn <?php echo $page == $total_pages ? 'disabled' : ''; ?>">Siguiente</a>
        </div>
        <?php endif; ?>
    </div>

    <!-- Barra dinÃ¡mica de acciones masivas: aparece cuando hay selecciÃ³n -->
    <div id="dynamicBulkBar" class="bulk-actions" style="display:none;">
        <div class="bulk-info"><span id="bulkCount">0</span> leads seleccionados</div>
        <div class="bulk-buttons">
            <button class="btn-primary" id="bulkAssignBtn">Asignar Leads</button>
            <button class="btn-danger" id="bulkDeleteBtn">Eliminar</button>
            <button class="btn-secondary" id="bulkClearBtn">Limpiar selecciÃ³n</button>
        </div>
    </div>
</div>

<script>
// ===== SelecciÃ³n y barra de acciones masivas =====
function getSelectedLeads() {
    return Array.from(document.querySelectorAll('.rowCheckbox:checked')).map(cb => cb.value);
}

function updateBulkActions() {
    const selected = getSelectedLeads();
    const bar = document.getElementById('dynamicBulkBar');
    const count = document.getElementById('bulkCount');
    if (!bar || !count) return;
    if (selected.length > 0) {
        bar.style.display = 'flex';
        count.textContent = selected.length;
    } else {
        bar.style.display = 'none';
    }
}

function toggleSelectAll() {
    const selectAll = document.getElementById('selectAll');
    document.querySelectorAll('.rowCheckbox').forEach(cb => { cb.checked = !!selectAll.checked; });
    updateBulkActions();
}

function clearSelection() {
    const selectAll = document.getElementById('selectAll');
    if (selectAll) selectAll.checked = false;
    document.querySelectorAll('.rowCheckbox').forEach(cb => { cb.checked = false; });
    updateBulkActions();
}

// ===== PaginaciÃ³n profesional: cambio de tamaÃ±o de pÃ¡gina =====
function changePerPage(sel) {
    try {
        const url = new URL(window.location);
        url.searchParams.set('per_page', sel.value);
        url.searchParams.set('page', '1');
        window.location = url.toString();
    } catch (e) {
        // Fallback: construir query manual
        var params = new URLSearchParams(window.location.search);
        params.set('per_page', sel.value);
        params.set('page', '1');
        window.location.search = '?' + params.toString();
    }
}

function changePerPageValue(val) {
    try {
        const url = new URL(window.location);
        url.searchParams.set('per_page', String(val));
        url.searchParams.set('page', '1');
        window.location = url.toString();
    } catch (e) {
        var params = new URLSearchParams(window.location.search);
        params.set('per_page', String(val));
        params.set('page', '1');
        window.location.search = '?' + params.toString();
    }
}

// ===== Multiselect de PaÃ­s con dropdown (estÃ©tica de filter-select) =====
function toggleCountryDropdown(event) {
    event?.stopPropagation();
    const wrap = document.getElementById('countryMultiselect');
    const dd = document.getElementById('countryDropdown');
    const trigger = wrap?.querySelector('.multiselect-trigger');
    if (!wrap || !dd || !trigger) return;
    const isOpen = dd.style.display !== 'none';
    dd.style.display = isOpen ? 'none' : 'block';
    trigger.setAttribute('aria-expanded', isOpen ? 'false' : 'true');
}

function closeCountryDropdown() {
    const dd = document.getElementById('countryDropdown');
    const trigger = document.querySelector('#countryMultiselect .multiselect-trigger');
    if (!dd || !trigger) return;
    dd.style.display = 'none';
    trigger.setAttribute('aria-expanded', 'false');
}

function updateCountryLabel() {
    const labelEl = document.getElementById('countryLabel');
    const checks = Array.from(document.querySelectorAll('#countryDropdown input[type="checkbox"]'));
    const selected = checks.filter(ch => ch.checked).map(ch => ch.value);
    if (!labelEl) return;
    if (selected.length === 0) labelEl.textContent = 'Todos los paÃ­ses';
    else if (selected.length === 1) labelEl.textContent = selected[0];
    else labelEl.textContent = selected.length + ' seleccionados';
}

function syncCountryHiddenInputs() {
    const form = document.querySelector('.filters-form');
    if (!form) return;
    // Eliminar anteriores
    form.querySelectorAll('input[name="country[]"]').forEach(n => n.remove());
    // Agregar actuales
    const checks = Array.from(document.querySelectorAll('#countryDropdown input[type="checkbox"]'));
    const selected = checks.filter(ch => ch.checked);
    selected.forEach(ch => {
        const h = document.createElement('input');
        h.type = 'hidden';
        h.name = 'country[]';
        h.value = ch.value;
        form.appendChild(h);
    });
}

function applyCountrySelection() {
    syncCountryHiddenInputs();
    const form = document.querySelector('.filters-form');
    closeCountryDropdown();
    if (form) form.submit();
}

function clearCountrySelection() {
    const checks = Array.from(document.querySelectorAll('#countryDropdown input[type="checkbox"]'));
    checks.forEach(ch => ch.checked = false);
    updateCountryLabel();
}

document.addEventListener('DOMContentLoaded', function() {
    // checkboxes de filas actualizan barra
    document.querySelectorAll('.rowCheckbox').forEach(cb => {
        cb.addEventListener('change', updateBulkActions);
    });
    // botones de barra
    document.getElementById('bulkClearBtn')?.addEventListener('click', clearSelection);
    document.getElementById('bulkAssignBtn')?.addEventListener('click', bulkAssign);
    document.getElementById('bulkDeleteBtn')?.addEventListener('click', bulkDelete);

    // Cerrar dropdown al hacer click fuera
    document.addEventListener('click', function(e) {
        const wrap = document.getElementById('countryMultiselect');
        if (!wrap) return;
        if (!wrap.contains(e.target)) closeCountryDropdown();
    });
    // Actualizar etiqueta al cambiar selecciÃ³n
    document.querySelectorAll('#countryDropdown input[type="checkbox"]').forEach(ch => {
        ch.addEventListener('change', updateCountryLabel);
    });
    // Sincronizar selecciÃ³n antes de enviar el formulario
    const filtersForm = document.querySelector('.filters-form');
    if (filtersForm) {
        filtersForm.addEventListener('submit', function() {
            syncCountryHiddenInputs();
        });
    }
});

// ===== Modal de AsignaciÃ³n Masiva =====
function bulkAssign() {
    const selected = getSelectedLeads();
    if (selected.length === 0) { alert('Selecciona al menos un lead'); return; }

    const backdrop = document.createElement('div');
    backdrop.className = 'modal-backdrop modal-premium';
    const modal = document.createElement('div');
    modal.className = 'modal';

    const desksData = <?php echo json_encode($desks ?? []); ?>;

    modal.innerHTML = `
        <div class="modal-header">
            <div class="modal-title"><span class="modal-icon">ðŸ“¦</span><h3>AsignaciÃ³n Masiva de Leads</h3></div>
            <button class="btn-ghost" onclick="this.closest('.modal-backdrop').remove()">&times;</button>
        </div>
        <div class="modal-body">
            <div class="modal-lead-context"><strong>${selected.length}</strong> leads seleccionados</div>
            <div class="form-group">
                <label class="form-label">Selecciona Desk</label>
                <select id="bulkDeskSelect" class="form-control">
                    <option value="">-- Selecciona un desk --</option>
                    ${desksData.map(d => `<option value="${d.id}">${d.name}</option>`).join('')}
                </select>
            </div>
            <div class="form-group">
                <label class="form-label">Empleados del Desk</label>
                <div style="display:flex;align-items:center;gap:8px;margin:.25rem 0 .5rem;">
                    <input type="checkbox" id="bulkUsersSelectAll"><label for="bulkUsersSelectAll" style="cursor:pointer;">Seleccionar todos</label>
                </div>
                <div id="bulkDeskUsers" class="permissions-by-module" style="border:1px solid var(--border-light); border-radius:10px; padding:8px; min-height:48px;">
                    <em style="color:#64748b">Selecciona un desk para cargar empleados...</em>
                </div>
            </div>
            <div class="form-group">
                <label class="form-label">Estado de asignaciÃ³n</label>
                <select id="bulkStatusSelect" class="form-control" disabled>
                    <option value="">-- Selecciona un desk para ver estados --</option>
                </select>
            </div>
            <div id="bulkDistributionInfo" class="empty-state" style="margin-top:8px;">
                <div class="empty-icon">âš–ï¸</div>
                <div>DistribuciÃ³n: selecciona empleados para calcular reparto automÃ¡tico</div>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn-secondary" onclick="this.closest('.modal-backdrop').remove()">Cancelar</button>
            <button class="btn-primary" id="bulkAssignConfirmBtn">Asignar Leads</button>
        </div>
    `;

    backdrop.appendChild(modal);
    document.body.appendChild(backdrop);

    const deskSelect = modal.querySelector('#bulkDeskSelect');
    const usersContainer = modal.querySelector('#bulkDeskUsers');
    const usersSelectAll = modal.querySelector('#bulkUsersSelectAll');
    const distInfo = modal.querySelector('#bulkDistributionInfo');
    const confirmBtn = modal.querySelector('#bulkAssignConfirmBtn');

    function updateDistribution() {
        const checked = Array.from(usersContainer.querySelectorAll('input.bulk-user:checked'));
        const nUsers = checked.length;
        const nLeads = selected.length;
        // limpiar badges
        usersContainer.querySelectorAll('.distribution-badge').forEach(b => b.textContent = '');
        if (nUsers === 0) { distInfo.innerHTML = `<div class=\"empty-icon\">âš–ï¸</div><div>DistribuciÃ³n: selecciona empleados para calcular reparto automÃ¡tico</div>`; return; }
        const base = Math.floor(nLeads / nUsers);
        const rem = nLeads % nUsers;
        const listItems = checked.map((cb, i) => {
            const name = cb.getAttribute('data-name') || 'Empleado';
            const count = base + (i < rem ? 1 : 0);
            const badge = cb.parentElement.querySelector('.distribution-badge');
            if (badge) badge.textContent = `${count} leads`;
            return `<li>${name}: <strong>${count}</strong> lead${count === 1 ? '' : 's'}</li>`;
        }).join('');
        const summary = (nUsers === 1)
            ? `Todos los ${nLeads} leads serÃ¡n asignados a <strong>${checked[0].getAttribute('data-name') || 'Empleado'}</strong>`
            : `${nLeads} leads, ${nUsers} empleados â†’ ${base} por empleado${rem ? ` y ${rem} adicionales` : ''}`;
        distInfo.innerHTML = `<div class=\"empty-icon\">âš–ï¸</div><div>${summary}</div><ul class=\"distribution-list\" style=\"margin-top:6px;padding-left:18px;\">${listItems}</ul>`;
    }

    async function loadDeskUsers(deskId) {
        usersContainer.innerHTML = '<em style="color:#64748b">Cargando empleados...</em>';
        try {
            const resp = await fetch(`/modules/leads/get_desk_users.php?desk_id=${encodeURIComponent(deskId)}`);
            const data = await resp.json();
            if (!data.success) { usersContainer.innerHTML = `<span style='color:#ef4444'>Error: ${(data.message||'No se pudo cargar')}</span>`; return; }
            if (!data.users || data.users.length === 0) { usersContainer.innerHTML = '<em style="color:#64748b">No hay empleados activos en este desk.</em>'; updateDistribution(); return; }
            usersContainer.innerHTML = '';
            data.users.forEach(u => {
                const row = document.createElement('label');
                row.className = 'permission-check';
                row.style.margin = '4px 0';
                row.innerHTML = `
                    <input type="checkbox" class="bulk-user" value="${u.id}" data-name="${u.full_name || u.username}">
                    <span class="permission-label" data-text="${u.full_name || u.username}">${u.full_name || u.username}</span>
                    <span class="distribution-badge" style="margin-left:8px;color:#64748b;font-size:12px;"></span>`;
                usersContainer.appendChild(row);
            });
            usersContainer.querySelectorAll('.bulk-user').forEach(cb => cb.addEventListener('change', updateDistribution));
            updateDistribution();
        } catch (e) {
            usersContainer.innerHTML = `<span style='color:#ef4444'>Error de red: ${e.message}</span>`;
        }
    }

    usersSelectAll.addEventListener('change', function() {
        usersContainer.querySelectorAll('.bulk-user').forEach(cb => { cb.checked = usersSelectAll.checked; });
        updateDistribution();
    });

    async function loadDeskStatuses(deskId) {
        const statusSelect = modal.querySelector('#bulkStatusSelect');
        statusSelect.disabled = true;
        statusSelect.innerHTML = '<option value="">Cargando estados...</option>';
        try {
            const resp = await fetch(`/modules/leads/get_desk_statuses.php?desk_id=${encodeURIComponent(deskId)}`);
            const data = await resp.json();
            if (!data.success) {
                statusSelect.innerHTML = `<option value="">Error al cargar estados</option>`;
                return;
            }
            const statuses = (data.statuses || []).filter(s => !!s);
            if (statuses.length === 0) {
                statusSelect.innerHTML = '<option value="">Este desk no tiene estados configurados</option>';
                return;
            }
            statusSelect.innerHTML = statuses.map(s => `<option value="${s}">${String(s).replace('_',' ')}</option>`).join('');
            statusSelect.disabled = false;
        } catch (e) {
            statusSelect.innerHTML = `<option value="">Error de red: ${e.message}</option>`;
        }
    }

    deskSelect.addEventListener('change', function() {
        const val = deskSelect.value;
        usersSelectAll.checked = false;
        const statusSelect = modal.querySelector('#bulkStatusSelect');
        if (!val) {
            usersContainer.innerHTML = '<em style="color:#64748b">Selecciona un desk para cargar empleados...</em>';
            statusSelect.disabled = true;
            statusSelect.innerHTML = '<option value="">-- Selecciona un desk para ver estados --</option>';
            updateDistribution();
            return;
        }
        loadDeskUsers(val);
        loadDeskStatuses(val);
    });

    confirmBtn.addEventListener('click', async function() {
        const deskId = deskSelect.value;
        const statusSel = modal.querySelector('#bulkStatusSelect').value;
        const selectedUsers = Array.from(usersContainer.querySelectorAll('.bulk-user:checked')).map(cb => cb.value);
        if (!deskId) { alert('Selecciona un desk'); return; }
        if (!statusSel) { alert('Selecciona el estado de asignaciÃ³n'); return; }
        if (selectedUsers.length === 0) { alert('Selecciona al menos un empleado'); return; }

        const form = new FormData();
        selected.forEach(id => form.append('lead_ids[]', id));
        selectedUsers.forEach(uid => form.append('user_ids[]', uid));
        form.append('desk_id', deskId);
        form.append('status', statusSel);

        confirmBtn.disabled = true; confirmBtn.textContent = 'Asignando...';
        try {
            const resp = await fetch('/modules/leads/bulk_assign.php', { method: 'POST', body: form });
            const data = await resp.json();
            if (data.success) {
                // NotificaciÃ³n con resumen sin recargar
                const dist = data.data?.distribution || {};
                const empleados = Object.keys(dist).length;
                const total = Object.values(dist).reduce((a,b)=>a+b,0);
                const base = empleados ? Math.floor(total / empleados) : 0;
                const rem = empleados ? (total % empleados) : 0;
                const msg = `Asignados ${total} leads entre ${empleados} empleados (${base} por empleado${rem?`, ${rem} adicionales`:''}).`;
                if (window.ProfixCRM && typeof window.ProfixCRM.showNotification === 'function') {
                    window.ProfixCRM.showNotification(msg, 'success');
                } else { alert(msg); }
                // Cerrar modal y limpiar selecciÃ³n; actualizar barra
                backdrop.remove();
                clearSelection();
                // Actualizar visualmente filas: asignado, desk y estado sin recargar
                const statusClasses = {
                    new: 'bg-blue-100 text-blue-800',
                    contacted: 'bg-yellow-100 text-yellow-800',
                    qualified: 'bg-green-100 text-green-800',
                    demo_scheduled: 'bg-purple-100 text-purple-800',
                    demo_completed: 'bg-indigo-100 text-indigo-800',
                    deposit_pending: 'bg-orange-100 text-orange-800',
                    deposited: 'bg-emerald-100 text-emerald-800',
                    active_trader: 'bg-teal-100 text-teal-800',
                    inactive: 'bg-gray-100 text-gray-800',
                    closed_lost: 'bg-red-100 text-red-800'
                };
                function setBadgeClass(el, key){
                    const cls = statusClasses[key] || 'bg-gray-100 text-gray-800';
                    el.className = 'status-badge ' + cls;
                }
                const updates = (data.data && Array.isArray(data.data.lead_updates)) ? data.data.lead_updates : [];
                if (updates.length > 0) {
                    updates.forEach(upd => {
                        const row = document.querySelector(`tr[data-lead-id="${upd.lead_id}"]`);
                        if (!row) return;
                        const nameEl = row.querySelector('.assigned-name');
                        const deskEl = row.querySelector('.assigned-desk');
                        const deskCell = row.querySelector('.lead-desk');
                        const badge = row.querySelector('.lead-status .status-badge');
                        if (nameEl) nameEl.textContent = upd.assigned_user_name || '';
                        if (deskEl) deskEl.textContent = upd.desk_name || '';
                        if (deskCell) deskCell.textContent = upd.desk_name || '';
                        if (badge) {
                            const key = String((upd.status || statusSel || '')).trim();
                            badge.textContent = key.replace('_',' ');
                            setBadgeClass(badge, key);
                        }
                    });
                } else {
                    // Fallback: solo actualizar estado para seleccionados
                    selected.forEach(id => {
                        const row = document.querySelector(`tr[data-lead-id="${id}"]`);
                        const badge = row?.querySelector('.lead-status .status-badge');
                        if (badge) {
                            const key = String(statusSel || '').trim();
                            badge.textContent = key.replace('_',' ');
                            setBadgeClass(badge, key);
                        }
                    });
                }
                // Advertencia si no hubo filas afectadas realmente
                if ((data.data?.updated ?? 0) === 0) {
                    const invalidUsers = (data.data?.invalid_user_ids || []).length;
                    const missingLeads = (data.data?.missing_lead_ids || []).length;
                    const skipped = (data.data?.skipped || []);
                    const skippedNoChange = skipped.filter(s=>s.reason==='no_change').length;
                    const skippedNoRows = skipped.filter(s=>s.reason==='no_rows_affected').length;
                    const details = `Sin cambios aplicados. InvÃ¡lidos: usuarios=${invalidUsers}, leads faltantes=${missingLeads}, omitidos: no_change=${skippedNoChange}, no_rows=${skippedNoRows}.`;
                    if (window.ProfixCRM && typeof window.ProfixCRM.showNotification === 'function') {
                        window.ProfixCRM.showNotification(details, 'warning');
                    } else { console.warn(details); }
                }
                // Refrescar widgets para consistencia total
                refreshStatsWidgets();
            } else {
                let msg = 'Error: ' + (data.message || 'No se pudo asignar');
                const errs = Array.isArray(data.errors) ? data.errors : [];
                if (errs.length) {
                    msg += `\nDetalles: ${errs.slice(0,3).map(e=>`Lead ${e.lead_id}: ${e.error}`).join('; ')}${errs.length>3?'...':''}`;
                }
                const invalidUsers = (data.data?.invalid_user_ids || []).length;
                const missingLeads = (data.data?.missing_lead_ids || []).length;
                const skipped = (data.data?.skipped || []);
                if (invalidUsers || missingLeads || skipped.length) {
                    const skippedNoChange = skipped.filter(s=>s.reason==='no_change').length;
                    const skippedNotFound = skipped.filter(s=>s.reason==='not_found').length;
                    const skippedNoRows = skipped.filter(s=>s.reason==='no_rows_affected').length;
                    msg += `\nInvÃ¡lidos: usuarios=${invalidUsers}, leads faltantes=${missingLeads}, omitidos: no_change=${skippedNoChange}, not_found=${skippedNotFound}, no_rows=${skippedNoRows}`;
                }
                alert(msg);
            }
        } catch (e) {
            alert('Error de red: ' + e.message);
        } finally {
            confirmBtn.disabled = false; confirmBtn.textContent = 'Asignar Leads';
        }
    });
}

// ===== Borrado masivo =====
function bulkDelete() {
    const selected = getSelectedLeads();
    if (selected.length === 0) { alert('Selecciona al menos un lead'); return; }
    if (!confirm(`Â¿EstÃ¡s seguro de que deseas eliminar ${selected.length} leads?`)) { return; }

    // Capturar estados de las filas a eliminar para actualizar widgets
    const rows = selected.map(id => document.querySelector(`tr[data-lead-id="${id}"]`)).filter(Boolean);
    const statusCounts = {};
    rows.forEach(row => {
        const badge = row.querySelector('.lead-status .status-badge');
        if (badge) {
            const label = (badge.textContent || '').trim().toLowerCase();
            const key = label.replace(/\s+/g, '_');
            statusCounts[key] = (statusCounts[key] || 0) + 1;
        }
    });

    const form = new FormData();
    selected.forEach(id => form.append('lead_ids[]', id));

    fetch('/modules/leads/bulk_delete.php', { method: 'POST', body: form })
        .then(resp => resp.json())
        .then(data => {
            if (!data.success) {
                alert('Error: ' + (data.message || 'No se pudo eliminar'));
                return;
            }
            const ids = (data.data && data.data.deleted_ids) ? data.data.deleted_ids : selected;
            // Actualizar widgets de estadÃ­sticas
            updateStatsWidgets(ids.length, statusCounts);
            ids.forEach(id => {
                const row = document.querySelector(`tr[data-lead-id="${id}"]`);
                if (row) row.remove();
            });
            updateBulkActions();
            alert('Leads eliminados correctamente');
        })
        .catch(e => alert('Error de red: ' + e.message));
}

function updateStatsWidgets(deletedCount, statusCounts) {
    const parseNum = (txt) => {
        const m = (txt || '').match(/\d+/g);
        if (!m) return 0;
        return parseInt(m.join(''), 10) || 0;
    };
    const formatNum = (n) => new Intl.NumberFormat('es-ES').format(n);

    const cards = document.querySelectorAll('.stats-grid .stat-card');
    const decs = Object.assign({ total: deletedCount }, statusCounts || {});
    cards.forEach(card => {
        const key = card.getAttribute('data-stat-key');
        const numEl = card.querySelector('.stat-number');
        if (!key || !numEl) return;
        const current = parseNum(numEl.textContent);
        const dec = decs[key] || 0;
        if (dec > 0) numEl.textContent = formatNum(Math.max(0, current - dec));
    });

    updateTableResultsCount(deletedCount);
    refreshStatsWidgets();
}

function refreshStatsWidgets() {
    fetch('/modules/leads/stats.php')
        .then(r => r.json())
        .then(j => {
            if (!j.success || !j.data) return;
            const formatNum = (n) => new Intl.NumberFormat('es-ES').format(n);
            const map = j.data;
            document.querySelectorAll('.stats-grid .stat-card').forEach(card => {
                const key = card.getAttribute('data-stat-key');
                const numEl = card.querySelector('.stat-number');
                if (!key || !numEl) return;
                if (key in map) numEl.textContent = formatNum(map[key] || 0);
            });
        })
        .catch(() => {});
}

function updateTableResultsCount(deletedCount) {
    const titleEl = document.querySelector('.table-title h3');
    if (!titleEl) return;
    const m = titleEl.textContent.match(/\(([^\)]*)\)/);
    if (!m) return;
    const parseNum = (txt) => {
        const mm = (txt || '').match(/\d+/g);
        if (!mm) return 0;
        return parseInt(mm.join(''), 10) || 0;
    };
    const current = parseNum(m[1]);
    const next = Math.max(0, current - (deletedCount || 0));
    titleEl.textContent = titleEl.textContent.replace(m[1], new Intl.NumberFormat('es-ES').format(next) + ' resultados');
}
</script>
<script>
// ===== Asistente de ImportaciÃ³n de Leads (Excel/CSV) =====
function ensureXLSXLoaded() {
    return new Promise((resolve, reject) => {
        if (window.XLSX) return resolve();
        const s = document.createElement('script');
        s.src = 'https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js';
        s.onload = () => resolve();
        s.onerror = () => reject(new Error('No se pudo cargar el parser XLSX'));
        document.head.appendChild(s);
    });
}

function openImportModal() { openImportWizard(); }

async function openImportWizard() {
    try { await ensureXLSXLoaded(); } catch (e) { alert(e.message); return; }
    const backdrop = document.createElement('div');
    backdrop.className = 'modal-backdrop modal-premium';
    const modal = document.createElement('div');
    modal.className = 'modal';

    const statuses = ['new','contacted','qualified','demo_scheduled','demo_completed','deposit_pending','deposited','active_trader','inactive','closed_lost'];
    const desksData = <?php echo json_encode($desks ?? []); ?>;

    modal.innerHTML = `
        <div class="modal-header">
            <div class="modal-title"><span class="modal-icon">ðŸ“¥</span><h3>ImportaciÃ³n Guiada de Leads</h3></div>
            <button class="btn-ghost" onclick="this.closest('.modal-backdrop').remove()">&times;</button>
        </div>
        <div class="modal-body">
            <div id="importStepUpload" class="wizard-step">
                <p>Adjunta un archivo Excel (.xlsx) o CSV. El sistema lo mapearÃ¡ automÃ¡ticamente.</p>
                <input type="file" id="importFileInput" accept=".xlsx,.xls,.csv" class="form-control">
            </div>
            <div id="importStepMapping" class="wizard-step" style="display:none;">
                <h4>Mapeo de columnas</h4>
                <div id="mappingFields" style="display:grid;grid-template-columns:repeat(2,1fr);gap:8px;"></div>
            </div>
            <div id="importStepOptions" class="wizard-step" style="display:none;">
                <h4>Opciones de importaciÃ³n</h4>
                <div class="form-group">
                    <label class="form-label">Estado de los nuevos leads (segÃºn desk)</label>
                    <select id="importStatus" class="form-control"><option value="">-- Selecciona un desk primero --</option></select>
                </div>
                <div class="form-group">
                    <label class="form-label">Asignar a Desk</label>
                    <select id="importDesk" class="form-control">
                        <option value="">-- Opcional --</option>
                        ${desksData.map(d=>`<option value="${d.id}">${d.name}</option>`).join('')}
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Asignar a empleado (del desk seleccionado)</label>
                    <select id="importAssignee" class="form-control"><option value="">-- Opcional --</option></select>
                </div>
                <div class="form-group">
                    <label class="form-label">GestiÃ³n de duplicados (por email)</label>
                    <select id="duplicatePolicy" class="form-control">
                        <option value="skip">Saltar duplicados</option>
                        <option value="update">Actualizar existentes</option>
                        <option value="allow">Permitir duplicados</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Modo diagnÃ³stico (dry-run)</label>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="checkbox" id="importDryRun">
                        <span style="color:#64748b">Validar y simular sin insertar/actualizar</span>
                    </div>
                </div>
            </div>
            <div id="importStepPreview" class="wizard-step" style="display:none;">
                <h4>Vista previa (primeros 5 registros mapeados)</h4>
                <div class="table-responsive">
                    <table class="data-table"><thead id="previewHead"></thead><tbody id="previewBody"></tbody></table>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <div style="flex:1;display:flex;gap:8px;align-items:center;">
                <span id="importStatusText" style="color:#64748b"></span>
            </div>
            <div style="display:flex;gap:8px;">
                <button class="btn-secondary" id="btnBack" disabled>AtrÃ¡s</button>
                <button class="btn-primary" id="btnNext" disabled>Siguiente</button>
                <button class="btn-primary" id="btnImport" style="display:none;">Importar</button>
            </div>
        </div>
    `;

    backdrop.appendChild(modal);
    document.body.appendChild(backdrop);

    const stepUpload = modal.querySelector('#importStepUpload');
    const stepMapping = modal.querySelector('#importStepMapping');
    const stepOptions = modal.querySelector('#importStepOptions');
    const stepPreview = modal.querySelector('#importStepPreview');
    const btnBack = modal.querySelector('#btnBack');
    const btnNext = modal.querySelector('#btnNext');
    const btnImport = modal.querySelector('#btnImport');
    const statusText = modal.querySelector('#importStatusText');
    const fileInput = modal.querySelector('#importFileInput');
    const mappingFields = modal.querySelector('#mappingFields');
    const previewHead = modal.querySelector('#previewHead');
    const previewBody = modal.querySelector('#previewBody');
    const deskSelect = modal.querySelector('#importDesk');
    const importStatusSel = modal.querySelector('#importStatus');
    async function loadImportStatuses(deskId){
        if (!importStatusSel) return;
        importStatusSel.innerHTML = '<option value="">-- Selecciona un estado --</option>';
        if (!deskId) return;
        try {
            const resp = await fetch(`/modules/leads/get_desk_statuses.php?desk_id=${encodeURIComponent(deskId)}`);
            const data = await resp.json();
            if (data.success && Array.isArray(data.statuses)) {
                importStatusSel.innerHTML = '';
                data.statuses.forEach(s=>{
                    const opt = document.createElement('option');
                    opt.value = s; opt.textContent = String(s).replace('_',' ');
                    importStatusSel.appendChild(opt);
                });
                if (!data.statuses.length) {
                    importStatusSel.innerHTML = '<option value="">-- Sin estados configurados en este desk --</option>';
                }
            }
        } catch (e) {}
    }
    deskSelect.addEventListener('change', function(){
        loadImportStatuses(deskSelect.value);
    });
    const assigneeSelect = modal.querySelector('#importAssignee');

    const systemFields = [
        {key:'first_name',label:'Nombre'},
        {key:'last_name',label:'Apellido'},
        {key:'email',label:'Email'},
        {key:'phone',label:'TelÃ©fono'},
        {key:'country',label:'PaÃ­s'},
        {key:'company',label:'Empresa'},
        {key:'job_title',label:'Cargo'},
        {key:'source',label:'Fuente'},
        {key:'status',label:'Estado (desde archivo)'},
        {key:'priority',label:'Prioridad'}
    ];

    let parsedData = { headers: [], rows: [] };
    let mapping = {}; // field->columnName

    async function loadAssigneesForDesk(deskId) {
        assigneeSelect.innerHTML = '<option value="">-- Opcional --</option>';
        if (!deskId) return;
        try {
            const resp = await fetch(`/modules/leads/get_desk_users.php?desk_id=${encodeURIComponent(deskId)}`);
            const data = await resp.json();
            if (data.success && data.users) {
                data.users.forEach(u => {
                    const opt = document.createElement('option');
                    opt.value = u.id;
                    opt.textContent = u.full_name || u.username;
                    assigneeSelect.appendChild(opt);
                });
            }
        } catch (e) { /* noop */ }
    }
    deskSelect.addEventListener('change', e => loadAssigneesForDesk(e.target.value));

    function setStep(step) {
        stepUpload.style.display = (step===0)?'block':'none';
        stepMapping.style.display = (step===1)?'block':'none';
        stepOptions.style.display = (step===2)?'block':'none';
        stepPreview.style.display = (step===3)?'block':'none';
        btnBack.disabled = (step===0);
        btnNext.style.display = (step<3)?'inline-block':'none';
        btnImport.style.display = (step===3)?'inline-block':'none';
    }

    function autoMap(headers) {
        mapping = {};
        const norm = s => s.toLowerCase().trim();
        const candidates = {
            first_name:['nombre','first name','firstname','first_name'],
            last_name:['apellido','last name','lastname','last_name'],
            email:['email','correo','e-mail','mail'],
            phone:['phone','telefono','telÃ©fono','mobile'],
            country:['country','pais','paÃ­s'],
            company:['company','empresa'],
            job_title:['cargo','puesto','position','job title'],
            source:['source','fuente','origen'],
            status:['status','estado'],
            priority:['priority','prioridad']
        };
        headers.forEach(h => {
            const nh = norm(h);
            Object.entries(candidates).forEach(([field,list])=>{ if (list.includes(nh) && !mapping[field]) mapping[field]=h; });
        });
    }

    function renderMapping(headers) {
        mappingFields.innerHTML = '';
        systemFields.forEach(f => {
            const wrap = document.createElement('div');
            wrap.className = 'form-group';
            wrap.innerHTML = `<label class="form-label">${f.label}</label>`;
            const sel = document.createElement('select');
            sel.className = 'form-control';
            sel.innerHTML = `<option value="">-- No asignar --</option>` + headers.map(h=>`<option value="${h}">${h}</option>`).join('');
            sel.value = mapping[f.key] || '';
            sel.addEventListener('change', ()=>{ mapping[f.key] = sel.value || undefined; });
            wrap.appendChild(sel);
            mappingFields.appendChild(wrap);
        });
    }

    function parseFile(file) {
        return new Promise((resolve,reject)=>{
            const reader = new FileReader();
            reader.onload = function(e) {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, {type:'array'});
                const sheetName = workbook.SheetNames[0];
                const sheet = workbook.Sheets[sheetName];
                const json = XLSX.utils.sheet_to_json(sheet, {header:1, defval:''});
                const headers = (json[0]||[]).map(h=>String(h));
                const rows = json.slice(1).map(r=>{
                    const row = {};
                    headers.forEach((h,idx)=>{ row[h] = r[idx] ?? ''; });
                    return row;
                });
                resolve({headers, rows});
            };
            reader.onerror = () => reject(new Error('No se pudo leer el archivo'));
            reader.readAsArrayBuffer(file);
        });
    }

    function applyMapping(rows) {
        return rows.map(r => {
            const obj = {};
            Object.entries(mapping).forEach(([field,col])=>{ if (col) obj[field] = (r[col] ?? '').toString(); });
            return obj;
        });
    }

    function renderPreview(mappedRows) {
        const cols = systemFields.map(f=>f.key).filter(k=>mapping[k]);
        previewHead.innerHTML = `<tr>${cols.map(c=>`<th>${c}</th>`).join('')}</tr>`;
        previewBody.innerHTML = mappedRows.slice(0,5).map(row=>`<tr>${cols.map(c=>`<td>${(row[c]??'').toString()}</td>`).join('')}</tr>`).join('');
    }

    fileInput.addEventListener('change', async function() {
        const file = fileInput.files[0];
        if (!file) return;
        statusText.textContent = 'Procesando archivo...';
        try {
            parsedData = await parseFile(file);
            autoMap(parsedData.headers);
            renderMapping(parsedData.headers);
            statusText.textContent = `Detectadas ${parsedData.rows.length} filas, ${parsedData.headers.length} columnas.`;
            btnNext.disabled = false;
        } catch (e) {
            alert(e.message);
        }
    });

    btnBack.addEventListener('click', function(){
        if (stepPreview.style.display==='block') { setStep(2); return; }
        if (stepOptions.style.display==='block') { setStep(1); return; }
        if (stepMapping.style.display==='block') { setStep(0); return; }
    });

    btnNext.addEventListener('click', function(){
        if (stepUpload.style.display==='block') { setStep(1); return; }
        if (stepMapping.style.display==='block') { setStep(2); return; }
        if (stepOptions.style.display==='block') {
            const mapped = applyMapping(parsedData.rows);
            renderPreview(mapped);
            setStep(3);
            btnNext.disabled = true;
        }
    });

    btnImport.addEventListener('click', async function(){
        const defaultStatus = modal.querySelector('#importStatus').value;
        const deskId = modal.querySelector('#importDesk').value || null;
        const assigneeId = modal.querySelector('#importAssignee').value || null;
        const duplicatePolicy = modal.querySelector('#duplicatePolicy').value || 'skip';
        const dryRun = !!modal.querySelector('#importDryRun')?.checked;
        const mapped = applyMapping(parsedData.rows);
        btnImport.disabled = true; btnImport.textContent = 'Importando...';
        try {
            const resp = await fetch('/modules/leads/import_leads.php', {
                method: 'POST',
                headers: {'Content-Type':'application/json'},
                body: JSON.stringify({ rows: mapped, options: { default_status: defaultStatus, desk_id: deskId, assignee_id: assigneeId, duplicate_policy: duplicatePolicy, dry_run: dryRun } })
            });
            const data = await resp.json();
            if (data.success) {
                const prefix = data.dry_run ? 'DiagnÃ³stico' : 'ImportaciÃ³n completa';
                const msg = `${prefix}: insertados ${data.summary.inserted}, actualizados ${data.summary.updated}, duplicados ${data.summary.duplicates}, saltados ${data.summary.skipped}, fallidos ${data.summary.failed}.`;
                if (window.ProfixCRM && typeof window.ProfixCRM.showNotification === 'function') {
                    const type = data.dry_run ? 'info' : (data.summary.failed ? 'warning' : 'success');
                    window.ProfixCRM.showNotification(msg, type);
                } else { alert(msg); }

                // Mostrar errores detallados en la UI si existen
                if (Array.isArray(data.errors) && data.errors.length) {
                    console.warn('Errores de importaciÃ³n:', data.errors);
                    const body = modal.querySelector('.modal-body');
                    let panel = body.querySelector('#importErrorsPanel');
                    if (!panel) {
                        panel = document.createElement('div');
                        panel.id = 'importErrorsPanel';
                        panel.style.marginTop = '16px';
                        panel.style.border = '1px solid #e57373';
                        panel.style.background = '#fff5f5';
                        panel.style.borderRadius = '6px';
                        panel.style.padding = '12px';
                        panel.innerHTML = `<h4 style="margin:0 0 8px 0;color:#c62828;">Errores detectados (${data.errors.length})</h4><div id="importErrorsList"></div>`;
                        body.appendChild(panel);
                    }
                    const list = panel.querySelector('#importErrorsList');
                    list.innerHTML = '';
                    const table = document.createElement('table');
                    table.style.width = '100%';
                    table.style.borderCollapse = 'collapse';
                    table.innerHTML = `<thead><tr><th style="text-align:left;padding:6px;border-bottom:1px solid #ddd;">Email</th><th style="text-align:left;padding:6px;border-bottom:1px solid #ddd;">AcciÃ³n</th><th style="text-align:left;padding:6px;border-bottom:1px solid #ddd;">Mensaje</th></tr></thead>`;
                    const tbody = document.createElement('tbody');
                    data.errors.forEach(err => {
                        const tr = document.createElement('tr');
                        tr.innerHTML = `<td style="padding:6px;border-bottom:1px solid #eee;">${err.email || ''}</td><td style="padding:6px;border-bottom:1px solid #eee;">${err.action || ''}</td><td style="padding:6px;border-bottom:1px solid #eee;">${err.message || ''}</td>`;
                        tbody.appendChild(tr);
                    });
                    table.appendChild(tbody);
                    list.appendChild(table);
                    // Mantener el modal abierto para revisar errores; no redirigir
                } else {
                    if (data.dry_run) {
                        // En dry-run, mantenemos el modal para que el usuario pueda revisar
                        // y decidir si ejecuta la importaciÃ³n real.
                    } else {
                        // Sin errores y no dry-run: cerrar y refrescar widgets
                        backdrop.remove();
                        refreshStatsWidgets();
                    }
                }
            } else {
                alert('Error: ' + (data.message || 'FallÃ³ la importaciÃ³n'));
            }
        } catch (e) {
            alert('Error de red: ' + e.message);
        } finally { btnImport.disabled = false; btnImport.textContent = 'Importar'; }
    });

    setStep(0);
}

// ===== Asistente Guiado: Nuevo Lead =====
function openCreateModal() { openNewLeadWizard(); }

function openNewLeadWizard() {
    const backdrop = document.createElement('div');
    backdrop.className = 'modal-backdrop modal-premium';
    const modal = document.createElement('div');
    modal.className = 'modal';
    const desksData = <?php echo json_encode($desks ?? []); ?>;

    modal.innerHTML = `
        <div class="modal-header">
            <div class="modal-title"><span class="modal-icon">ðŸ§­</span><h3>Asistente: Nuevo Lead</h3></div>
            <button class="btn-ghost" onclick="this.closest('.modal-backdrop').remove()">&times;</button>
        </div>
        <div class="modal-body">
            <div id="nlStep1" class="wizard-step">
                <h4>Datos bÃ¡sicos</h4>
                <div class="form-group"><label class="form-label">Nombre</label><input id="nlFirstName" class="form-control"></div>
                <div class="form-group"><label class="form-label">Apellido</label><input id="nlLastName" class="form-control"></div>
                <div class="form-group"><label class="form-label">Email</label><input id="nlEmail" class="form-control"></div>
                <div class="form-group"><label class="form-label">TelÃ©fono</label><input id="nlPhone" class="form-control"></div>
                <div class="form-group"><label class="form-label">PaÃ­s</label><input id="nlCountry" class="form-control"></div>
            </div>
            <div id="nlStep2" class="wizard-step" style="display:none;">
                <h4>Preferencias de trading</h4>
                <div class="form-group"><label class="form-label">Experiencia</label>
                    <select id="nlExperience" class="form-control"><option value="none">Sin experiencia</option><option value="beginner">Principiante</option><option value="intermediate">Intermedio</option><option value="advanced">Avanzado</option><option value="professional">Profesional</option></select>
                </div>
                <div class="form-group"><label class="form-label">Monto de inversiÃ³n</label><input id="nlInvestment" class="form-control" type="number" min="0"></div>
            </div>
            <div id="nlStep3" class="wizard-step" style="display:none;">
                <h4>AsignaciÃ³n y estado</h4>
                <div class="form-group"><label class="form-label">Desk</label><select id="nlDesk" class="form-control"><option value="">-- Selecciona un desk --</option>${desksData.map(d=>`<option value="${d.id}">${d.name}</option>`).join('')}</select></div>
                <div class="form-group"><label class="form-label">Asignar a</label><select id="nlAssignee" class="form-control"><option value="">-- Selecciona empleado --</option></select></div>
                <div class="form-group"><label class="form-label">Estado</label><select id="nlStatus" class="form-control"><option value="">-- Selecciona estado del desk --</option></select></div>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn-secondary" id="nlBack" disabled>AtrÃ¡s</button>
            <button class="btn-primary" id="nlNext">Siguiente</button>
            <button class="btn-primary" id="nlCreate" style="display:none;">Crear Lead</button>
        </div>
    `;

    backdrop.appendChild(modal);
    document.body.appendChild(backdrop);

    const s1 = modal.querySelector('#nlStep1');
    const s2 = modal.querySelector('#nlStep2');
    const s3 = modal.querySelector('#nlStep3');
    const back = modal.querySelector('#nlBack');
    const next = modal.querySelector('#nlNext');
    const createBtn = modal.querySelector('#nlCreate');
    const deskSel = modal.querySelector('#nlDesk');
    const assigneeSel = modal.querySelector('#nlAssignee');
    const statusSel = modal.querySelector('#nlStatus');

    async function loadAssignees(deskId){
        assigneeSel.innerHTML = '<option value="">-- Selecciona empleado --</option>';
        if (!deskId) return;
        try {
            const resp = await fetch(`/modules/leads/get_desk_users.php?desk_id=${encodeURIComponent(deskId)}`);
            const data = await resp.json();
            if (data.success && data.users) {
                data.users.forEach(u=>{
                    const opt = document.createElement('option');
                    opt.value = u.id; opt.textContent = u.full_name || u.username;
                    assigneeSel.appendChild(opt);
                });
            }
        } catch (e) {}
    }

    async function loadStatuses(deskId){
        statusSel.innerHTML = '<option value="">-- Selecciona estado del desk --</option>';
        if (!deskId) return;
        try {
            const resp = await fetch(`/modules/leads/get_desk_statuses.php?desk_id=${encodeURIComponent(deskId)}`);
            const data = await resp.json();
            if (data.success && Array.isArray(data.statuses)) {
                data.statuses.forEach(s=>{
                    const opt = document.createElement('option');
                    opt.value = s; opt.textContent = String(s).replace('_',' ');
                    statusSel.appendChild(opt);
                });
            }
        } catch (e) {}
    }

    deskSel.addEventListener('change', function(){
        const deskId = deskSel.value;
        loadAssignees(deskId);
        loadStatuses(deskId);
    });

    function setStep(i){
        s1.style.display = (i===0)?'block':'none';
        s2.style.display = (i===1)?'block':'none';
        s3.style.display = (i===2)?'block':'none';
        back.disabled = (i===0);
        next.style.display = (i<2)?'inline-block':'none';
        createBtn.style.display = (i===2)?'inline-block':'none';
    }

    back.addEventListener('click', function(){
        if (s3.style.display==='block') { setStep(1); return; }
        if (s2.style.display==='block') { setStep(0); return; }
    });
    next.addEventListener('click', function(){
        if (s1.style.display==='block') { setStep(1); return; }
        if (s2.style.display==='block') {
            setStep(2);
            if (!deskSel.value) {
                alert('Primero selecciona el desk para cargar empleados y estados.');
            }
            return;
        }
    });

    createBtn.addEventListener('click', async function(){
        const payload = {
            first_name: modal.querySelector('#nlFirstName').value.trim(),
            last_name: modal.querySelector('#nlLastName').value.trim(),
            email: modal.querySelector('#nlEmail').value.trim(),
            phone: modal.querySelector('#nlPhone').value.trim(),
            country: modal.querySelector('#nlCountry').value.trim(),
            experience: modal.querySelector('#nlExperience').value,
            investment_amount: modal.querySelector('#nlInvestment').value,
            status: modal.querySelector('#nlStatus').value,
            desk_id: modal.querySelector('#nlDesk').value || null,
            assigned_to: modal.querySelector('#nlAssignee').value || null
        };
        if (!payload.email) { alert('El email es obligatorio'); return; }
        if (!payload.desk_id) { alert('Selecciona el desk'); return; }
        if (!payload.status) { alert('Selecciona el estado del desk'); return; }
        createBtn.disabled = true; createBtn.textContent = 'Creando...';
        try {
            const resp = await fetch('/modules/leads/create_lead.php', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(payload) });
            const data = await resp.json();
            if (data.success) {
                if (window.ProfixCRM && typeof window.ProfixCRM.showNotification === 'function') {
                    window.ProfixCRM.showNotification('Lead creado exitosamente', 'success');
                } else { alert('Lead creado exitosamente'); }
                backdrop.remove();
                // Refrescar widgets para reflejar nuevos totales sin recargar
                refreshStatsWidgets();
            } else { alert('Error: ' + (data.message||'No se pudo crear')); }
        } catch (e) { alert('Error de red: ' + e.message); }
        finally { createBtn.disabled = false; createBtn.textContent = 'Crear Lead'; }
    });

    setStep(0);
}
</script>
