<?php
// Asegurar que la sesión esté iniciada
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Asegurar que el lead esté disponible
if (!isset($lead) || !is_array($lead)) {
    $lead = [];
}

// Helpers para badges y máscaras
if (!function_exists('statusBadgeClass')) {
    function statusBadgeClass($status) {
        $map = [
            'new' => 'status-new',
            'contacted' => 'status-contacted', 
            'qualified' => 'status-qualified',
            'demo_scheduled' => 'status-demo',
            'demo_completed' => 'status-demo-done',
            'deposit_pending' => 'status-deposit',
            'deposited' => 'status-deposited',
            'active_trader' => 'status-active',
            'inactive' => 'status-inactive',
            'closed_lost' => 'status-lost'
        ];
        return $map[$status] ?? 'status-default';
    }
}

if (!function_exists('priorityBadgeClass')) {
    function priorityBadgeClass($priority) {
        $map = [
            'low' => 'priority-low',
            'medium' => 'priority-medium', 
            'high' => 'priority-high',
            'urgent' => 'priority-urgent'
        ];
        return $map[$priority] ?? 'priority-medium';
    }
}

if (!function_exists('maskEmail')) {
    function maskEmail($email, $first = 3, $last = 2) {
        if (empty($email) || strpos($email, '@') === false) return $email;
        list($local, $domain) = explode('@', $email, 2);
        $localLen = strlen($local);
        if ($localLen <= ($first + $last)) return str_repeat('*', $localLen) . '@' . $domain;
        return substr($local, 0, $first) . str_repeat('*', $localLen - ($first + $last)) . substr($local, -$last) . '@' . $domain;
    }
}

if (!function_exists('maskPhone')) {
    function maskPhone($phone, $first = 3, $last = 2) {
        $digits = preg_replace('/\D+/', '', $phone);
        $len = strlen($digits);
        if ($len <= ($first + $last)) return str_repeat('*', $len);
        return substr($digits, 0, $first) . str_repeat('*', $len - ($first + $last)) . substr($digits, -$last);
    }
}

// Asegurar que las variables de permisos existan
if (!isset($canViewEmailFull)) $canViewEmailFull = false;
if (!isset($canViewPhoneFull)) $canViewPhoneFull = false;

// Asegurar que las variables de paginación y actividades existan
if (!isset($activities)) $activities = [];
if (!isset($total_activities)) $total_activities = 0;
if (!isset($total_pages)) $total_pages = 1;
if (!isset($page)) $page = 1;
if (!isset($stats)) $stats = [];
if (!isset($total_activities)) $total_activities = 0;

// Datos del lead
$full_name = trim(($lead['first_name'] ?? '') . ' ' . ($lead['last_name'] ?? ''));
$initials = strtoupper(substr($lead['first_name'] ?? 'L', 0, 1) . substr($lead['last_name'] ?? 'D', 0, 1));
$emailDisplay = $canViewEmailFull ? ($lead['email'] ?? '') : maskEmail($lead['email'] ?? '');
$phoneDisplay = $canViewPhoneFull ? ($lead['phone'] ?? '') : maskPhone($lead['phone'] ?? '');
$is_online = (!empty($lead['last_seen']) && (time() - strtotime($lead['last_seen'])) <= 300);
?>

<style>
<?php include __DIR__ . '/view_styles.css'; ?>
</style>

<div class="lead-profile-container">
    <!-- Hero Section Premium -->
    <div class="lead-hero fade-in">
        <div class="lead-hero-content">
            <div class="lead-avatar">
                <?= strtoupper(substr($lead['first_name'] . ' ' . $lead['last_name'], 0, 2)) ?>
            </div>
            <div class="lead-info">
                <h1><?= htmlspecialchars($lead['first_name'] . ' ' . $lead['last_name']) ?></h1>
                <p class="lead-subtitle">Lead ID: <?= $lead['id'] ?> • <?= htmlspecialchars($lead['company'] ?? 'Sin empresa') ?></p>
                <div class="lead-badges">
                    <span class="luxury-badge status-<?= strtolower($lead['status']) ?>">
                        <span class="dot <?= $lead['status'] === 'active' ? 'online' : 'offline' ?>"></span>
                        <?= ucfirst($lead['status']) ?>
                    </span>
                    <span class="luxury-badge priority-<?= strtolower($lead['priority'] ?? 'medium') ?>">
                        Prioridad <?= ucfirst($lead['priority'] ?? 'Media') ?>
                    </span>
                </div>
            </div>
        </div>
    </div>

    <!-- Acciones Rápidas Premium -->
    <div class="quick-actions slide-up">
        <div class="quick-action-card" onclick="openNoteModal()">
            <div class="quick-action-icon">📝</div>
            <h3 class="quick-action-title">Agregar Notas</h3>
            <p class="quick-action-desc">Registrar actividades y comentarios</p>
        </div>
        <div class="quick-action-card">
            <div class="quick-action-icon">📞</div>
            <h3 class="quick-action-title">Llamar Ahora</h3>
            <p class="quick-action-desc">Contactar directamente con el lead</p>
        </div>
        <div class="quick-action-card">
            <div class="quick-action-icon">📧</div>
            <h3 class="quick-action-title">Enviar Email</h3>
            <p class="quick-action-desc">Comunicación por correo electrónico</p>
        </div>
        <div class="quick-action-card" onclick="openAppointmentModal()">
            <div class="quick-action-icon">📅</div>
            <h3 class="quick-action-title">Programar Cita</h3>
            <p class="quick-action-desc">Agendar reunión o seguimiento</p>
        </div>
    </div>

    <?php
    $clientForLeadId = 0;
    try {
        require_once BASE_PATH . '/database/connection.php';
        $pdoTemp = getDB()->getConnection();
        if (!empty($lead['email'])) {
            $stmtCli = $pdoTemp->prepare('SELECT id FROM clients WHERE email = ? LIMIT 1');
            $stmtCli->execute([$lead['email']]);
            $clientForLeadId = (int)$stmtCli->fetchColumn();
        }
    } catch (Exception $e) { $clientForLeadId = 0; }
    $canChangePwd = function_exists('userHasPermissionByName') ? (userHasPermissionByName($pdoTemp ?? $pdo_local ?? getDB()->getConnection(), 'leads.change_portal_password', (int)($_SESSION['user_id'] ?? 0)) || userHasPermissionByName($pdoTemp ?? $pdo_local ?? getDB()->getConnection(), 'clients.change_portal_password', (int)($_SESSION['user_id'] ?? 0))) : false;
    ?>
    <?php if ($canChangePwd): ?>
    <div class="info-panels slide-up">
        <div class="panel collapsible slide-up start-collapsed" id="pwd-panel">
            <div class="panel-header" role="button" tabindex="0" aria-expanded="false" aria-controls="pwd-panel-content" onclick="togglePanel('pwd-panel')">
                <div class="panel-icon">🔒</div>
                <h3 class="panel-title">Contraseña del Trader Room</h3>
                <div class="panel-caret" aria-hidden="true">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"></polyline></svg>
                </div>
            </div>
            <div id="pwd-panel-content" class="panel-content collapsible-content">
                <?php if ($clientForLeadId > 0): ?>
                <form method="post" action="<?= module_url('clients/actions.php') ?>" class="comment-form" onsubmit="return validateLeadPwd(this)">
                    <input type="hidden" name="action" value="change_password">
                    <input type="hidden" name="client_id" value="<?= intval($clientForLeadId) ?>">
                    <input type="hidden" name="redirect" value="<?= route_url(['module'=>($current_module ?? 'leads'),'action'=>'view','id'=>(int)$lead['id']]) ?>">
                    <div class="form-group">
                        <label>Nueva contraseña</label>
                        <input type="password" name="new_password" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label>Confirmar contraseña</label>
                        <input type="password" name="confirm_password" class="form-input" required>
                    </div>
                    <button type="submit" class="btn-primary">Actualizar contraseña</button>
                    <small class="text-muted">Mínimo 8 caracteres. Se guarda encriptada.</small>
                </form>
                <?php else: ?>
                <p class="text-muted">Este lead aún no tiene cliente asociado. Convierte el lead para poder gestionar la contraseña.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Paneles de Información Premium -->
    <div class="info-panels slide-up">
        <!-- Panel de Información de Contacto -->
        <div class="panel collapsible panel-contact is-open slide-up">
            <div class="panel-header" role="button" tabindex="0" aria-expanded="true" aria-controls="contact-panel-content">
                <div class="panel-icon">📇</div>
                <h3 class="panel-title">Información de Contacto</h3>
                <div class="panel-caret" aria-hidden="true">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <polyline points="6 9 12 15 18 9"></polyline>
                    </svg>
                </div>
            </div>
            <div id="contact-panel-content" class="panel-content collapsible-content">
                <div class="contact-info">
                    <div class="contact-item slide-up">
                        <div class="item-icon">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                                <circle cx="12" cy="7" r="4"></circle>
                            </svg>
                        </div>
                        <div class="item-content">
                            <strong>Nombre:</strong> <?php echo htmlspecialchars($full_name); ?>
                        </div>
                    </div>
                    <div class="contact-item slide-up">
                        <div class="item-icon">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"></path>
                                <polyline points="22,6 12,13 2,6"></polyline>
                            </svg>
                        </div>
                        <div class="item-content">
                            <strong>Email:</strong> 
                            <a href="<?php echo $canViewEmailFull ? 'mailto:' . htmlspecialchars($lead['email']) : '#'; ?>" class="contact-link">
                                <?php echo htmlspecialchars($emailDisplay); ?>
                            </a>
                        </div>
                    </div>
                    <div class="contact-item slide-up">
                        <div class="item-icon">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path>
                            </svg>
                        </div>
                        <div class="item-content">
                            <strong>Teléfono:</strong> 
                            <a href="<?php echo $canViewPhoneFull ? 'tel:' . htmlspecialchars($lead['phone']) : '#'; ?>" class="contact-link">
                                <?php echo htmlspecialchars($phoneDisplay); ?>
                            </a>
                        </div>
                    </div>
                    <div class="contact-item slide-up">
                        <div class="item-icon">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <circle cx="12" cy="10" r="3"></circle>
                                <path d="M12 21.7C17.3 17 20 13 20 10a8 8 0 1 0-16 0c0 3 2.7 7 8 11.7z"></path>
                            </svg>
                        </div>
                        <div class="item-content">
                            <strong>País:</strong> <?php echo htmlspecialchars($lead['country'] ?? 'No especificado'); ?>
                        </div>
                    </div>
                    <div class="contact-item slide-up">
                        <div class="item-icon">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path>
                                <polyline points="3.27,6.96 12,12.01 20.73,6.96"></polyline>
                                <line x1="12" y1="22.08" x2="12" y2="12"></line>
                            </svg>
                        </div>
                        <div class="item-content">
                            <strong>Fuente:</strong> <?php echo htmlspecialchars($lead['source'] ?? 'Desconocida'); ?>
                        </div>
                    </div>
                    <div class="contact-item slide-up">
                        <div class="item-icon">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                                <line x1="16" y1="2" x2="16" y2="6"></line>
                                <line x1="8" y1="2" x2="8" y2="6"></line>
                                <line x1="3" y1="10" x2="21" y2="10"></line>
                            </svg>
                        </div>
                        <div class="item-content">
                            <strong>Creado:</strong> <?php echo date('d/m/Y H:i', strtotime($lead['created_at'])); ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Assignment and Status -->
        <div class="panel collapsible panel-assign is-open slide-up">
            <div class="panel-header" role="button" tabindex="0" aria-expanded="true" aria-controls="assign-panel-content">
                <div class="panel-icon">🗂️</div>
                <h3 class="panel-title">Asignación y Estado</h3>
                <div class="panel-caret" aria-hidden="true">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <polyline points="6 9 12 15 18 9"></polyline>
                    </svg>
                </div>
            </div>
            <div id="assign-panel-content" class="panel-content collapsible-content">
                <div class="assignment-info">
                    <div class="assignment-item slide-up">
                        <div class="item-icon">
                            <svg width="16" height="16" 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"></path>
                                <circle cx="9" cy="7" r="4"></circle>
                                <path d="M22 21v-2a4 4 0 0 0-3-3.87"></path>
                                <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
                            </svg>
                        </div>
                        <div class="item-content">
                            <strong>Asignado a:</strong> <?php echo htmlspecialchars($lead['assigned_name'] ?? $lead['assigned_user'] ?? 'Sin asignar'); ?>
                        </div>
                    </div>
                    <div class="assignment-item slide-up">
                        <div class="item-icon">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect>
                                <line x1="8" y1="21" x2="16" y2="21"></line>
                                <line x1="12" y1="17" x2="12" y2="21"></line>
                            </svg>
                        </div>
                        <div class="item-content">
                            <strong>Desk:</strong> <?php echo htmlspecialchars($lead['desk_name'] ?? 'Sin desk'); ?>
                        </div>
                    </div>
                    <div class="assignment-item slide-up">
                        <div class="item-icon">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <circle cx="12" cy="12" r="3"></circle>
                                <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1 1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
                            </svg>
                        </div>
                        <div class="item-content">
                            <strong>Estado:</strong>
                            <select id="lead-status-select" class="form-select" data-lead-id="<?php echo $lead['id']; ?>" data-original-status="<?php echo htmlspecialchars($lead['status']); ?>">
                                <?php 
                                // Obtener estados permitidos para el desk del lead
                                $desk_id = intval($lead['desk_id'] ?? 0);
                                $allowed_statuses = [];
                                
                                if ($desk_id > 0) {
                                    // Si el lead tiene desk, obtener estados permitidos para ese desk
                                    $allowed_statuses = $db->select("SELECT status FROM desk_allowed_statuses WHERE desk_id = ? ORDER BY position ASC, status ASC", [$desk_id]);
                                    $allowed_statuses = array_column($allowed_statuses, 'status');
                                }
                                
                                // Si no hay estados específicos del desk, usar estados por defecto
                                if (empty($allowed_statuses)) {
                                    $allowed_statuses = ['new','contacted','qualified','demo_scheduled','demo_completed','deposit_pending','deposited','active_trader','inactive','closed_lost'];
                                }
                                
                                foreach($allowed_statuses as $status): ?>
                                    <option value="<?php echo $status; ?>" <?php echo ($lead['status'] === $status) ? 'selected' : ''; ?>>
                                        <?php echo ucfirst(str_replace('_', ' ', $status)); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="assignment-item slide-up">
                        <div class="item-icon">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <polygon points="12,2 15.09,8.26 22,9.27 17,14.14 18.18,21.02 12,17.77 5.82,21.02 7,14.14 2,9.27 8.91,8.26"></polygon>
                            </svg>
                        </div>
                        <div class="item-content">
                            <strong>Lead Score:</strong> <?php echo (int)($lead['lead_score'] ?? 0); ?>/100
                        </div>
                    </div>
                    <div class="assignment-item slide-up">
                        <div class="item-icon">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <circle cx="12" cy="12" r="10"></circle>
                                <polyline points="12,6 12,12 16,14"></polyline>
                            </svg>
                        </div>
                        <div class="item-content">
                            <strong>Última actividad:</strong> <span id="lastActivityValue"><?php echo !empty($stats['last_activity']) ? date('d/m/Y H:i', strtotime($stats['last_activity'])) : 'Sin actividad'; ?></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Estadísticas Premium -->
    <div class="stats-grid slide-up">
        <div class="stat-card premium-card">
            <div class="stat-icon">📞</div>
            <div class="stat-number"><?php echo (int)($stats['total_calls'] ?? 0); ?></div>
            <div class="stat-label">Llamadas realizadas</div>
        </div>
        <div class="stat-card premium-card">
            <div class="stat-icon">✉️</div>
            <div class="stat-number"><?php echo (int)($stats['total_emails'] ?? 0); ?></div>
            <div class="stat-label">Emails enviados</div>
        </div>
        <div class="stat-card premium-card">
            <div class="stat-icon">🎥</div>
            <div class="stat-number"><?php echo (int)($stats['total_meetings'] ?? 0); ?></div>
            <div class="stat-label">Reuniones programadas</div>
        </div>
        <div class="stat-card premium-card">
            <div class="stat-icon">✅</div>
            <div class="stat-number"><?php echo (int)($stats['completed_tasks'] ?? 0); ?></div>
            <div class="stat-label">Tareas completadas</div>
        </div>
        <div class="stat-card premium-card">
            <div class="stat-icon">⏳</div>
            <div class="stat-number"><?php echo (int)($stats['pending_tasks'] ?? 0); ?></div>
            <div class="stat-label">Tareas pendientes</div>
        </div>
    </div>

    <!-- Timeline de Actividades Premium -->
    <?php if (isset($current_module) && $current_module === 'clients' && isset($financial_kpis) && is_array($financial_kpis)): ?>
    <div class="panel slide-up" id="financial-stats-panel">
        <div class="panel-header" onclick="togglePanel('financial-stats-panel')">
            <div class="panel-icon">📈</div>
            <h3 class="panel-title">Stats Financieros</h3>
            <div class="panel-caret">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="6,9 12,15 18,9"></polyline>
                </svg>
            </div>
        </div>
        <div class="collapsible-content">
            <div class="panel-content">
                <div class="financial-stats-row row-top">
                    <div class="stat-card premium-card">
                        <div class="stat-icon">💼</div>
                        <div class="stat-number"><?php echo number_format((float)($financial_kpis['balance'] ?? 0),2); ?></div>
                        <div class="stat-label">Balance</div>
                    </div>
                    <div class="stat-card premium-card">
                        <div class="stat-icon">📊</div>
                        <div class="stat-number"><?php echo number_format((float)($financial_kpis['equity'] ?? 0),2); ?></div>
                        <div class="stat-label">Equity</div>
                    </div>
                    <div class="stat-card premium-card">
                        <div class="stat-icon">🛡️</div>
                        <div class="stat-number"><?php echo number_format((float)($financial_kpis['margin_level'] ?? 0),2); ?>%</div>
                        <div class="stat-label">Margin Level</div>
                    </div>
                    <div class="stat-card premium-card">
                        <div class="stat-icon">💹</div>
                        <div class="stat-number"><?php echo (($financial_kpis['profit'] ?? 0) >= 0 ? '+' : '') . number_format((float)($financial_kpis['profit'] ?? 0),2); ?></div>
                        <div class="stat-label">PnL</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
    <?php if (isset($current_module) && $current_module === 'clients' && isset($financial_kpis) && is_array($financial_kpis)): ?>
    <div class="panel slide-up" id="financial-panel">
        <div class="panel-header" onclick="togglePanel('financial-panel')">
            <div class="panel-icon">💳</div>
            <h3 class="panel-title">Financiero</h3>
            <div class="panel-caret">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="6,9 12,15 18,9"></polyline>
                </svg>
            </div>
        </div>
        <div class="collapsible-content">
            <div class="panel-content">
                
                <div class="financial-stats-row row-bottom">
                    <div class="stat-card premium-card">
                        <div class="stat-icon">⬇️</div>
                        <div class="stat-number"><?php echo number_format((float)($financial_kpis['deposits_total'] ?? 0),2); ?></div>
                        <div class="stat-label">Depósitos</div>
                    </div>
                    <div class="stat-card premium-card">
                        <div class="stat-icon">⬆️</div>
                        <div class="stat-number"><?php echo number_format((float)($financial_kpis['withdrawals_total'] ?? 0),2); ?></div>
                        <div class="stat-label">Retiros</div>
                    </div>
                    <div class="stat-card premium-card">
                        <div class="stat-icon">🏦</div>
                        <div class="stat-number"><?php echo number_format((float)($financial_kpis['credits_total'] ?? 0),2); ?></div>
                        <div class="stat-label">Créditos</div>
                    </div>
                </div>

                <table class="table">
                    <thead>
                        <tr>
                            <th>Fecha</th>
                            <th>Tipo</th>
                            <th>Monto</th>
                            <th>Divisa</th>
                            <th>Referencia</th>
                            <th>Agente</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($financial_movements)): foreach ($financial_movements as $m): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($m['date']); ?></td>
                                <td><span class="chip <?php echo (strtolower($m['type'])==='deposit')?'chip-buy':'chip-sell'; ?>"><?php echo strtoupper(htmlspecialchars($m['type'])); ?></span></td>
                                <td><?php echo htmlspecialchars($m['amount']); ?></td>
                                <td><?php echo htmlspecialchars($m['currency']); ?></td>
                                <td><?php echo htmlspecialchars($m['reference']); ?></td>
                                <td><?php echo htmlspecialchars($m['agent']); ?></td>
                            </tr>
                        <?php endforeach; else: ?>
                            <tr><td colspan="6">Sin movimientos registrados</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <?php endif; ?>
    <?php if (isset($current_module) && $current_module === 'clients' && isset($client_positions) && is_array($client_positions)): ?>
    <div class="panel slide-up" id="trading-positions-panel">
        <div class="panel-header" onclick="togglePanel('trading-positions-panel')">
            <div class="panel-icon">📈</div>
            <h3 class="panel-title">Operaciones en WebTrader</h3>
            <div class="panel-caret">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="6,9 12,15 18,9"></polyline>
                </svg>
            </div>
        </div>
        <div class="collapsible-content">
            <div class="panel-content">
                <?php if (empty($client_positions)): ?>
                    <div class="empty-state">
                        <div class="empty-icon">📄</div>
                        <h4>Sin operaciones abiertas</h4>
                        <p>No hay posiciones activas en este momento.</p>
                    </div>
                <?php else: ?>
                    <style>
                        .chip{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:999px;font-weight:700;border:1px solid #e5e7eb}
                        .chip-buy{background:#ecfdf5;color:#166534;border-color:#a7f3d0}
                        .chip-sell{background:#fee2e2;color:#991b1b;border-color:#fecaca}
                        .pnl-positive{color:#16a34a;font-weight:800}
                        .pnl-negative{color:#dc2626;font-weight:800}
                        .flag-pair{display:inline-flex;align-items:center;gap:6px;margin-right:8px}
                        .flag{width:20px;height:14px;border-radius:3px;box-shadow:0 1px 2px rgba(0,0,0,.15);display:inline-block;overflow:hidden}
                        .table-pagination{display:flex;justify-content:flex-end;align-items:center;gap:8px;padding-top:8px}
                        .pg-btn{display:inline-flex;align-items:center;justify-content:center;height:30px;padding:0 .75rem;border-radius:8px;border:1px solid #e5e7eb;background:#fff;color:#334155}
                        .pg-btn[disabled]{opacity:.5;cursor:not-allowed}
                        .page-indicator{font-weight:700;color:#0f172a}
                    </style>
                    <table class="table" id="positionsTable" data-client-id="<?php echo isset($current_module) && $current_module==='clients' ? intval($lead['id'] ?? 0) : 0; ?>">
                        <thead>
                            <tr>
                                <th>Símbolo</th>
                                <th>Tipo</th>
                                <th>Volumen</th>
                                <th>Apertura</th>
                                <th>Actual</th>
                                <th>PnL</th>
                                <th>Abierta</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($client_positions as $pos): ?>
                                <tr class="<?= htmlspecialchars($pos['status_class']) ?>">
                                    <td><span class="flag-pair"></span><?= htmlspecialchars($pos['symbol']) ?></td>
                                    <?php $typeCls = (strtolower($pos['type'] ?? '') === 'buy') ? 'chip-buy' : 'chip-sell'; ?>
                                    <td><span class="chip <?= $typeCls ?>"><?= htmlspecialchars(strtoupper($pos['type'])) ?></span></td>
                                    <td><?= htmlspecialchars($pos['volume_formatted']) ?></td>
                                    <td><?= htmlspecialchars($pos['open_price_formatted']) ?></td>
                                    <td><?= htmlspecialchars($pos['current_price_formatted']) ?></td>
                                    <td><span class="<?= (strpos($pos['pnl_formatted'], '-')===false)?'pnl-positive':'pnl-negative' ?>"><?= htmlspecialchars($pos['pnl_formatted']) ?></span></td>
                                    <td><?= htmlspecialchars($pos['opened_at_formatted']) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <script>
                    (function(){
                      var t = document.getElementById('positionsTable');
                      if (!t) return;
                      var cid = parseInt(t.getAttribute('data-client-id')||'0');
                      if (!cid) return;
                      function flagSVG(code){
                        code = String(code||'').toUpperCase();
                        if (!code) return '';
                        if (code==='USD') return '<svg class="flag" viewBox="0 0 60 42"><rect width="60" height="42" fill="#b91c1c"/><rect y="6" width="60" height="6" fill="#fff"/><rect y="18" width="60" height="6" fill="#fff"/><rect y="30" width="60" height="6" fill="#fff"/><rect width="24" height="18" fill="#1e3a8a"/></svg>';
                        if (code==='EUR') return '<svg class="flag" viewBox="0 0 60 42"><rect width="60" height="42" fill="#1e3a8a"/><g fill="#facc15">'+Array(12).fill(0).map(function(_,i){var a=(i*30)*Math.PI/180;var x=30+12*Math.cos(a);var y=21+12*Math.sin(a);return '<circle cx="'+x+'" cy="'+y+'" r="2" />';}).join('')+'</g></svg>';
                        if (code==='GBP') return '<svg class="flag" viewBox="0 0 60 42"><rect width="60" height="42" fill="#1e3a8a"/><path d="M0 19h60v4H0z" fill="#fff"/><path d="M28 0h4v42h-4z" fill="#fff"/><path d="M0 21h60v2H0z" fill="#dc2626"/><path d="M29 0h2v42h-2z" fill="#dc2626"/></svg>';
                        if (code==='JPY') return '<svg class="flag" viewBox="0 0 60 42"><rect width="60" height="42" fill="#fff"/><circle cx="30" cy="21" r="10" fill="#b91c1c"/></svg>';
                        if (code==='CHF') return '<svg class="flag" viewBox="0 0 60 42"><rect width="60" height="42" fill="#dc2626"/><rect x="22" y="10" width="16" height="22" fill="#fff"/><rect x="16" y="16" width="28" height="10" fill="#fff"/></svg>';
                        if (code==='CAD') return '<svg class="flag" viewBox="0 0 60 42"><rect width="60" height="42" fill="#fff"/><rect width="12" height="42" fill="#dc2626"/><rect x="48" width="12" height="42" fill="#dc2626"/><path d="M30 12l3 6h6l-5 4 2 6-6-3-6 3 2-6-5-4h6z" fill="#dc2626"/></svg>';
                        if (code==='AUD' || code==='NZD') return '<svg class="flag" viewBox="0 0 60 42"><rect width="60" height="42" fill="#1e3a8a"/><circle cx="30" cy="21" r="2" fill="#f87171"/></svg>';
                        return '<svg class="flag" viewBox="0 0 60 42"><rect width="60" height="42" fill="#64748b"/></svg>';
                      }
                      var pageSize = 5;
                      var currentPage = 1;
                      var data = [];
                      function renderTable(rows){
                        var tbody = t.querySelector('tbody');
                        tbody.innerHTML = '';
                        for (var i=0;i<rows.length;i++){
                          var r = rows[i];
                          var tr = document.createElement('tr');
                          tr.className = r.status_class || '';
                          var base = r.base_currency || null;
                          var quote = r.quote_currency || null;
                          if ((!base || !quote) && /^[A-Z]{6}$/.test(String(r.symbol||''))) { base = r.symbol.slice(0,3); quote = r.symbol.slice(3,6); }
                          var tcls = (String(r.type||'').toUpperCase()==='BUY') ? 'chip-buy' : 'chip-sell';
                          tr.innerHTML = '<td><span class="flag-pair">'+flagSVG(base)+' '+flagSVG(quote)+'</span>'+escapeHtml(r.symbol)+'</td>'+
                            '<td><span class="chip '+tcls+'">'+escapeHtml(String(r.type||'').toUpperCase())+'</span></td>'+
                            '<td>'+escapeHtml(r.volume_formatted||'')+'</td>'+
                            '<td>'+escapeHtml(r.open_price_formatted||'')+'</td>'+
                            '<td>'+escapeHtml(r.current_price_formatted||'')+'</td>'+
                            '<td><span class="'+((r.pnl>=0)?'pnl-positive':'pnl-negative')+'">'+escapeHtml(r.pnl_formatted||'')+'</span></td>'+
                            '<td>'+escapeHtml(r.opened_at_formatted||'')+'</td>';
                          tbody.appendChild(tr);
                        }
                      }
                      function renderPagination(){
                        var cont = document.getElementById('positionsPagination');
                        if (!cont){ cont = document.createElement('div'); cont.id = 'positionsPagination'; cont.className = 'table-pagination'; t.parentNode.appendChild(cont); }
                        var totalPages = Math.max(1, Math.ceil(data.length / pageSize));
                        var prevDisabled = currentPage <= 1;
                        var nextDisabled = currentPage >= totalPages;
                        cont.innerHTML = '';
                        var prev = document.createElement('button'); prev.className = 'pg-btn'; prev.textContent = 'Anterior'; prev.disabled = prevDisabled;
                        var info = document.createElement('span'); info.className = 'page-indicator'; info.textContent = 'Página ' + currentPage + ' / ' + totalPages;
                        var next = document.createElement('button'); next.className = 'pg-btn'; next.textContent = 'Siguiente'; next.disabled = nextDisabled;
                        prev.onclick = function(){ if (currentPage > 1) { currentPage--; paginate(); } };
                        next.onclick = function(){ var tp = Math.max(1, Math.ceil(data.length / pageSize)); if (currentPage < tp) { currentPage++; paginate(); } };
                        cont.appendChild(prev); cont.appendChild(info); cont.appendChild(next);
                      }
                      function paginate(){
                        var start = (currentPage - 1) * pageSize;
                        var end = start + pageSize;
                        var pageRows = data.slice(start, end);
                        renderTable(pageRows);
                        renderPagination();
                      }
                      function escapeHtml(s){
                        return String(s).replace(/[&<>"]/g,function(c){return({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'})[c]})}
                      var base = window.APP_BASE_PATH || '';
                      function tick(){
                        fetch(base + '/api/client_positions.php?client_id=' + cid)
                          .then(function(r){return r.json()})
                          .then(function(j){ if (j && j.success && Array.isArray(j.positions)) { data = j.positions; currentPage = 1; paginate(); } })
                          .catch(function(_){ });
                      }
                      tick();
                      setInterval(tick, 5000);
                    })();
                    </script>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>
    <div class="panel slide-up" id="activity-panel">
        <div class="panel-header" onclick="togglePanel('activity-panel')">
            <div class="panel-icon">📋</div>
            <h3 class="panel-title">Historial de Actividades</h3>
            <div class="panel-caret">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="6,9 12,15 18,9"></polyline>
                </svg>
            </div>
        </div>
        <div class="collapsible-content">
            <div class="panel-content">
                <?php if (empty($activities)): ?>
                    <div class="empty-state">
                        <div class="empty-icon">📝</div>
                        <h4>No hay actividades registradas</h4>
                        <p>Utiliza las acciones rápidas para comenzar a registrar actividades.</p>
                    </div>
                <?php else: ?>
                    <div id="activityTimeline" class="activity-timeline">
                        <!-- Timeline Header -->
                        <div class="timeline-header">
                            <div class="timeline-column">Fecha de Creación</div>
                            <div class="timeline-column">Actividad</div>
                            <div class="timeline-column">Comentario</div>
                            <div class="timeline-column">Creado Por</div>
                        </div>
                        
                        <!-- Timeline Items -->
                        <?php foreach ($activities as $activity): ?>
                            <div class="timeline-row">
                                <div class="timeline-column" data-label="Fecha de Creación">
                                    <span class="activity-date"><?php echo date('d/m/Y H:i', strtotime($activity['created_at'])); ?></span>
                                </div>
                                <div class="timeline-column" data-label="Actividad">
                                    <div class="activity-type">
                                        <span class="activity-icon">
                                            <?php 
                                            $icon = match($activity['type']) {
                                                'call' => '📞',
                                                'email' => '📧',
                                                'meeting' => '🤝',
                                                'note' => '📝',
                                                'task' => '✅',
                                                'system' => '⚙️',
                                                default => '📌'
                                            };
                                            echo $icon;
                                            ?>
                                        </span>
                                        <span class="activity-name">
                                            <?php 
                                            $typeName = match($activity['type']) {
                                                'call' => 'Llamada',
                                                'email' => 'Email',
                                                'meeting' => 'Reunión',
                                                'task' => 'Tarea',
                                                'note' => 'Nota',
                                                'system' => 'Sistema',
                                                default => 'Actividad'
                                            };
                                            echo $typeName;
                                            ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="timeline-column" data-label="Comentario">
                                    <div class="activity-description">
                                        <?php echo !empty($activity['description']) ? nl2br(htmlspecialchars($activity['description'])) : ''; ?>
                                    </div>
                                </div>
                                <div class="timeline-column" data-label="Creado Por">
                                    <span class="activity-user">
                                        <?php 
                                        if (!empty($activity['creator_name'])) {
                                            echo htmlspecialchars($activity['creator_name']);
                                        } elseif (!empty($activity['creator_username'])) {
                                            echo htmlspecialchars($activity['creator_username']);
                                        } else {
                                            echo 'Sistema';
                                        }
                                        ?>
                                    </span>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <!-- Controles de paginación AJAX -->
                    <?php if ($total_pages > 1): ?>
                        <div class="pagination-controls" style="margin-top: 20px; text-align: center;">
                            <div class="pagination-container">
                                <?php if ($page > 1): ?>
                                    <button class="pagination-btn pagination-prev" onclick="loadActivitiesPage(<?php echo $page - 1; ?>)" title="Página anterior">« Anterior</button>
                                <?php endif; ?>
                                
                                <?php
                                // Calcular rango de páginas a mostrar
                                $start_page = max(1, $page - 2);
                                $end_page = min($total_pages, $page + 2);
                                
                                // Mostrar primera página si es necesario
                                if ($start_page > 1): ?>
                                    <button class="pagination-btn" onclick="loadActivitiesPage(1)">1</button>
                                    <?php if ($start_page > 2): ?>
                                        <span class="pagination-dots">...</span>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
                                    <button class="pagination-btn <?php echo $i == $page ? 'pagination-active' : ''; ?>" onclick="loadActivitiesPage(<?php echo $i; ?>)"><?php echo $i; ?></button>
                                <?php endfor; ?>
                                
                                <?php if ($end_page < $total_pages): ?>
                                    <?php if ($end_page < $total_pages - 1): ?>
                                        <span class="pagination-dots">...</span>
                                    <?php endif; ?>
                                    <button class="pagination-btn" onclick="loadActivitiesPage(<?php echo $total_pages; ?>)"><?php echo $total_pages; ?></button>
                                <?php endif; ?>
                                
                                <?php if ($page < $total_pages): ?>
                                    <button class="pagination-btn pagination-next" onclick="loadActivitiesPage(<?php echo $page + 1; ?>)" title="Página siguiente">Siguiente »</button>
                                <?php endif; ?>
                            </div>
                            <div style="margin-top: 10px; color: #666; font-size: 14px;">
                                Página <?php echo $page; ?> de <?php echo $total_pages; ?> (<?php echo $total_activities; ?> actividades)
                            </div>
                        </div>
                    <?php endif; ?>
                    <?php endif; ?>
                </div>
        </div>
    </div>
</div>

<!-- Context data for JavaScript -->
<script>
    window.leadData = {
        id: <?php echo $lead['id']; ?>,
        name: <?php echo json_encode($lead['name'] ?? ''); ?>,
        currentPage: <?php echo $page; ?>,
        totalPages: <?php echo $total_pages; ?>,
        totalActivities: <?php echo $total_activities; ?>
    };

function togglePanel(panelId) {
    const panel = document.getElementById(panelId);
    if (!panel) return;
    
    const content = panel.querySelector('.collapsible-content');
    const caret = panel.querySelector('.panel-caret');
    const isOpen = panel.classList.contains('is-open');
    
    panel.classList.toggle('is-open', !isOpen);
    
    if (content) {
        if (!isOpen) {
            content.style.maxHeight = content.scrollHeight + 'px';
            content.style.opacity = '1';
        } else {
            content.style.maxHeight = '0px';
            content.style.opacity = '0';
        }
    }
    
    if (caret) {
        caret.style.transform = !isOpen ? 'rotate(180deg)' : 'rotate(0deg)';
    }
}

// Inicialización de paneles
document.addEventListener('DOMContentLoaded', function() {
    // Abrir paneles por defecto, excepto los marcados para iniciar colapsados
    const panels = document.querySelectorAll('.panel');
    panels.forEach(panel => {
        if (panel.classList.contains('start-collapsed')) return;
        panel.classList.add('is-open');
        const content = panel.querySelector('.collapsible-content');
        const caret = panel.querySelector('.panel-caret');
        if (content) {
            content.style.maxHeight = content.scrollHeight + 'px';
            content.style.opacity = '1';
        }
        if (caret) {
            caret.style.transform = 'rotate(180deg)';
        }
    });
    
    // Animaciones de entrada
    const slideUpElements = document.querySelectorAll('.slide-up');
    slideUpElements.forEach((element, index) => {
        element.style.animationDelay = `${index * 0.1}s`;
    });
});
 </script>

<!-- Sistema de Error Logging -->
<script src="error_logger.js"></script>
<script>
// Fallback para errorLogger si no se cargó el script externo
window.errorLogger = window.errorLogger || {
    log: function(){},
    getErrors: function(){ return []; },
    toggleDebugPanel: function(){}
};
// Definir variables globales necesarias
const leadId = <?= json_encode($lead['id']) ?>;

// Configuración específica para el módulo de leads
window.errorLogger.log('Módulo de leads cargado', 'Module Load');

// Interceptar errores específicos del módulo
window.addEventListener('load', function() {
    console.log('🚨 Sistema de error logging activado para módulo de leads');
    
    // Verificar que saveComment esté disponible
    if (typeof saveComment === 'function') {
        window.errorLogger.log('Función saveComment disponible', 'Function Check');
    } else {
        window.errorLogger.log('Función saveComment NO disponible', 'Function Error');
    }
    
    // Verificar elementos críticos
    const criticalElements = [
        'commentSubject',
        'commentDescription',
        'commentDate'
    ];
    
    criticalElements.forEach(elementId => {
        const element = document.getElementById(elementId);
        if (element) {
            window.errorLogger.log(`Elemento ${elementId} encontrado`, 'Element Check');
        } else {
            window.errorLogger.log(`Elemento ${elementId} NO encontrado`, 'Element Error');
        }
    });
    
    // Verificar que el lead ID esté disponible globalmente
    if (typeof leadId !== 'undefined' && leadId) {
        window.errorLogger.log(`Lead ID disponible: ${leadId}`, 'Data Check');
    } else {
        window.errorLogger.log('Lead ID NO disponible en variable global', 'Data Error');
    }
});

// Mostrar panel de debug automáticamente si hay errores
setTimeout(() => {
    if (window.errorLogger.getErrors().length > 0) {
        window.errorLogger.toggleDebugPanel();
    }
}, 2000);

// Función para abrir el modal de cita con verificación de disponibilidad
function openAppointmentModal() {
    const clientName = <?= json_encode(trim(($lead['first_name'] ?? '') . ' ' . ($lead['last_name'] ?? ''))) ?> || 'Lead';
    const leadId = <?= json_encode((int)$lead['id']) ?>;
    
    // Verificar que ProfixCRM esté disponible
    if (window.ProfixCRM && typeof window.ProfixCRM.openAppointmentAssistant === 'function') {
        window.ProfixCRM.openAppointmentAssistant({
            clientName: clientName,
            leadId: leadId
        });
    } else {
        // Si ProfixCRM no está disponible, mostrar error o intentar alternativa
        console.error('ProfixCRM u openAppointmentAssistant no están disponibles');
        alert('Error: La función de programación de citas no está disponible. Por favor, recarga la página.');
    }
}
</script>

<?php if (isset($_GET['message']) && $_GET['message']==='password_changed'): ?>
<div class="modal-backdrop" id="leadPwdSuccessBackdrop" style="position:fixed;inset:0;display:flex;align-items:center;justify-content:center;z-index:10000;background: rgba(15,23,42,0.45);">
  <div class="modal modal-notification modal-success" style="position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:10001;background:#fff;border-radius:12px;box-shadow:0 10px 15px rgba(0,0,0,0.15);min-width:420px;max-width:640px;width:calc(100% - 2rem);overflow:hidden;">
    <div class="modal-header">
      <div class="modal-title"><div class="modal-icon">✅</div><h3>Contraseña actualizada</h3></div>
      <button type="button" class="btn btn-ghost" id="leadPwdSuccessClose">×</button>
    </div>
    <div class="modal-body">
      <p>La contraseña del Trader Room se actualizó correctamente.</p>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-primary" id="leadPwdSuccessOk">Entendido</button>
    </div>
  </div>
</div>
<script>
(function(){
  var bd=document.getElementById('leadPwdSuccessBackdrop');
  if(!bd) return;
  var ok=document.getElementById('leadPwdSuccessOk');
  var cl=document.getElementById('leadPwdSuccessClose');
  var close=function(){ if(bd&&bd.parentNode){ bd.parentNode.removeChild(bd); } };
  if(ok) ok.onclick=close;
  if(cl) cl.onclick=close;
  bd.addEventListener('click', function(e){ if(e.target===bd) close(); });
  try{
    var u=new URL(window.location);
    u.searchParams.delete('message');
    history.replaceState({}, document.title, u.toString());
  }catch(_){ }
})();
</script>
<?php endif; ?>

<!-- Nuevo Modal de Asistente Guiado para Comentarios -->
<div id="commentWizardModal" class="wizard-modal">
    <div class="wizard-container">
        <div class="wizard-header">
            <div class="wizard-progress">
                <div class="progress-step active" data-step="1">
                    <div class="step-number">1</div>
                    <div class="step-label">Tipo</div>
                </div>
                <div class="progress-line"></div>
                <div class="progress-step" data-step="2">
                    <div class="step-number">2</div>
                    <div class="step-label">Comentario</div>
                </div>
                <div class="progress-line"></div>
                <div class="progress-step" data-step="3">
                    <div class="step-number">3</div>
                    <div class="step-label">Confirmar</div>
                </div>
            </div>
            <button type="button" class="wizard-close" onclick="closeCommentWizard()">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="18" y1="6" x2="6" y2="18"></line>
                    <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
            </button>
        </div>

        <div class="wizard-content">
            <!-- Paso 1: Seleccionar Tipo de Comentario -->
            <div class="wizard-step active" data-step="1">
                <div class="step-header">
                    <h3>¿Qué tipo de comentario deseas agregar?</h3>
                    <p>Selecciona el tipo que mejor describa tu actividad</p>
                </div>
                <div class="comment-types">
                    <div class="comment-type-card" data-type="call">
                        <div class="type-icon">📞</div>
                        <div class="type-title">Llamada</div>
                        <div class="type-description">Registro de una llamada telefónica</div>
                    </div>
                    <div class="comment-type-card" data-type="email">
                        <div class="type-icon">📧</div>
                        <div class="type-title">Email</div>
                        <div class="type-description">Comunicación por correo electrónico</div>
                    </div>
                    <div class="comment-type-card" data-type="meeting">
                        <div class="type-icon">🤝</div>
                        <div class="type-title">Reunión</div>
                        <div class="type-description">Encuentro presencial o virtual</div>
                    </div>
                    <div class="comment-type-card" data-type="note">
                        <div class="type-icon">📝</div>
                        <div class="type-title">Nota</div>
                        <div class="type-description">Comentario o recordatorio general</div>
                    </div>
                </div>
            </div>

            <!-- Paso 2: Escribir Comentario -->
            <div class="wizard-step" data-step="2">
                <div class="step-header">
                    <h3>Escribe tu comentario</h3>
                    <p>Proporciona los detalles de la actividad</p>
                </div>
                <form id="commentForm" class="comment-form">
                    <div class="form-group">
                        <label for="commentSubject">Asunto *</label>
                        <input type="text" id="commentSubject" class="form-input" required 
                               placeholder="Ej: Llamada de seguimiento comercial">
                    </div>
                    <div class="form-group">
                        <label for="commentDescription">Descripción *</label>
                        <textarea id="commentDescription" class="form-textarea" required rows="6"
                                  placeholder="Describe los detalles de la actividad: qué se discutió, resultados obtenidos, próximos pasos, etc."></textarea>
                    </div>
                    <div class="form-group">
                        <label for="commentDate">Fecha y hora</label>
                        <input type="datetime-local" id="commentDate" class="form-input">
                    </div>
                </form>
            </div>

            <!-- Paso 3: Confirmar -->
            <div class="wizard-step" data-step="3">
                <div class="step-header">
                    <h3>Confirma tu comentario</h3>
                    <p>Revisa la información antes de guardar</p>
                </div>
                <div class="comment-preview">
                    <div class="preview-item">
                        <strong>Tipo:</strong> <span id="previewType"></span>
                    </div>
                    <div class="preview-item">
                        <strong>Asunto:</strong> <span id="previewSubject"></span>
                    </div>
                    <div class="preview-item">
                        <strong>Descripción:</strong> <span id="previewDescription"></span>
                    </div>
                    <div class="preview-item">
                        <strong>Fecha:</strong> <span id="previewDate"></span>
                    </div>
                    <div class="preview-item">
                        <strong>Creado por:</strong> <?php echo htmlspecialchars($_SESSION['user_name'] ?? 'Usuario Actual'); ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="wizard-actions">
            <button type="button" class="wizard-btn wizard-btn-secondary" id="prevBtn" onclick="previousStep()" style="display: none;">
                Anterior
            </button>
            <button type="button" class="wizard-btn wizard-btn-primary" id="nextBtn" onclick="nextStep()">
                Siguiente
            </button>
            <button type="button" class="wizard-btn wizard-btn-success" id="saveBtn" onclick="saveComment()" style="display: none;">
                Guardar Comentario
            </button>
        </div>
    </div>
</div>

<!-- Context data for JavaScript -->
<script>
    window.leadData = {
        id: <?php echo $lead['id']; ?>,
        name: <?php echo json_encode($full_name); ?>,
        email: <?php echo json_encode($emailDisplay); ?>,
        phone: <?php echo json_encode($phoneDisplay); ?>,
        desk_id: <?php echo (int)($lead['desk_id'] ?? 0); ?>,
        status: <?php echo json_encode($lead['status'] ?? 'new'); ?>
    };
</script>

<!-- Modal de Resultado del Comentario -->
<div id="resultModal" class="result-modal" style="display: none;">
    <div class="result-modal-content">
        <div class="result-modal-header">
            <h3 id="resultTitle">✅ Comentario Agregado</h3>
            <button type="button" class="result-close-btn" onclick="closeResultModal()">&times;</button>
        </div>
        <div class="result-modal-body">
            <div class="result-success-icon">
                <i class="fas fa-check-circle"></i>
            </div>
            <div class="result-details">
                <h4 id="resultSubject"></h4>
                <p id="resultDescription"></p>
                <div class="result-meta">
                    <span class="result-type" id="resultType"></span>
                    <span class="result-date" id="resultDate"></span>
                </div>
            </div>
        </div>
        <div class="result-modal-footer">
            <button type="button" class="result-btn result-btn-primary" onclick="closeResultModal()">
                Continuar
            </button>
        </div>
    </div>
</div>

<script>
<?php include __DIR__ . '/view_scripts.js'; ?>
</script>

<script>
// Definir variables globales necesarias (evitar duplicados)
if (typeof leadId === 'undefined') {
    const leadId = <?= json_encode($lead['id']) ?>;
}

// Configurar window.leadData para la paginación
window.leadData = window.leadData || { id: <?= json_encode($lead['id']) ?> };

// Configuración específica para el módulo de leads
window.errorLogger.log('Módulo de leads cargado', 'Module Load');

// Interceptar errores específicos del módulo
window.addEventListener('load', function() {
    console.log('🚨 Sistema de error logging activado para módulo de leads');
    
    // Verificar que saveComment esté disponible
    if (typeof saveComment === 'function') {
        window.errorLogger.log('Función saveComment disponible', 'Function Check');
    } else {
        window.errorLogger.log('Función saveComment NO disponible', 'Function Error');
    }
    
    // Verificar elementos críticos
    const criticalElements = [
        'commentSubject',
        'commentDescription',
        'commentDate'
    ];
    
    criticalElements.forEach(elementId => {
        const element = document.getElementById(elementId);
        if (element) {
            window.errorLogger.log(`Elemento ${elementId} encontrado`, 'Element Check');
        } else {
            window.errorLogger.log(`Elemento ${elementId} NO encontrado`, 'Element Error');
        }
    });
    
    // Verificar que el lead ID esté disponible globalmente
    if (typeof leadId !== 'undefined' && leadId) {
        window.errorLogger.log(`Lead ID disponible: ${leadId}`, 'Data Check');
    } else {
        window.errorLogger.log('Lead ID NO disponible en variable global', 'Data Error');
    }
});

// Mostrar panel de debug automáticamente si hay errores
setTimeout(() => {
    if (window.errorLogger.getErrors().length > 0) {
        window.errorLogger.toggleDebugPanel();
    }
}, 2000);
</script>
