{% extends "base.html" %}

{% block title %}Gestión de Leads{% endblock %}

{% block content %}
<div id="admin-content" class="container-fluid">
    <div class="row">
        <div class="col-12 mb-4 admin-header">
            <h1>Gestión de Leads</h1>
        </div>
    </div>
    
    <div class="row mb-4">
        <div class="col-md-6">
            <p class="mb-0">Administre los leads de facturas creados por los clientes y supervise su estado.</p>
        </div>
        <div class="col-md-6 text-md-end">
            <button id="toggleFiltersBtn" class="btn btn-outline-secondary me-2" type="button"
                    data-bs-toggle="collapse" data-bs-target="#filtersCollapse" aria-expanded="false"
                    aria-controls="filtersCollapse">
                <i class="fas fa-filter me-1"></i>
                <span class="toggle-text">Mostrar filtros</span>
            </button>
            {% if not is_comercial %}
                <button class="btn btn-danger" type="button" onclick="document.getElementById('deleteLeadsForm').submit();"><i class="fas fa-trash me-1"></i> Eliminar Seleccionados</button>
            {% endif %}
        </div>
    </div>
    
    <!-- Filtros colapsables -->
    <div class="row mb-3">
        <div class="col-12">
            <div class="collapse" id="filtersCollapse">
                <div class="card shadow-sm filters-card">
                    <div class="card-body py-3">
                        <form method="get" id="filtersForm">
                            <div class="row g-3">
                                <!-- Columna 1: ID, Fecha -->
                                <div class="col-md-3">
                                    <div class="mb-2">
                                        <label for="filter_id" class="form-label fw-bold small text-muted mb-1">ID</label>
                                        <input type="text" class="form-control" id="filter_id" name="id" placeholder="ID" value="{{ filter_id or '' }}">
                                    </div>
                                    <div class="mb-2">
                                        <label for="filter_date_from" class="form-label fw-bold small text-muted mb-1">Fecha desde</label>
                                        <input type="date" class="form-control" id="filter_date_from" name="date_from" value="{{ filter_date_from or '' }}">
                                    </div>
                                    <div>
                                        <label for="filter_date_until" class="form-label fw-bold small text-muted mb-1">Fecha hasta</label>
                                        <input type="date" class="form-control" id="filter_date_until" name="date_until" value="{{ filter_date_until or '' }}">
                                    </div>
                                </div>
                                
                                <!-- Columna 2: Nombre, Email, Teléfono -->
                                <div class="col-md-3">
                                    <div class="mb-2">
                                        <label for="filter_name" class="form-label fw-bold small text-muted mb-1">Nombre</label>
                                        <input type="text" class="form-control" id="filter_name" name="name" placeholder="Nombre" value="{{ filter_name or '' }}">
                                    </div>
                                    <div class="mb-2">
                                        <label for="filter_email" class="form-label fw-bold small text-muted mb-1">Email</label>
                                        <input type="text" class="form-control" id="filter_email" name="email" placeholder="Email" value="{{ filter_email or '' }}">
                                    </div>
                                    <div>
                                        <label for="filter_phone" class="form-label fw-bold small text-muted mb-1">Teléfono</label>
                                        <input type="text" class="form-control" id="filter_phone" name="phone" placeholder="Teléfono" value="{{ filter_phone or '' }}">
                                    </div>
                                </div>
                                
                                <!-- Columna 3: CUPS, Estado, Tarifa -->
                                <div class="col-md-3">
                                    <div class="mb-2">
                                        <label for="filter_cups" class="form-label fw-bold small text-muted mb-1">CUPS</label>
                                        <input type="text" class="form-control" id="filter_cups" name="cups" placeholder="CUPS" value="{{ filter_cups or '' }}">
                                    </div>
                                    <div class="mb-2">
                                        <label for="filter_status" class="form-label fw-bold small text-muted mb-1">Estado</label>
                                        <select class="form-select" id="filter_status" name="status">
                                            <option value="" {% if not filter_status %}selected{% endif %}>Todos</option>
                                            <option value="pending" {% if filter_status == 'pending' %}selected{% endif %}>Pendiente</option>
                                            <option value="completed" {% if filter_status == 'completed' %}selected{% endif %}>Completado</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label for="filter_tariff" class="form-label fw-bold small text-muted mb-1">Tarifa</label>
                                        <div class="input-group input-group-sm">
                                            <span class="input-group-text"><i class="fas fa-bolt"></i></span>
                                            <select class="form-select" id="filter_tariff" name="tariff">
                                                <option value="" {% if not filter_tariff %}selected{% endif %}>Todas</option>
                                                <!-- Opciones se cargan dinámicamente -->
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Columna 4: Comercializadora, Canal -->
                                <div class="col-md-3">
                                    <div class="mb-2">
                                        <label for="filter_supplier" class="form-label fw-bold small text-muted mb-1">Comercializadora</label>
                                        <div class="input-group input-group-sm">
                                            <span class="input-group-text"><i class="fas fa-building"></i></span>
                                            <select class="form-select" id="filter_supplier" name="supplier">
                                                <option value="" {% if not filter_supplier %}selected{% endif %}>Todas</option>
                                                <!-- Opciones se cargan dinámicamente -->
                                            </select>
                                        </div>
                                    </div>
                                    <div class="mb-2">
                                        <label for="filter_channel" class="form-label fw-bold small text-muted mb-1">Canal</label>
                                        <div class="input-group input-group-sm">
                                            <span class="input-group-text"><i class="fas fa-route"></i></span>
                                            <select class="form-select" id="filter_channel" name="channel">
                                                <option value="" {% if not filter_channel %}selected{% endif %}>Todos</option>
                                                <option value="public" {% if filter_channel == 'public' %}selected{% endif %}>Leads</option>
                                                <!-- Comerciales se cargan dinámicamente -->
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Botones de acción -->
                            <div class="row mt-3">
                                <div class="col-12 d-flex flex-wrap align-items-center justify-content-between">
                                    <div class="d-flex align-items-center mb-2 mb-md-0">
                                        <label for="per_page" class="form-label fw-bold small text-muted mb-0 me-2">Resultados por página</label>
                                        <select name="per_page" id="per_page" class="form-select form-select-sm" style="width: auto;">
                                            <option value="10" {% if per_page == 10 %}selected{% endif %}>10</option>
                                            <option value="25" {% if per_page == 25 %}selected{% endif %}>25</option>
                                            <option value="50" {% if per_page == 50 %}selected{% endif %}>50</option>
                                            <option value="100" {% if per_page == 100 %}selected{% endif %}>100</option>
                                        </select>
                                    </div>
                                    <div class="d-flex">
                                        <a href="{{ url_for('admin.list_leads') }}" class="btn btn-sm btn-outline-secondary me-2">
                                            <i class="fas fa-sync-alt me-1"></i> Limpiar
                                        </a>
                                        <button type="submit" class="btn btn-sm btn-primary">
                                            <i class="fas fa-search me-1"></i> Buscar
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Estadísticas y conteo -->
    <div class="row mb-3">
        <div class="col-12 text-end">
            <span class="text-muted small">Mostrando {{ leads|length }} de {{ pagination.total if pagination else 0 }} leads</span>
        </div>
    </div>
    
    <form id="deleteLeadsForm" method="post" action="{{ url_for('admin.delete_leads') }}" onsubmit="return confirm('¿Seguro que quieres eliminar los leads seleccionados o todos?');">
    
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body p-0">
                    {% if pagination and pagination.items %}
                        <div class="table-responsive">
                            <table class="table table-hover table-striped table-bordered leads-table align-middle">
                                <thead class="table-light">
                                    <tr>
                                        {% if not is_comercial %}
                                        <th><input type="checkbox" id="selectAll" title="Seleccionar todos los leads"></th>
                                        {% endif %}
                                        <th>ID</th>
                                        <th>Fecha</th>
                                        <th>Nombre</th>
                                        <th>CUPS</th>
                                        <th>Estado</th>
                                        <th>Tarifa</th>
                                        <th>Comentario</th>
                                        <th>Canal</th>
                                        <th>Acciones</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for lead in pagination.items %}
                                    <tr>
                                        {% if not is_comercial %}
                                        <td><input type="checkbox" name="lead_ids" value="{{ lead.id }}" title="Seleccionar lead {{ lead.id }}"></td>
                                        {% endif %}
                                        <td>{{ lead.id }}</td>
                                        <td class="text-nowrap">{{ lead.submitted_at.strftime('%d/%m/%Y') if lead.submitted_at else 'Sin fecha' }}</td>
                                        <td>{{ lead.name or 'Sin nombre' }}</td>
                                        <td>{{ lead.cups or 'Sin CUPS' }}</td>
                                        <td>
                                            {% set status_map = {
                                                'pending': {'label': 'Pendiente', 'class': 'bg-warning text-dark'},
                                                'completed': {'label': 'Completado', 'class': 'bg-success'},
                                                'in_progress': {'label': 'En progreso', 'class': 'bg-info'},
                                                'contacted': {'label': 'Contactado', 'class': 'bg-primary'},
                                                'closed': {'label': 'Cerrado', 'class': 'bg-secondary'},
                                                'cancelled': {'label': 'Cancelado', 'class': 'bg-danger'}
                                            } %}
                                            {% set status_info = status_map.get(lead.status, {'label': lead.status|title, 'class': 'bg-secondary'}) %}
                                            <span class="badge {{ status_info.class }}">{{ status_info.label }}</span>
                                        </td>
                                        <td><span class="badge bg-secondary">{{ lead.tariff_type or 'Sin tarifa' }}</span></td>
                                        <td>
                                            {% if lead.message %}
                                                <div class="message-container" title="Click para ver comentario completo">
                                                    <i class="fas fa-comment message-view-icon" aria-hidden="true"></i>
                                                    <span class="text-truncate d-inline-block cursor-pointer" data-message="{{ lead.message }}" style="max-width: 100px;">
                                                        {{ lead.message }}
                                                    </span>
                                                </div>
                                            {% else %}
                                                <span class="text-muted">Sin comentario</span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            {% if lead.channel == 'commercial' and lead.created_by %}
                                                <span class="badge bg-info">{{ lead.created_by.name if lead.created_by.name else lead.created_by.username }}</span>
                                            {% else %}
                                                <span class="badge bg-primary">Público</span>
                                            {% endif %}
                                        </td>
                                        <td class="text-nowrap">
                                            <div class="btn-group flex-nowrap">
                                                <button type="button" class="btn btn-sm btn-outline-secondary btn-view" 
                                                        data-lead-id="{{ lead.id }}" title="Ver detalles">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                                <button type="button" class="btn btn-sm btn-outline-info btn-history" 
                                                        data-lead-id="{{ lead.id }}" title="Ver histórico">
                                                    <i class="fas fa-history"></i>
                                                </button>
                                                {% if not is_comercial %}
                                                <button type="button" class="btn btn-sm btn-outline-primary btn-edit" 
                                                        data-lead-id="{{ lead.id }}" title="Editar Lead">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button type="button" class="btn btn-sm btn-outline-danger" 
                                                         data-lead-id="{{ lead.id }}" 
                                                         data-lead-name="{{ lead.name }}" 
                                                         onclick="confirmDelete(this.getAttribute('data-lead-id'), this.getAttribute('data-lead-name'))" title="Eliminar Lead">
                                                     <i class="fas fa-trash-alt"></i>
                                                 </button>
                                                {% endif %}
                                                <button type="button" class="btn btn-sm btn-outline-success btn-recalculate" 
                                                        data-lead-id="{{ lead.id }}" title="Recalcular ahorro">
                                                    <i class="fas fa-calculator"></i>
                                                </button>
                                                {% if lead.file_path %}
                                                <a href="{{ url_for('admin.get_lead_file', lead_id=lead.id) }}" target="_blank" 
                                                   class="btn btn-sm btn-outline-info" title="Ver PDF">
                                                    <i class="fas fa-file-pdf"></i>
                                                </a>
                                                {% endif %}
                                            </div>
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    {% else %}
                        <div class="text-center py-4">
                            <div class="d-flex flex-column align-items-center">
                                <i class="fas fa-folder-open fa-3x text-muted mb-3"></i>
                                <h5 class="text-muted">No hay leads disponibles</h5>
                                <p class="text-muted">No se encontraron leads con los filtros actuales o no hay ninguno registrado.</p>
                            </div>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
    
    <!-- Controles de paginación -->
    <nav aria-label="Page navigation">
        <ul class="pagination justify-content-center">
            <li class="page-item {% if not pagination or not pagination.has_prev %}disabled{% endif %}">
                <a class="page-link" href="{{ url_for('admin.list_leads', page=pagination.prev_num if pagination else 1, per_page=per_page, status=status, sort=sort_order) }}" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
            {% if pagination %}
                {% for p in pagination.iter_pages() %}
                    {% if p %}
                        <li class="page-item {% if p == pagination.page %}active{% endif %}">
                            <a class="page-link" href="{{ url_for('admin.list_leads', page=p, per_page=per_page, status=status, sort=sort_order) }}">{{ p }}</a>
                        </li>
                    {% else %}
                        <li class="page-item disabled">
                            <span class="page-link">…</span>
                        </li>
                    {% endif %}
                {% endfor %}
            {% endif %}
            <li class="page-item {% if not pagination or not pagination.has_next %}disabled{% endif %}">
                <a class="page-link" href="{{ url_for('admin.list_leads', page=pagination.next_num if pagination else 1, per_page=per_page, status=status, sort=sort_order) }}" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        </ul>
    </nav>

<!-- Modal de confirmación para eliminar -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalLabel">Confirmar eliminación</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>¿Está seguro de que desea eliminar el lead <strong id="deleteLeadName"></strong>?</p>
                <p class="text-danger">Esta acción no se puede deshacer.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">Eliminar</button>
            </div>
        </div>
    </div>
</div>

<!-- Modal personalizado de detalle de lead -->
<div class="custom-modal" id="viewLeadModal">
    <!-- Overlay de fondo oscuro -->
    <div class="custom-modal-overlay"></div>
    
    <!-- Contenedor del modal centrado -->
    <div class="custom-modal-container">
        <!-- Contenido del modal -->
        <div class="custom-modal-content lead-detail-modal">
            <!-- Encabezado del modal con título y botón de cierre -->
            <div class="custom-modal-header">
                <div class="d-flex align-items-center">
                    <i class="fas fa-user-tie me-2 text-primary"></i>
                    <h5 class="custom-modal-title" id="viewLeadLabel">Detalle de Lead</h5>
                </div>
                <button type="button" class="custom-modal-close" id="modalCloseButton">&times;</button>
            </div>
            
            <!-- Cuerpo del modal -->
            <div class="custom-modal-body">
                <div id="leadDetailContent">
                    <!-- Información principal en tarjeta -->
                    <div class="info-card mb-3">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <div class="detail-item">
                                    <span class="detail-label"><i class="fas fa-hashtag"></i> ID</span>
                                    <span class="detail-value fw-bold fs-5" id="d_id"></span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="detail-item">
                                    <span class="detail-label"><i class="fas fa-calendar"></i> Fecha</span>
                                    <span class="detail-value" id="d_date"></span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="detail-item">
                                    <span class="detail-label"><i class="fas fa-user"></i> Nombre</span>
                                    <span class="detail-value" id="d_name"></span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="detail-item">
                                    <span class="detail-label"><i class="fas fa-envelope"></i> Email</span>
                                    <span class="detail-value" id="d_email"></span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="detail-item">
                                    <span class="detail-label"><i class="fas fa-phone"></i> Teléfono</span>
                                    <span class="detail-value" id="d_phone"></span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="detail-item">
                                    <span class="detail-label"><i class="fas fa-plug"></i> CUPS</span>
                                    <span class="detail-value" id="d_cups"></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Estado y tarifa -->
                    <div class="status-card mb-3">
                        <div class="card-header bg-light py-2">
                            <h6 class="m-0"><i class="fas fa-info-circle me-1"></i> Estado y Tarifa</h6>
                        </div>
                        <div class="card-body py-2">
                            <div class="row align-items-center">
                                <div class="col-md-6">
                                    <div class="detail-item">
                                        <span class="detail-label">Estado</span>
                                        <span class="detail-value" id="d_status"></span>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="detail-item">
                                        <span class="detail-label">Tipo de Tarifa</span>
                                        <span class="detail-value" id="d_tariff"></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Comentario -->
                    <div class="comment-card mb-3">
                        <div class="card-header bg-light py-2">
                            <h6 class="m-0"><i class="fas fa-comment me-2"></i>Comentario</h6>
                        </div>
                        <div class="card-body py-2">
                            <div id="d_message" class="text-muted"></div>
                        </div>
                    </div>
                    
                    <!-- Detalles del análisis -->
                    <div class="analysis-card mb-3" id="analysisCard" style="display: none;">
                        <div class="card-header bg-light py-2">
                            <h6 class="m-0"><i class="fas fa-chart-line me-2"></i>Análisis de Ahorro</h6>
                        </div>
                        <div class="card-body py-2">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="detail-item">
                                        <span class="detail-label">Ahorro Estimado</span>
                                        <span class="detail-value text-success fw-bold" id="d_savings"></span>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="detail-item">
                                        <span class="detail-label">Mejor Plan</span>
                                        <span class="detail-value" id="d_best_plan"></span>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="detail-item">
                                        <span class="detail-label">Comercializadora</span>
                                        <span class="detail-value" id="d_supplier"></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Datos comerciales -->
                    <div class="commercial-card mb-3">
                        <div class="card-header bg-light py-2">
                            <h6 class="m-0"><i class="fas fa-user-tie me-2"></i>Datos Comerciales</h6>
                        </div>
                        <div class="card-body py-2">
                            <div class="mb-2">
                                <label for="commercial_comments" class="form-label small">Comentarios:</label>
                                <textarea class="form-control form-control-sm" id="commercial_comments" rows="2"></textarea>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-2">
                                        <label for="selected_plan" class="form-label small">Plan Seleccionado:</label>
                                        <input type="text" class="form-control form-control-sm" id="selected_plan">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-2">
                                        <label for="recommended_supplier" class="form-label small">Comercializadora:</label>
                                        <input type="text" class="form-control form-control-sm" id="recommended_supplier">
                                    </div>
                                </div>
                            </div>
                            <button type="button" class="btn btn-sm btn-success" id="saveSavingsBtn">
                                <i class="fas fa-save me-1"></i>Guardar Datos
                            </button>
                        </div>
                    </div>
                    
                    <!-- Canal -->
                    <div class="channel-card mb-3">
                        <div class="card-header bg-light py-2">
                            <h6 class="m-0"><i class="fas fa-route me-2"></i>Canal</h6>
                        </div>
                        <div class="card-body py-2">
                            <div id="d_channel" class="text-muted"></div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Pie del modal con botones -->
            <div class="custom-modal-footer">
                <button type="button" class="btn btn-secondary" id="modalCloseBtn">
                    <i class="fas fa-times me-1"></i> Cerrar
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Modal para histórico de estudios -->
<div class="custom-modal" id="historyModal">
    <div class="custom-modal-overlay"></div>
    <div class="custom-modal-container">
        <div class="custom-modal-content">
            <div class="custom-modal-header">
                <div class="d-flex align-items-center">
                    <i class="fas fa-history me-2 text-primary"></i>
                    <h5 class="custom-modal-title">Histórico de Estudios</h5>
                </div>
                <button type="button" class="custom-modal-close" id="historyModalCloseButton">&times;</button>
            </div>
            <div class="custom-modal-body">
                <div id="historyContent">
                    <p class="text-muted">Cargando histórico...</p>
                </div>
            </div>
            <div class="custom-modal-footer">
                <button type="button" class="btn btn-secondary" id="historyModalCloseBtn">
                    <i class="fas fa-times me-1"></i> Cerrar
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Modal 100% personalizado para mostrar el mensaje completo -->
<div id="customMessageModal" class="custom-modal">
    <!-- Overlay de fondo oscuro -->
    <div class="custom-modal-overlay"></div>
    
    <!-- Contenedor del modal centrado -->
    <div class="custom-modal-container">
        <!-- Contenido del modal -->
        <div class="custom-modal-content">
            <!-- Encabezado del modal con título y botón de cierre -->
            <div class="custom-modal-header">
                <h5 class="custom-modal-title">Comentario Completo</h5>
                <button type="button" class="custom-modal-close" id="messageModalCloseButton">&times;</button>
            </div>
            
            <!-- Cuerpo del modal con el contenido del mensaje -->
            <div class="custom-modal-body">
                <div id="modalMessageText"></div>
            </div>
            
            <!-- Pie del modal con botón de cerrar -->
            <div class="custom-modal-footer">
                <button type="button" class="custom-modal-btn" id="messageModalCloseBtn">Cerrar</button>
            </div>
        </div>
    </div>
</div>

    <!-- Estilos personalizados para el modal y los mensajes -->
    <style>
        /* Estilos para el contenedor de mensajes con ícono */
        .message-container {
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
            padding: 2px 4px;
            border-radius: 4px;
            transition: background-color 0.2s;
        }
        
        .message-container:hover {
            background-color: rgba(198, 8, 213, 0.1); /* #c608d5 con opacidad para tono tenue */
        }
        
        .message-view-icon {
            color: #6c757d;
            font-size: 0.875rem;
            min-width: 16px;
            transition: color 0.2s;
        }
        
        .message-container:hover .message-view-icon {
            color: #c608d5; /* Cambio color del icono al mismo púrpura */
        }
        
        .message-container span {
            max-width: 130px;
        }
        
        /* Estilo base del modal para cubrir toda la pantalla */
        .custom-modal {
            display: none; /* Oculto por defecto */
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            z-index: 9999;
        }
        
        /* Overlay de fondo oscuro que cubre toda la pantalla */
        .custom-modal-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.6);
            -webkit-backdrop-filter: blur(3px); /* Compatibilidad con Safari */
            backdrop-filter: blur(3px);
        }
        
        /* Contenedor que centra el modal vertical y horizontalmente */
        .custom-modal-container {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
            box-sizing: border-box;
        }
        
        /* El contenido real del modal con fondo blanco */
        .custom-modal-content {
            background-color: #ffffff;
            width: 100%;
            max-width: 500px;
            border-radius: 8px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);
            margin: auto;
            animation: modalFadeIn 0.3s ease-out;
            position: relative;
            max-height: 80vh;
            display: flex;
            flex-direction: column;
        }
        
        /* Encabezado del modal con título */
        .custom-modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 20px;
            border-bottom: 1px solid #e9ecef;
        }
        
        .custom-modal-title {
            margin: 0;
            font-size: 1.25rem;
            font-weight: 600;
            color: #333;
        }
        
        /* Botón de cierre (X) */
        .custom-modal-close {
            background: transparent;
            border: none;
            font-size: 28px;
            font-weight: 700;
            line-height: 1;
            color: #888;
            cursor: pointer;
            padding: 0;
            margin: 0;
        }
        
        .custom-modal-close:hover {
            color: #333;
        }
        
        /* Cuerpo del modal donde va el mensaje */
        .custom-modal-body {
            padding: 20px;
            overflow-y: auto;
            flex: 1;
        }
        
        #modalMessageText {
            white-space: pre-wrap;
            word-break: break-word;
            line-height: 1.5;
        }
        
        /* Pie del modal con botones */
        .custom-modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #e9ecef;
            text-align: right;
        }
        
        /* Botón personalizado */
        .custom-modal-btn {
            background-color: #6c757d;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 500;
        }
        
        .custom-modal-btn:hover {
            background-color: #5a6268;
        }
        
        /* Animación de entrada del modal */
        @keyframes modalFadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        /* Asegurar que el modal se vea bien en pantallas pequeñas */
        @media (max-width: 576px) {
            .custom-modal-content {
                max-width: 95%;
                margin: 10px;
            }
        }
    </style>

    <script>
        let currentLeadId = null;
        
        function confirmDelete(leadId, leadName) {
            currentLeadId = leadId;
            document.getElementById('deleteLeadName').textContent = leadName;
            
            var deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
            deleteModal.show();
        }
        
        // Manejar confirmación de eliminación
        document.addEventListener('DOMContentLoaded', function() {
            const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
            if (confirmDeleteBtn) {
                confirmDeleteBtn.addEventListener('click', function() {
                    if (currentLeadId) {
                        fetch(`{{ url_for('admin.delete_lead', lead_id=0) }}`.replace('0', currentLeadId), {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': '{{ csrf_token() }}'
                            }
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                // Cerrar modal
                                bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
                                // Recargar página
                                window.location.reload();
                            } else {
                                alert('Error: ' + data.message);
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            alert('Error al eliminar el lead');
                        });
                    }
                });
            }
        });
        
        // Función para poblar select de comercializadoras
        function populateSupplierSelect() {
            fetch('{{ url_for("admin.get_lead_suppliers") }}')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const select = document.getElementById('filter_supplier');
                        const currentValue = '{{ filter_supplier or "" }}';
                        
                        // Limpiar opciones excepto la primera
                        while (select.children.length > 1) {
                            select.removeChild(select.lastChild);
                        }
                        
                        // Añadir opciones
                        data.suppliers.forEach(supplier => {
                            const option = document.createElement('option');
                            option.value = supplier;
                            option.textContent = supplier;
                            if (supplier === currentValue) option.selected = true;
                            select.appendChild(option);
                        });
                    }
                })
                .catch(error => console.error('Error cargando comercializadoras:', error));
        }
        
        // Función para poblar select de tipos de tarifa
        function populateTariffSelect() {
            fetch('{{ url_for("admin.get_lead_tariff_types") }}')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const select = document.getElementById('filter_tariff');
                        const currentValue = '{{ filter_tariff or "" }}';
                        
                        // Limpiar opciones excepto la primera
                        while (select.children.length > 1) {
                            select.removeChild(select.lastChild);
                        }
                        
                        // Añadir opciones
                        data.tariff_types.forEach(tariff => {
                            const option = document.createElement('option');
                            option.value = tariff;
                            option.textContent = tariff;
                            if (tariff === currentValue) option.selected = true;
                            select.appendChild(option);
                        });
                    }
                })
                .catch(error => console.error('Error cargando tipos de tarifa:', error));
        }
        
        // Función para poblar select de canal con comerciales
        function populateChannelSelect() {
            fetch('{{ url_for("admin.get_lead_commercials") }}')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const select = document.getElementById('filter_channel');
                        const currentValue = '{{ filter_channel or "" }}';
                        
                        // Limpiar opciones excepto las dos primeras (Todos, Leads)
                        while (select.children.length > 2) {
                            select.removeChild(select.lastChild);
                        }
                        
                        // Añadir comerciales
                        data.commercials.forEach(commercial => {
                            const option = document.createElement('option');
                            option.value = `commercial_${commercial.id}`;
                            option.textContent = commercial.name;
                            if (`commercial_${commercial.id}` === currentValue) option.selected = true;
                            select.appendChild(option);
                        });
                    }
                })
                .catch(error => console.error('Error cargando comerciales:', error));
        }
        
        document.addEventListener('DOMContentLoaded', function() {
            // Cargar datos dinámicos para filtros
            populateSupplierSelect();
            populateTariffSelect();
            populateChannelSelect();
            
            // Toggle de filtros: actualizar texto del botón según estado del collapse
            const filtersCollapseEl = document.getElementById('filtersCollapse');
            const toggleFiltersBtn = document.getElementById('toggleFiltersBtn');
            if (filtersCollapseEl && toggleFiltersBtn) {
                filtersCollapseEl.addEventListener('shown.bs.collapse', function () {
                    const span = toggleFiltersBtn.querySelector('.toggle-text');
                    if (span) span.textContent = 'Ocultar filtros';
                });
                filtersCollapseEl.addEventListener('hidden.bs.collapse', function () {
                    const span = toggleFiltersBtn.querySelector('.toggle-text');
                    if (span) span.textContent = 'Mostrar filtros';
                });
            }
            
            // Auto submit al cambiar resultados por página
            const perPageSelect = document.getElementById('per_page');
            if (perPageSelect) {
                perPageSelect.addEventListener('change', function() {
                    const form = document.getElementById('filtersForm');
                    if (form) form.submit();
                });
            }
            
            // Funcionalidad para el checkbox de seleccionar todos
            const selectAll = document.getElementById('selectAll');
            if (selectAll) {
                selectAll.addEventListener('change', function() {
                    const checkboxes = document.querySelectorAll('input[name="lead_ids"]');
                    checkboxes.forEach(cb => cb.checked = this.checked);
                });
            }

            // Referencias a los modales personalizados
            const customModal = document.getElementById('viewLeadModal');
            const messageModal = document.getElementById('customMessageModal');
            const modalOverlay = customModal ? customModal.querySelector('.custom-modal-overlay') : null;
            const modalCloseBtn = document.getElementById('modalCloseBtn');
            const modalCloseButton = document.getElementById('modalCloseButton');
            
            const messageModalOverlay = messageModal ? messageModal.querySelector('.custom-modal-overlay') : null;
            const messageModalCloseBtn = document.getElementById('messageModalCloseBtn');
            const messageModalCloseButton = document.getElementById('messageModalCloseButton');
            
            // Funciones para abrir y cerrar el modal de detalle
            function openCustomModal() {
                if (customModal) {
                    customModal.style.display = 'block';
                    document.body.style.overflow = 'hidden';
                }
            }
            
            function closeCustomModal() {
                if (customModal) {
                    customModal.style.display = 'none';
                    document.body.style.overflow = '';
                }
            }
            
            // Funciones para abrir y cerrar el modal de mensaje
            function openMessageModal(message) {
                if (messageModal) {
                    document.getElementById('modalMessageText').textContent = message;
                    messageModal.style.display = 'block';
                    document.body.style.overflow = 'hidden';
                }
            }
            
            function closeMessageModal() {
                if (messageModal) {
                    messageModal.style.display = 'none';
                    document.body.style.overflow = '';
                }
            }
            
            // Asignar eventos para cerrar los modales
            if (modalCloseBtn) modalCloseBtn.addEventListener('click', closeCustomModal);
            if (modalCloseButton) modalCloseButton.addEventListener('click', closeCustomModal);
            if (modalOverlay) modalOverlay.addEventListener('click', closeCustomModal);
            
            if (messageModalCloseBtn) messageModalCloseBtn.addEventListener('click', closeMessageModal);
            if (messageModalCloseButton) messageModalCloseButton.addEventListener('click', closeMessageModal);
            if (messageModalOverlay) messageModalOverlay.addEventListener('click', closeMessageModal);
            
            // Cerrar modales con Escape
            document.addEventListener('keydown', function(event) {
                if (event.key === 'Escape') {
                    if (customModal && customModal.style.display === 'block') {
                        closeCustomModal();
                    }
                    if (messageModal && messageModal.style.display === 'block') {
                        closeMessageModal();
                    }
                }
            });
            
            // Variable global para el lead actual
            let currentLeadId = null;
            
            // Botones para ver detalles de lead
            document.querySelectorAll('.btn-view').forEach(btn => {
                btn.addEventListener('click', function(e) {
                    e.preventDefault();
                    const leadId = this.getAttribute('data-lead-id');
                    currentLeadId = leadId;
                    
                    // Petición AJAX para obtener detalles
                    fetch(`{{ url_for('admin.lead_detail', lead_id=0) }}`.replace('0', leadId))
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                // Actualizar campos del modal
                                document.getElementById('d_id').textContent = data.lead.id;
                                document.getElementById('d_date').textContent = formatDate(data.lead.submitted_at);
                                document.getElementById('d_name').textContent = data.lead.name || 'Sin nombre';
                                document.getElementById('d_email').textContent = data.lead.email || 'Sin email';
                                document.getElementById('d_phone').textContent = data.lead.phone || 'Sin teléfono';
                                document.getElementById('d_cups').textContent = data.lead.cups || 'Sin CUPS';
                                document.getElementById('d_status').innerHTML = getStatusBadge(data.lead.status);
                                document.getElementById('d_tariff').textContent = data.lead.tariff_type || 'Sin tarifa';
                                document.getElementById('d_message').textContent = data.lead.message || 'Sin comentario';
                                document.getElementById('d_channel').innerHTML = getChannelBadge(data.lead.channel, data.lead.created_by);
                                
                                // Cargar datos comerciales existentes
                                document.getElementById('commercial_comments').value = data.lead.commercial_comments || '';
                                document.getElementById('selected_plan').value = data.lead.selected_plan || '';
                                document.getElementById('recommended_supplier').value = data.lead.recommended_supplier || '';
                                
                                // Mostrar análisis si existe
                                const analysisCard = document.getElementById('analysisCard');
                                if (data.lead.details && data.lead.details.estimated_savings) {
                                    document.getElementById('d_savings').textContent = data.lead.details.estimated_savings.toFixed(2) + ' €';
                                    document.getElementById('d_best_plan').textContent = data.lead.details.best_rate_name || 'Sin plan';
                                    document.getElementById('d_supplier').textContent = data.lead.details.best_rate_supplier || 'Sin comercializadora';
                                    analysisCard.style.display = 'block';
                                } else {
                                    analysisCard.style.display = 'none';
                                }
                                
                                // Mostrar modal personalizado
                                openCustomModal();
                            } else {
                                alert('Error al cargar los detalles del lead');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            alert('Error al cargar los detalles del lead');
                        });
                });
            });
            
            // Botones para ver histórico
            document.querySelectorAll('.btn-history').forEach(btn => {
                btn.addEventListener('click', function(e) {
                    e.preventDefault();
                    const leadId = this.getAttribute('data-lead-id');
                    loadLeadHistory(leadId);
                });
            });
            
            // Botones para editar lead
            document.querySelectorAll('.btn-edit').forEach(btn => {
                btn.addEventListener('click', function(e) {
                    e.preventDefault();
                    const leadId = this.getAttribute('data-lead-id');
                    window.location.href = `{{ url_for('admin.edit_lead', lead_id=0) }}`.replace('0', leadId);
                });
            });
            
            // Botones para recalcular
            document.querySelectorAll('.btn-recalculate').forEach(btn => {
                btn.addEventListener('click', function(e) {
                    e.preventDefault();
                    const leadId = this.getAttribute('data-lead-id');
                    
                    if (confirm('¿Desea recalcular el ahorro con los precios actualizados?')) {
                        fetch(`{{ url_for('admin.recalculate_lead_savings', lead_id=0) }}`.replace('0', leadId), {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': '{{ csrf_token() }}'
                            }
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                alert(data.message);
                                if (data.redirect_url) {
                                    window.location.reload();
                                }
                            } else {
                                alert('Error: ' + data.message);
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            alert('Error al recalcular el ahorro');
                        });
                    }
                });
            });
            
            // Botón para guardar datos comerciales
            const saveSavingsBtn = document.getElementById('saveSavingsBtn');
            if (saveSavingsBtn) {
                saveSavingsBtn.addEventListener('click', function() {
                    if (!currentLeadId) {
                        alert('Error: No se ha seleccionado un lead');
                        return;
                    }
                    
                    const data = {
                        lead_id: currentLeadId,
                        comments: document.getElementById('commercial_comments').value,
                        selected_plan: document.getElementById('selected_plan').value,
                        recommended_supplier: document.getElementById('recommended_supplier').value
                    };
                    
                    fetch(`{{ url_for('admin.save_lead_savings') }}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRFToken': '{{ csrf_token() }}'
                        },
                        body: JSON.stringify(data)
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert(data.message);
                        } else {
                            alert('Error: ' + data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('Error al guardar los datos');
                    });
                });
            }
            
            // Asignar evento click a todos los contenedores de mensajes
            document.querySelectorAll('.message-container').forEach(container => {
                container.addEventListener('click', function() {
                    const message = this.querySelector('span').getAttribute('data-message');
                    openMessageModal(message);
                });
            });
            
            // Función para formatear fechas
            function formatDate(dateString) {
                if (!dateString) return 'Sin fecha';
                const date = new Date(dateString);
                return date.toLocaleDateString('es-ES');
            }
            
            // Función para generar badge de estado
            function getStatusBadge(status) {
                const statusMap = {
                    'pending': { label: 'Pendiente', class: 'bg-warning text-dark' },
                    'completed': { label: 'Completado', class: 'bg-success' },
                    'in_progress': { label: 'En progreso', class: 'bg-info' },
                    'contacted': { label: 'Contactado', class: 'bg-primary' },
                    'closed': { label: 'Cerrado', class: 'bg-secondary' },
                    'cancelled': { label: 'Cancelado', class: 'bg-danger' }
                };
                const statusInfo = statusMap[status] || { label: status, class: 'bg-secondary' };
                return `<span class="badge ${statusInfo.class}">${statusInfo.label}</span>`;
            }
            
            // Función para generar badge de canal
            function getChannelBadge(channel, createdBy) {
                if (channel === 'commercial' && createdBy) {
                    const name = createdBy.name || createdBy.username;
                    return `<span class="badge bg-info">${name}</span>`;
                } else {
                    return '<span class="badge bg-primary">Público</span>';
                }
            }
            
            // Función para cargar histórico de estudios
            function loadLeadHistory(leadId) {
                fetch(`{{ url_for('admin.get_lead_history', lead_id=0) }}`.replace('0', leadId))
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            displayHistory(data.history, data.current_data);
                            openHistoryModal();
                        } else {
                            alert('Error al cargar el histórico');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('Error al cargar el histórico');
                    });
            }
            
            // Función para mostrar el histórico
            function displayHistory(history, currentData) {
                const container = document.getElementById('historyContent');
                
                let html = '';
                
                // Mostrar datos actuales si existen
                if (currentData && (currentData.comments || currentData.selected_plan || currentData.recommended_supplier)) {
                    html += `
                        <div class="alert alert-info">
                            <h6><i class="fas fa-info-circle me-2"></i>Datos Actuales</h6>
                            <div class="row">
                                <div class="col-md-6">
                                    <strong>Plan:</strong> ${currentData.selected_plan || 'No especificado'}<br>
                                    <strong>Comercializadora:</strong> ${currentData.recommended_supplier || 'No especificada'}
                                </div>
                                <div class="col-md-6">
                                    <strong>Comentarios:</strong><br>
                                    ${currentData.comments || 'Sin comentarios'}
                                </div>
                            </div>
                        </div>
                    `;
                }
                
                if (!history || history.length === 0) {
                    html += '<p class="text-muted">No hay estudios previos registrados</p>';
                } else {
                    html += '<h6><i class="fas fa-history me-2"></i>Histórico de Estudios</h6>';
                    history.forEach((study, index) => {
                        const date = new Date(study.timestamp).toLocaleDateString('es-ES', {
                            year: 'numeric',
                            month: 'short',
                            day: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit'
                        });
                        
                        html += `
                            <div class="card mb-2">
                                <div class="card-body py-2">
                                    <div class="d-flex justify-content-between align-items-start mb-2">
                                        <small class="text-muted"><i class="fas fa-clock me-1"></i>${date}</small>
                                        <small class="badge bg-secondary">${study.created_by}</small>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <strong>Plan:</strong> ${study.selected_plan || 'No especificado'}<br>
                                            <strong>Comercializadora:</strong> ${study.recommended_supplier || 'No especificada'}
                                        </div>
                                        <div class="col-md-6">
                                            <strong>Comentarios:</strong><br>
                                            <small>${study.comments || 'Sin comentarios'}</small>
                                        </div>
                                    </div>
                                    ${study.savings_data && study.savings_data.estimated_savings ? 
                                        `<div class="mt-2 pt-2 border-top">
                                            <small class="text-success">
                                                <i class="fas fa-euro-sign me-1"></i>
                                                Ahorro estimado: ${study.savings_data.estimated_savings.toFixed(2)} €
                                            </small>
                                        </div>` : ''
                                    }
                                </div>
                            </div>
                        `;
                    });
                }
                
                container.innerHTML = html;
            }
            
            // Funciones para el modal de histórico
            const historyModal = document.getElementById('historyModal');
            const historyModalOverlay = historyModal ? historyModal.querySelector('.custom-modal-overlay') : null;
            const historyModalCloseBtn = document.getElementById('historyModalCloseBtn');
            const historyModalCloseButton = document.getElementById('historyModalCloseButton');
            
            function openHistoryModal() {
                if (historyModal) {
                    historyModal.style.display = 'block';
                    document.body.style.overflow = 'hidden';
                }
            }
            
            function closeHistoryModal() {
                if (historyModal) {
                    historyModal.style.display = 'none';
                    document.body.style.overflow = '';
                }
            }
            
            // Eventos para cerrar el modal de histórico
            if (historyModalCloseBtn) historyModalCloseBtn.addEventListener('click', closeHistoryModal);
            if (historyModalCloseButton) historyModalCloseButton.addEventListener('click', closeHistoryModal);
            if (historyModalOverlay) historyModalOverlay.addEventListener('click', closeHistoryModal);
            
            // Cerrar modal de histórico con Escape
            document.addEventListener('keydown', function(event) {
                if (event.key === 'Escape') {
                    if (historyModal && historyModal.style.display === 'block') {
                        closeHistoryModal();
                    }
                }
            });
        });
    </script>
    </form>
</div> <!-- Fin del contenedor admin-content -->
{% endblock %}
