<?php
/**
 * ASISMA CRM - Ficha de Detalle de Lead
 */
$_estados = arr_estados_embudo();
$estActual = isset($_estados[$lead['estado_embudo']]) ? $_estados[$lead['estado_embudo']] : array('label' => $lead['estado_embudo'], 'color' => 'bg-slate-800 text-slate-300 border-slate-700');
$esAdmin      = SessionHelper::isAdmin();
$datosVisibles = $lead['datos_liberados'] || $esAdmin;
$telMostrar    = $datosVisibles ? $lead['telefono_real'] : (isset($lead['telefono_enmascarado']) ? $lead['telefono_enmascarado'] : '****');
$correoMostrar = $datosVisibles ? (isset($lead['correo_real']) ? $lead['correo_real'] : '') : (isset($lead['correo_enmascarado']) ? $lead['correo_enmascarado'] : '');
?>
<!-- Header -->
<div class="mb-8 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
    <div>
        <a href="<?php echo APP_URL; ?>/leads" class="inline-flex items-center gap-1.5 text-xs text-slate-500 hover:text-slate-300 font-semibold mb-3">
            <i data-lucide="arrow-left" class="w-3.5 h-3.5"></i>
            <span>Volver al Listado</span>
        </a>
        <div class="flex items-center gap-3">
            <h1 class="text-3xl font-extrabold text-white tracking-tight"><?php echo htmlspecialchars($lead['contacto_nombre']); ?></h1>
            <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold border <?php echo $estActual['color']; ?>">
                <?php echo $estActual['label']; ?>
            </span>
        </div>
        <?php if (!empty($lead['empresa_razon_social'])): ?>
        <p class="text-slate-400 text-sm mt-1">Empresa: <strong class="text-slate-200"><?php echo htmlspecialchars($lead['empresa_razon_social']); ?></strong></p>
        <?php endif; ?>
    </div>

    <!-- Action quick toggles -->
    <div class="flex flex-wrap gap-3">
        <?php if (!$datosVisibles): ?>
        <!-- Liberar Datos button -->
        <button id="btnLiberarDatos"
                class="px-4 py-2.5 bg-amber-600 hover:bg-amber-500 text-white rounded-xl text-sm font-semibold transition-colors flex items-center gap-1.5 shadow-md shadow-amber-600/10">
            <i data-lucide="unlock" class="w-4 h-4"></i>
            <span>Aceptar Lead y Ver Datos</span>
        </button>
        <?php else: ?>
        <span class="px-4 py-2.5 bg-emerald-900/30 border border-emerald-700/40 text-emerald-400 rounded-xl text-sm font-semibold flex items-center gap-1.5">
            <i data-lucide="lock-open" class="w-4 h-4"></i>
            <span>Datos liberados</span>
        </span>
        <?php endif; ?>

        <a href="<?php echo APP_URL; ?>/leads/editar?id=<?php echo $lead['id']; ?>"
           class="px-4 py-2.5 bg-slate-900 hover:bg-slate-800 border border-slate-800 text-slate-200 rounded-xl text-sm font-semibold transition-colors flex items-center gap-1.5">
            <i data-lucide="pencil" class="w-4 h-4 text-slate-400"></i>
            <span>Editar</span>
        </a>

        <?php if (SessionHelper::isAdmin()): ?>
        <!-- Reasignar: SOLO el superadmin de la matriz -->
        <button onclick="$('#reassignPanel').toggleClass('hidden')"
                class="px-4 py-2.5 bg-slate-900 hover:bg-slate-800 border border-slate-800 text-slate-200 rounded-xl text-sm font-semibold transition-colors flex items-center gap-1.5">
            <i data-lucide="user-cog" class="w-4 h-4 text-slate-400"></i>
            <span>Reasignar</span>
        </button>
        <?php endif; ?>

        <?php if (SessionHelper::hasPermiso('whatsapp')): ?>
        <a href="<?php echo APP_URL; ?>/whatsapp?lead_id=<?php echo $lead['id']; ?>"
           class="px-4 py-2.5 bg-emerald-600 hover:bg-emerald-500 text-white rounded-xl text-sm font-semibold transition-all shadow-md shadow-emerald-600/10 flex items-center gap-1.5">
            <i data-lucide="message-circle" class="w-4 h-4"></i>
            <span>Chat WhatsApp</span>
        </a>
        <?php endif; ?>

        <a href="<?php echo APP_URL; ?>/cotizaciones/crear?lead_id=<?php echo $lead['id']; ?>"
           class="px-4 py-2.5 bg-blue-600 hover:bg-blue-500 text-white rounded-xl text-sm font-semibold transition-all shadow-md shadow-blue-600/10 flex items-center gap-1.5">
            <i data-lucide="file-signature" class="w-4 h-4"></i>
            <span>Crear Cotización</span>
        </a>
    </div>
</div>

<?php if (SessionHelper::isAdmin()): ?>
<!-- Reasignar Panel (solo superadmin; los endpoints tambien lo exigen) -->
<div id="reassignPanel" class="hidden bg-slate-900 border border-slate-800 rounded-2xl p-6 shadow-xl mb-8 space-y-6">
    <div>
        <h3 class="text-sm font-bold text-white mb-4 uppercase tracking-wider">Asignar Vendedor de la Franquicia</h3>
        <form id="reassignForm" class="flex flex-col sm:flex-row gap-4 items-end">
            <input type="hidden" name="lead_id" value="<?php echo $lead['id']; ?>">
            <div class="flex-1">
                <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Seleccionar Vendedor</label>
                <select name="usuario_asignado_id" required
                        class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-800 rounded-xl text-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">-- Seleccionar Vendedor --</option>
                    <?php foreach ($usuarios as $usr): ?>
                        <option value="<?php echo $usr['id']; ?>" <?php echo $lead['usuario_asignado_id'] == $usr['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($usr['nombre']); ?> (<?php echo htmlspecialchars($usr['empresa_nombre']); ?> - <?php echo $usr['rol']; ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="submit" class="px-5 py-2.5 bg-blue-600 hover:bg-blue-500 text-white font-semibold rounded-xl text-sm transition-colors">
                Confirmar Asignación
            </button>
        </form>
    </div>

    <?php if (!empty($puedeDerivar)): ?>
    <div class="border-t border-slate-800 pt-5">
        <h3 class="text-sm font-bold text-white mb-1 uppercase tracking-wider">Derivar a Otro Franquiciado</h3>
        <p class="text-xs text-slate-500 mb-4">Solo aparecen franquiciados de la misma región y vertical que comercializan la marca/producto de este lead. El lead quedará sin vendedor en el destino.</p>
        <?php if (!empty($franquiciadosElegibles)): ?>
        <form id="derivarFranquiciadoForm" class="flex flex-col sm:flex-row gap-4 items-end">
            <input type="hidden" name="lead_id" value="<?php echo $lead['id']; ?>">
            <div class="flex-1">
                <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Franquiciado de Destino</label>
                <select name="franquiciado_id" required
                        class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-800 rounded-xl text-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-amber-500">
                    <option value="">-- Seleccionar Franquiciado --</option>
                    <?php foreach ($franquiciadosElegibles as $fe): ?>
                        <option value="<?php echo $fe['id']; ?>"><?php echo htmlspecialchars($fe['nombre_fantasia']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="submit" class="px-5 py-2.5 bg-amber-600 hover:bg-amber-500 text-white font-semibold rounded-xl text-sm transition-colors">
                Derivar Lead
            </button>
        </form>
        <?php else: ?>
        <p class="text-xs text-amber-400/80 bg-amber-500/10 border border-amber-500/20 rounded-xl px-3 py-2">No hay otros franquiciados en la misma región y vertical con la marca de este lead.</p>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>
<?php endif; // fin panel reasignar (solo superadmin) ?>

<!-- Main detailed Grid -->
<div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
    
    <!-- Left column: Ficha and State Update -->
    <div class="lg:col-span-1 space-y-8">
        
        <!-- Ficha de Datos -->
        <div class="bg-slate-900 border border-slate-800/80 rounded-2xl p-6 shadow-xl">
            <h3 class="text-sm font-bold text-white mb-6 uppercase tracking-wider border-b border-slate-800 pb-2 flex items-center gap-2">
                <i data-lucide="info" class="w-4 h-4 text-blue-500"></i>
                <span>Ficha del Lead</span>
            </h3>

            <div class="space-y-4 text-sm">
                <div>
                    <span class="text-xs text-slate-500 block">Contacto Directo</span>
                    <span class="font-bold text-slate-200 block mt-0.5"><?php echo htmlspecialchars($lead['contacto_nombre']); ?></span>
                    <span class="text-xs text-slate-400"><?php echo htmlspecialchars(isset($lead['contacto_cargo']) ? $lead['contacto_cargo'] : 'Cargo no registrado'); ?></span>
                </div>
                
                <div>
                    <span class="text-xs text-slate-500 block">Teléfono / WhatsApp</span>
                    <?php if ($datosVisibles): ?>
                    <div class="flex items-center gap-1.5 mt-0.5">
                        <a href="https://wa.me/<?php echo preg_replace('/[^\d]/', '', $lead['telefono_real']); ?>" target="_blank"
                           class="font-mono text-blue-400 hover:underline flex items-center gap-1">
                            <i data-lucide="phone" class="w-3.5 h-3.5"></i>
                            <span id="telefonoReal"><?php echo htmlspecialchars($lead['telefono_real']); ?></span>
                        </a>
                        <button type="button" onclick="copiarTexto('<?php echo htmlspecialchars($lead['telefono_real']); ?>', this)" title="Copiar teléfono"
                                class="p-1 rounded-md text-slate-500 hover:text-white hover:bg-slate-800 transition-colors">
                            <i data-lucide="copy" class="w-3.5 h-3.5"></i>
                        </button>
                    </div>
                    <?php else: ?>
                    <div class="flex items-center gap-2 mt-0.5">
                        <span class="font-mono text-amber-400"><?php echo htmlspecialchars($telMostrar); ?></span>
                        <span class="text-[10px] text-amber-500 bg-amber-500/10 px-1.5 py-0.5 rounded">oculto</span>
                    </div>
                    <?php endif; ?>
                </div>

                <div>
                    <span class="text-xs text-slate-500 block">Correo Electrónico</span>
                    <?php if ($datosVisibles && !empty($correoMostrar)): ?>
                    <span class="font-mono text-slate-300 block mt-0.5" id="correoReal"><?php echo htmlspecialchars($correoMostrar); ?></span>
                    <?php elseif (!$datosVisibles && !empty($correoMostrar)): ?>
                    <div class="flex items-center gap-2 mt-0.5">
                        <span class="font-mono text-amber-400"><?php echo htmlspecialchars($correoMostrar); ?></span>
                        <span class="text-[10px] text-amber-500 bg-amber-500/10 px-1.5 py-0.5 rounded">oculto</span>
                    </div>
                    <?php else: ?>
                    <span class="text-slate-500 text-xs italic">No registrado</span>
                    <?php endif; ?>
                </div>

                <div>
                    <span class="text-xs text-slate-500 block">Región</span>
                    <span class="text-slate-300 block mt-0.5"><?php echo htmlspecialchars($lead['region_nombre']); ?></span>
                </div>

                <div class="border-t border-slate-800/80 pt-4">
                    <span class="text-xs text-slate-500 block">Interés de Negocio</span>
                    <div class="mt-1 space-y-1">
                        <span class="inline-flex items-center rounded bg-blue-500/10 px-2 py-0.5 text-xs font-semibold text-blue-400 border border-blue-500/20">
                            Vertical: <?php echo htmlspecialchars($lead['vertical_nombre']); ?>
                        </span>
                        <?php if (!empty($lead['marca_nombre'])): ?>
                            <div class="text-xs text-slate-300 font-semibold mt-1">Marca: <?php echo htmlspecialchars($lead['marca_nombre']); ?></div>
                        <?php endif; ?>
                        <?php if (!empty($lead['producto_nombre'])): ?>
                            <div class="text-xs text-slate-400">Producto: <?php echo htmlspecialchars($lead['producto_nombre']); ?></div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="border-t border-slate-800/80 pt-4">
                    <span class="text-xs text-slate-500 block">Origen del Lead</span>
                    <span class="text-xs font-semibold text-slate-300 capitalize block mt-0.5">
                        <?php $_orig = arr_origenes_lead(); echo isset($_orig[$lead['origen']]) ? $_orig[$lead['origen']] : $lead['origen']; ?>
                    </span>
                </div>

                <div class="border-t border-slate-800/80 pt-4 text-xs text-slate-500 flex justify-between">
                    <span>Creado: <?php echo date('d/m/Y H:i', strtotime($lead['created_at'])); ?></span>
                    <span>ID: #<?php echo $lead['id']; ?></span>
                </div>
            </div>
        </div>

        <!-- Actualizar Estado del Embudo -->
        <div class="bg-slate-900 border border-slate-800/80 rounded-2xl p-6 shadow-xl">
            <h3 class="text-sm font-bold text-white mb-6 uppercase tracking-wider border-b border-slate-800 pb-2 flex items-center gap-2">
                <i data-lucide="milestone" class="w-4 h-4 text-indigo-500"></i>
                <span>Avanzar Embudo</span>
            </h3>

            <form id="stateForm" class="space-y-4">
                <input type="hidden" name="lead_id" value="<?php echo $lead['id']; ?>">
                
                <div>
                    <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Seleccionar Estado</label>
                    <select name="estado" id="funnelStateSelect"
                            class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-800 rounded-xl text-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <?php foreach (arr_estados_embudo() as $key => $est): ?>
                            <option value="<?php echo $key; ?>" <?php echo $lead['estado_embudo'] === $key ? 'selected' : ''; ?>><?php echo $est['label']; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Perdido Fields (Hidden by default unless 'perdido' is chosen) -->
                <div id="lostFields" class="<?php echo $lead['estado_embudo'] === ESTADO_PERDIDO ? '' : 'hidden'; ?> space-y-4 border-t border-slate-800 pt-4">
                    <div>
                        <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Motivo de Pérdida *</label>
                        <select name="motivo_perdida" id="motivo_perdida"
                                class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-800 rounded-xl text-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">-- Seleccionar Motivo --</option>
                            <?php foreach (arr_motivos_perdida() as $key => $label): ?>
                                <option value="<?php echo $key; ?>" <?php echo $lead['motivo_perdida'] === $key ? 'selected' : ''; ?>><?php echo $label; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Notas Adicionales de Pérdida</label>
                        <textarea name="nota_perdida" rows="3"
                                  class="block w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                                  placeholder="Detalle los motivos..."><?php echo htmlspecialchars(isset($lead['nota_perdida']) ? $lead['nota_perdida'] : ''); ?></textarea>
                    </div>
                </div>

                <button type="submit" class="w-full py-2.5 bg-indigo-600 hover:bg-indigo-500 text-white font-semibold rounded-xl text-sm transition-colors shadow-md">
                    Actualizar Estado
                </button>
            </form>
        </div>

    </div>

    <!-- Right Column: CRM Activity Log -->
    <div class="lg:col-span-2 bg-slate-900 border border-slate-800/80 rounded-2xl p-6 shadow-xl flex flex-col min-h-[500px]">
        <h3 class="text-sm font-bold text-white mb-6 uppercase tracking-wider border-b border-slate-800 pb-2 flex items-center gap-2">
            <i data-lucide="message-square" class="w-4 h-4 text-emerald-500"></i>
            <span>Historial de Actividades e Interacciones</span>
        </h3>

        <!-- Add Activity Form -->
        <form id="activityForm" class="mb-8 space-y-4 bg-slate-950 border border-slate-850 p-4 rounded-xl">
            <input type="hidden" name="lead_id" value="<?php echo $lead['id']; ?>">
            
            <div class="flex flex-col sm:flex-row gap-4">
                <div class="flex-1">
                    <input type="text" name="asunto" required
                           class="block w-full px-3 py-2 bg-slate-900 border border-slate-800 rounded-lg text-slate-200 text-xs focus:outline-none focus:ring-2 focus:ring-blue-500"
                           placeholder="Asunto: ej. Llamada de seguimiento, correo enviado...">
                </div>
                <div class="w-full sm:w-44">
                    <select name="tipo"
                            class="block w-full px-3 py-2 bg-slate-900 border border-slate-800 rounded-lg text-slate-300 text-xs focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="nota">Nota Manual</option>
                        <option value="llamada">Llamada telefónica</option>
                        <option value="correo">Correo electrónico</option>
                        <option value="reunion">Reunión / Videollamada</option>
                    </select>
                </div>
            </div>

            <div>
                <textarea name="detalles" rows="3" required
                          class="block w-full px-3 py-2 bg-slate-900 border border-slate-800 rounded-lg text-slate-200 text-xs focus:outline-none focus:ring-2 focus:ring-blue-500"
                          placeholder="Escriba los detalles de la interacción aquí..."></textarea>
            </div>

            <div class="flex justify-end">
                <button type="submit" id="addActivityBtn"
                        class="px-4 py-2 bg-emerald-600 hover:bg-emerald-500 text-white font-semibold rounded-lg text-xs transition-colors flex items-center gap-1">
                    <i data-lucide="plus" class="w-3.5 h-3.5"></i>
                    <span>Agregar Actividad</span>
                </button>
            </div>
        </form>

        <!-- Activities Feed list -->
        <div class="flex-1 overflow-y-auto space-y-6 pr-2 max-h-[500px]" id="activitiesFeed">
            <?php if (empty($actividades)): ?>
                <div class="text-center py-12 text-slate-500" id="emptyActivityMsg">
                    <i data-lucide="history" class="w-8 h-8 mx-auto mb-2 text-slate-600"></i>
                    <p class="text-xs">No se registran actividades para este lead.</p>
                </div>
            <?php else: ?>
                <?php foreach ($actividades as $act): ?>
                    <?php
                    // Resolver icono según el tipo
                    $icon = 'sticky-note';
                    $iconColor = 'text-slate-400 bg-slate-800/80';
                    switch ($act['tipo']) {
                        case 'whatsapp':
                            $icon = 'message-circle';
                            $iconColor = 'text-emerald-400 bg-emerald-500/10';
                            break;
                        case 'llamada':
                            $icon = 'phone';
                            $iconColor = 'text-blue-400 bg-blue-500/10';
                            break;
                        case 'correo':
                            $icon = 'mail';
                            $iconColor = 'text-purple-400 bg-purple-500/10';
                            break;
                        case 'reunion':
                            $icon = 'video';
                            $iconColor = 'text-amber-400 bg-amber-500/10';
                            break;
                        case 'sistema':
                            $icon = 'cpu';
                            $iconColor = 'text-indigo-400 bg-indigo-500/10 border border-indigo-500/20';
                            break;
                    }
                    ?>
                    <div class="flex gap-4 items-start relative group">
                        <!-- Icon -->
                        <div class="w-8 h-8 rounded-lg flex items-center justify-center shrink-0 <?php echo $iconColor; ?>">
                            <i data-lucide="<?php echo $icon; ?>" class="w-4 h-4"></i>
                        </div>
                        
                        <!-- Log Details -->
                        <div class="flex-1 min-w-0 bg-slate-950/40 border border-slate-850 p-4 rounded-xl">
                            <div class="flex justify-between items-start gap-4">
                                <h4 class="text-xs font-bold text-slate-200"><?php echo htmlspecialchars($act['asunto']); ?></h4>
                                <span class="text-[10px] text-slate-500 font-mono shrink-0"><?php echo date('d-m-Y H:i', strtotime($act['created_at'])); ?></span>
                            </div>
                            <p class="text-xs text-slate-400 mt-2 leading-relaxed whitespace-pre-wrap"><?php echo htmlspecialchars($act['detalles']); ?></p>
                            
                            <!-- Author -->
                            <div class="mt-3 flex items-center gap-1.5 text-[10px] text-slate-500 font-semibold uppercase tracking-wider">
                                <i data-lucide="user" class="w-3 h-3"></i>
                                <span><?php echo htmlspecialchars(isset($act['usuario_nombre']) ? $act['usuario_nombre'] : 'Sistema ASISMA'); ?></span>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

    </div>

</div>

<!-- jQuery Script for Dynamic form interactions -->
<script>
    $(document).ready(function() {
        
        // 1. Funnel state selector toggle fields (Lost)
        $('#funnelStateSelect').on('change', function() {
            if ($(this).val() === 'perdido') {
                $('#lostFields').removeClass('hidden');
            } else {
                $('#lostFields').addClass('hidden');
            }
        });

        // 2. Submit change funnel state
        $('#stateForm').on('submit', function(e) {
            e.preventDefault();
            const formData = $(this).serialize();

            $.ajax({
                url: '<?php echo APP_URL; ?>/leads/cambiar-estado',
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Estado Actualizado',
                            text: response.message,
                            background: '#1e293b',
                            color: '#f8fafc',
                            confirmButtonColor: '#3b82f6',
                            timer: 1500,
                            showConfirmButton: false
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error al cambiar estado',
                            text: response.message,
                            background: '#1e293b',
                            color: '#f8fafc',
                            confirmButtonColor: '#3b82f6'
                        });
                    }
                }
            });
        });

        // 3. Submit Manual reassign form
        $('#reassignForm').on('submit', function(e) {
            e.preventDefault();
            const formData = $(this).serialize();

            $.ajax({
                url: '<?php echo APP_URL; ?>/leads/asignar',
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Asignación Actualizada',
                            text: response.message,
                            background: '#1e293b',
                            color: '#f8fafc',
                            confirmButtonColor: '#3b82f6',
                            timer: 1500,
                            showConfirmButton: false
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error de Asignación',
                            text: response.message,
                            background: '#1e293b',
                            color: '#f8fafc',
                            confirmButtonColor: '#3b82f6'
                        });
                    }
                }
            });
        });

        // 3b. Derivar el lead a OTRO franquiciado (misma región/vertical/marca)
        $('#derivarFranquiciadoForm').on('submit', function(e) {
            e.preventDefault();
            const formData = $(this).serialize();
            const nombreDestino = $(this).find('select[name="franquiciado_id"] option:selected').text();

            Swal.fire({
                title: '¿Derivar este lead?',
                text: 'El lead pasará a ' + nombreDestino + ' y quedará sin vendedor asignado en esa franquicia.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Sí, derivar',
                cancelButtonText: 'Cancelar',
                background: '#1e293b',
                color: '#f8fafc',
                confirmButtonColor: '#d97706'
            }).then(function(result) {
                if (!result.isConfirmed) return;
                $.ajax({
                    url: '<?php echo APP_URL; ?>/leads/reasignar-franquiciado',
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Lead Derivado',
                                text: response.message,
                                background: '#1e293b',
                                color: '#f8fafc',
                                confirmButtonColor: '#3b82f6',
                                timer: 2000,
                                showConfirmButton: false
                            }).then(function() { location.reload(); });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'No se pudo derivar',
                                text: response.message,
                                background: '#1e293b',
                                color: '#f8fafc',
                                confirmButtonColor: '#3b82f6'
                            });
                        }
                    }
                });
            });
        });

        // 0. Liberar datos del lead
        $('#btnLiberarDatos').on('click', function() {
            Swal.fire({
                title: '¿Aceptar este lead?',
                text: 'Confirmas que quieres tomar este lead y acceder a los datos reales de contacto.',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Sí, aceptar',
                cancelButtonText: 'Cancelar',
                background: '#1e293b',
                color: '#f8fafc',
                confirmButtonColor: '#d97706'
            }).then(function(result) {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '<?php echo APP_URL; ?>/leads/liberar-datos',
                        type: 'POST',
                        data: { lead_id: <?php echo $lead['id']; ?> },
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: '¡Lead aceptado!',
                                    text: response.message,
                                    background: '#1e293b',
                                    color: '#f8fafc',
                                    confirmButtonColor: '#3b82f6',
                                    timer: 1500,
                                    showConfirmButton: false
                                }).then(function() { location.reload(); });
                            } else {
                                Swal.fire({ icon: 'error', title: 'Error', text: response.message, background: '#1e293b', color: '#f8fafc' });
                            }
                        }
                    });
                }
            });
        });

        // 4. Submit Activity Note form
        $('#activityForm').on('submit', function(e) {
            e.preventDefault();
            
            $('#addActivityBtn').attr('disabled', true).addClass('opacity-80');
            const formData = $(this).serialize();

            $.ajax({
                url: '<?php echo APP_URL; ?>/leads/guardar-nota',
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        // Limpiar formulario
                        $('#activityForm')[0].reset();
                        
                        // Quitar mensaje de vacío si estaba visible
                        $('#emptyActivityMsg').remove();

                        // Icono dinámico según el tipo ingresado
                        const tipo = $('#activityForm select[name="tipo"]').val() || 'nota';
                        let icon = 'sticky-note';
                        let colorClass = 'text-slate-400 bg-slate-800/80';
                        if (tipo === 'llamada') { icon = 'phone'; colorClass = 'text-blue-400 bg-blue-500/10'; }
                        if (tipo === 'correo') { icon = 'mail'; colorClass = 'text-purple-400 bg-purple-500/10'; }
                        if (tipo === 'reunion') { icon = 'video'; colorClass = 'text-amber-400 bg-amber-500/10'; }

                        // Inyectar la nota en el feed en la parte superior
                        const notaHtml = `
                            <div class="flex gap-4 items-start relative group animate-fade-in">
                                <div class="w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${colorClass}">
                                    <i data-lucide="${icon}" class="w-4 h-4"></i>
                                </div>
                                <div class="flex-1 min-w-0 bg-slate-950/40 border border-slate-850 p-4 rounded-xl">
                                    <div class="flex justify-between items-start gap-4">
                                        <h4 class="text-xs font-bold text-slate-200">${response.data.asunto || 'Nota manual'}</h4>
                                        <span class="text-[10px] text-slate-500 font-mono shrink-0">${response.data.created_at}</span>
                                    </div>
                                    <p class="text-xs text-slate-400 mt-2 leading-relaxed whitespace-pre-wrap">${$('#activityForm textarea[name="detalles"]').val()}</p>
                                    <div class="mt-3 flex items-center gap-1.5 text-[10px] text-slate-500 font-semibold uppercase tracking-wider">
                                        <i data-lucide="user" class="w-3 h-3"></i>
                                        <span>${response.data.usuario_nombre}</span>
                                    </div>
                                </div>
                            </div>`;

                        $('#activitiesFeed').prepend(notaHtml);
                        lucide.createIcons();

                        Swal.fire({
                            toast: true,
                            position: 'top-end',
                            icon: 'success',
                            title: 'Actividad registrada',
                            background: '#1e293b',
                            color: '#f8fafc',
                            showConfirmButton: false,
                            timer: 1500
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.message,
                            background: '#1e293b',
                            color: '#f8fafc',
                            confirmButtonColor: '#ef4444'
                        });
                    }
                    $('#addActivityBtn').attr('disabled', false).removeClass('opacity-80');
                },
                error: function() {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'No se pudo guardar la actividad en este momento.',
                        background: '#1e293b',
                        color: '#f8fafc',
                        confirmButtonColor: '#ef4444'
                    });
                    $('#addActivityBtn').attr('disabled', false).removeClass('opacity-80');
                }
            });
        });

    });
</script>
