<?php
ob_start();
session_start();
include_once 'db/db_connection.php'; 

$active_complaints = [];
$archived_complaints = [];
// Inicializamos el contador de estados activos para el panel Kanban
$complaints_counts = ['Recibido' => 0, 'Resolviendo' => 0, 'Acción Requerida' => 0, 'Resuelto' => 0];

try {
    // La consulta es eficiente y correcta.
    $stmt_complaints = $pdo->query("
        SELECT 
            comp.id, comp.title, comp.description, comp.status, comp.created_at, comp.updated_at, 
            c.first_name, c.last_name, comp.client_id, 
            s.name as service_name, s.id as service_id
        FROM complaints comp
        LEFT JOIN clients c ON comp.client_id = c.id
        LEFT JOIN services s ON comp.service_id = s.id
        ORDER BY comp.updated_at DESC
    ");
    $db_complaints_rows = $stmt_complaints->fetchAll(PDO::FETCH_ASSOC);

    foreach ($db_complaints_rows as $row) {
        $complaint_data = [
            'id' => $row['id'],
            'title' => $row['title'],
            'description' => $row['description'],
            'client_name' => $row['first_name'] ? trim($row['first_name'] . ' ' . $row['last_name']) : 'Cliente no encontrado',
            'client_id' => $row['client_id'],
            'service_name' => $row['service_name'] ?? 'No asignado',
            'service_id' => $row['service_id'] ?? null,
            'created_at' => $row['created_at'],
            'status' => $row['status'],
            'updated_at' => $row['updated_at']
        ];
        
        if ($row['status'] === 'Archivado') {
            $archived_complaints[] = $complaint_data;
        } else {
            $active_complaints[$row['id']] = $complaint_data;
        }
    }
    
    // Contamos para las tarjetas principales
    $cards_counts = ['abiertos' => 0, 'resolviendo' => 0, 'resueltos' => 0];
    foreach($active_complaints as $complaint){
        if ($complaint['status'] === 'Recibido' || $complaint['status'] === 'Acción Requerida') {
            $cards_counts['abiertos']++;
        }
        if ($complaint['status'] === 'Resolviendo') {
            $cards_counts['resolviendo']++;
        }
        if ($complaint['status'] === 'Resuelto') {
            $cards_counts['resueltos']++;
        }
        // Contamos para las columnas (se sobrescribe en JS, pero es buena práctica)
        if (isset($complaints_counts[$complaint['status']])) {
             $complaints_counts[$complaint['status']]++;
        }
    }

} catch (PDOException $e) {
    error_log("Error al cargar reclamos: " . $e->getMessage());
}

$complaints_json = json_encode($active_complaints);
$archived_complaints_json = json_encode($archived_complaints);
ob_end_clean();
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>FlowCRM™ Tu Centro De Control Empresarial Powered By OrozCO</title>
  <meta name="description" content="La Plataforma Todo En Uno Para Impulsar Tu Negocio">
  <meta name="robots" content="noindex, nofollow">

    <link rel="icon" type="image/png" href="img/favicon.png">
    <link rel="apple-touch-icon" href="img/apple-touch-icon.png">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://cdn.tailwindcss.com"></script>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="style.css"> 
    <script src="files/header-manager.js"></script>
    
</head>

<body data-page-title="Panel De Gestión De Reclamos" 
data-page-subtitle="Atiende, Gestiona Y Resuelve Las Incidencias De Tus Clientes"
data-page-icon="triangle-alert">
    
        <div id="toast-container" class="toast-container"></div>
    
<?php include 'files/gtm-body.php'; ?>

<div class="relative min-h-screen md:flex">
    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>
    
    <?php include 'menu.php'; ?>

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-sm p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
        </header>
        
        <div id="content-area" class="p-4 md:p-8 space-y-8">
            <section id="reclamos" class="dashboard-section">
                <div class="bg-white p-6 rounded-xl shadow-lg">
                    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
                        <div>
                            <h3 class="text-2xl font-extrabold text-gray-800 flex items-center gap-2">
                                <i data-lucide="layout-dashboard" class="w-7 h-7 text-[var(--color-secondary)]"></i> CENTRO DE SEGUIMIENTO DE RECLAMOS
                            </h3>
                            <p class="text-gray-500 text-sm mt-1 uppercase">ARRASTRA LAS TARJETAS PARA CAMBIAR EL ESTADO.</p>
                        </div>
                        <div class="relative w-full md:w-auto">
                             <select id="status-filter" class="appearance-none bg-gray-100 border border-gray-300 text-gray-700 py-2 px-4 pr-8 rounded-lg leading-tight focus:outline-none focus:bg-white focus:border-[var(--color-secondary)] transition-all duration-200 uppercase font-semibold text-sm">
                                <option value="all">Ver Todos los Estados</option>
                                <option value="Recibido">Recibido</option>
                                <option value="Resolviendo">Resolviendo</option>
                                <option value="Acción Requerida">Acción Requerida</option>
                                <option value="Resuelto">Resuelto</option>
                            </select>
                            <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
                                <i data-lucide="chevron-down" class="w-4 h-4"></i>
                            </div>
                        </div>
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">

    <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-primary)]">
        <i data-lucide="inbox" class="w-12 h-12 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">RECLAMOS ABIERTOS</h3>
            <p id="count-abiertos" class="text-5xl font-bold text-[var(--color-primary)]"><?php echo $cards_counts['abiertos']; ?></p>
        </div>
    </div>

    <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
        <i data-lucide="wrench" class="w-12 h-12 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">EN PROCESO</h3>
            <p id="count-resolviendo" class="text-5xl font-bold text-[var(--color-highlight)]"><?php echo $cards_counts['resolviendo']; ?></p>
        </div>
    </div>

    <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-primary)]">
        <i data-lucide="check-circle-2" class="w-12 h-12 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">LISTOS PARA ARCHIVAR</h3>
            <p id="count-resueltos" class="text-5xl font-bold text-[var(--color-primary)]"><?php echo $cards_counts['resueltos']; ?></p>
        </div>
    </div>
    
</div>
                    
                    <div class="space-y-6">
                        <?php 
                        $columns = [
                            "Recibido" => ["icon" => "check-square", "color" => "border-gray-500"], 
                            "Resolviendo" => ["icon" => "wrench", "color" => "border-[var(--color-highlight)]"], 
                            "Acción Requerida" => ["icon" => "alert-circle", "color" => "border-[var(--color-secondary)]"], 
                            "Resuelto" => ["icon" => "check-circle-2", "color" => "border-[var(--color-primary)]"] 
                        ];
                        ?>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                            <?php foreach ($columns as $name => $data): $slug = str_replace(' ', '-', strtolower($name)); ?>
                            <div class="w-full bg-white rounded-xl shadow-lg pt-0 flex flex-col">
                                <h4 class="text-base font-extrabold text-white p-4 bg-[var(--color-primary)] rounded-t-xl flex items-center justify-between uppercase flex-shrink-0">
                                    <span class="flex items-center gap-2">
                                        <i data-lucide="<?php echo $data['icon']; ?>" class="w-5 h-5 text-[var(--color-highlight)]"></i>
                                        <?php echo $name; ?>
                                    </span>
                                    <span id="count-<?php echo $slug; ?>" class="bg-[var(--color-secondary)] text-white px-3 py-1 text-xs font-bold rounded-full">
                                        0
                                    </span>
                                </h4>
                                <div id="column-<?php echo $slug; ?>" class="p-4 space-y-3 min-h-[40vh] complaint-column flex-grow bg-gray-50 rounded-b-xl border-t-4 <?php echo $data['color']; ?>" data-status="<?php echo $name; ?>">
                                    </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <div class="bg-white p-6 rounded-xl shadow-lg mt-8">
                    <h3 class="text-2xl font-extrabold text-gray-800 flex items-center gap-2 mb-4">
                        <i data-lucide="archive" class="w-7 h-7 text-[var(--color-secondary)]"></i> HISTORIAL DE RECLAMOS ARCHIVADOS
                    </h3>
                    <div class="overflow-x-auto">
                        <table class="min-w-full bg-white divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr class="text-left text-gray-500 uppercase text-xs font-semibold">
                                    <th class="py-3 px-6">Asunto</th>
                                    <th class="py-3 px-6 hidden md:table-cell">Cliente</th>
                                    <th class="py-3 px-6 hidden lg:table-cell">Servicio</th>
                                    <th class="py-3 px-6 hidden lg:table-cell">Fecha Archivo</th>
                                    <th class="py-3 px-6 text-center">Acciones</th>
                                </tr>
                            </thead>
                            <tbody id="archived-complaints-table-body" class="text-gray-700 text-sm divide-y divide-gray-100"></tbody>
                        </table>
                    </div>
                </div>
            </section>
        </div>
    </main>
</div>

<div id="viewComplaintPanel" class="fixed inset-y-0 right-0 w-full md:w-2/5 bg-white shadow-2xl transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
    <div class="flex flex-col h-full">
        <div class="bg-[var(--color-primary)] text-white p-6 flex justify-between items-center flex-shrink-0 shadow-lg">
            <h3 class="text-xl font-bold uppercase flex items-center">
                <i data-lucide="message-square-text" class="w-6 h-6 mr-3 text-[var(--color-highlight)]"></i>FICHA Y SEGUIMIENTO
            </h3>
            <button onclick="closePanel('viewComplaintPanel')" class="text-gray-300 hover:text-white transition-colors duration-200"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <div class="flex-grow overflow-y-auto p-6 space-y-6">
            <div id="view-complaint-content" class="border-b pb-4">
                <h2 id="view-complaint-title" class="text-2xl font-extrabold text-gray-900 mb-4 uppercase leading-tight"></h2>
                <div class="bg-gray-50 p-4 rounded-lg space-y-2 border">
                    <p id="view-complaint-client" class="flex items-center gap-2 font-semibold text-gray-700 text-sm"></p>
                    <p id="view-complaint-status" class="flex items-center gap-2 font-semibold text-gray-700 text-sm"></p>
                    <p id="view-complaint-service" class="flex items-center gap-2 font-semibold text-gray-700 text-sm"></p>
                    <div id="status-tag-container" class="mt-2 pt-2 border-t"></div>
                </div>
                <h4 class="text-lg font-bold text-gray-800 mt-6 mb-2">Descripción Detallada</h4>
                <p id="view-complaint-description" class="text-gray-700 whitespace-pre-wrap"></p>
                <button id="archive-complaint-btn-view" type="button" class="mt-4 btn-secondary font-bold py-2 px-4 rounded-lg uppercase w-full hidden transition-colors duration-200">
                    <i data-lucide="archive" class="w-4 h-4 mr-2"></i> Archivar Caso
                </button>
            </div>
            
            <div class="space-y-4 border-b pb-6 mb-6">
                <h4 class="text-lg font-bold text-gray-800 flex items-center"><i data-lucide="languages" class="w-5 h-5 mr-2 text-[var(--color-secondary)]"></i> Asistente de Redacción con IA</h4>
                <div>
                    <label for="spanish-response-textarea" class="block text-sm font-medium text-gray-600 mb-1">Escribe tu respuesta en español aquí:</label>
                    <textarea id="spanish-response-textarea" rows="4" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--color-secondary)] focus:border-[var(--color-secondary)] transition-all duration-200" placeholder="Estimado cliente, hemos revisado su caso..."></textarea>
                    <button id="translate-with-ia-btn" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase mt-2 w-full transition-colors duration-200 flex items-center justify-center">
                        <i data-lucide="bot" class="w-4 h-4 mr-2"></i> Traducir a Inglés con IA
                    </button>
                </div>
                <div id="translation-result-container" class="hidden pt-4 border-t border-gray-200">
                    <label class="block text-sm font-medium text-gray-600 mb-1">Traducción sugerida en inglés:</label>
                    <div class="relative">
                        <textarea id="english-translation-textarea" rows="4" readonly class="w-full p-3 border rounded-lg bg-gray-100 text-gray-800"></textarea>
                        <button id="copy-translation-btn" class="absolute top-2 right-2 bg-gray-300 hover:bg-gray-400 text-gray-700 font-bold py-1 px-2 rounded-lg text-xs transition-colors duration-200">Copiar</button>
                    </div>
                    <p class="text-xs text-gray-500 mt-1">Copia este texto y pégalo en la casilla "Publicar en Portal del Cliente" o envíalo por WhatsApp.</p>
                </div>
            </div>

            <div class="space-y-4">
                <h4 class="text-lg font-bold text-gray-800 border-b pb-2 flex items-center gap-2"><i data-lucide="history" class="w-5 h-5 text-gray-500"></i> Historial del Caso</h4>
                <div id="complaint-history-log" class="space-y-4 max-h-96 overflow-y-auto pr-2">
                    </div>
            </div>
            
            <div class="space-y-6 pt-4 border-t">
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2 uppercase">Publicar en Portal del Cliente</label>
                    <textarea id="portal-message-input" rows="3" class="w-full p-3 border rounded-lg focus:ring-2 focus:ring-[var(--color-primary)] focus:border-[var(--color-primary)]" placeholder="Este mensaje será visible para el cliente..."></textarea>
                    <button id="publish-portal-message-btn" class="bg-[var(--color-primary)] hover:bg-[var(--color-primary)] text-white font-bold py-2 px-4 rounded-lg uppercase mt-2 w-full transition-colors duration-200 flex items-center justify-center">
                        <i data-lucide="send" class="w-4 h-4 mr-2"></i> Publicar Mensaje
                    </button>
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2 uppercase">Añadir Nota Interna</label>
                    <textarea id="internal-note-input" rows="2" class="w-full p-3 border rounded-lg focus:ring-2 focus:ring-gray-600 focus:border-gray-600" placeholder="Solo visible para el equipo..."></textarea>
                    <button id="save-internal-note-btn" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg uppercase mt-2 w-full transition-colors duration-200 flex items-center justify-center">
                        <i data-lucide="bookmark" class="w-4 h-4 mr-2"></i> Guardar Nota
                    </button>
                </div>
            </div>
        </div>
        <div class="flex-shrink-0 p-6 bg-gray-50 border-t flex justify-between items-center space-x-4">
            <button id="delete-complaint-btn-view" type="button" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase flex items-center">
                <i data-lucide="trash-2" class="w-4 h-4 mr-2"></i> Eliminar
            </button>
            <div class="flex space-x-4">
                <button id="generate-whatsapp-btn" type="button" class="bg-[var(--color-primary)] hover:bg-[var(--color-primary)] text-white font-bold py-2 px-4 rounded-lg uppercase transition-colors duration-200 flex items-center">
                    <i data-lucide="message-circle-code" class="w-4 h-4 mr-2"></i> WhatsApp
                </button>
                <button type="button" class="bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase border border-gray-300" onclick="closePanel('viewComplaintPanel')">
                     Cerrar
                </button>
            </div>
        </div>
    </div>
</div>

<div id="confirmDeleteModal" class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center hidden z-50">
    <div class="bg-white p-8 rounded-xl shadow-2xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center">
        <div class="flex justify-center mb-4"><i data-lucide="alert-triangle" class="w-16 h-16 text-[var(--color-secondary)]"></i></div>
        <h3 class="text-2xl font-bold text-gray-800 mb-4 uppercase">CONFIRMAR ELIMINACIÓN</h3>
        <p class="text-gray-700 mb-6 uppercase">¿ESTÁS SEGURO? ESTA ACCIÓN NO SE PUEDE DESHACER.</p>
        <div class="flex flex-col sm:flex-row justify-center space-y-2 sm:space-y-0 sm:space-x-4">
            <button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase w-full sm:w-auto" id="cancel-delete-button">CANCELAR</button>
            <button type="button" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase w-full sm:w-auto" id="confirm-delete-button">CONFIRMAR</button>
        </div>
    </div>
</div>

<div id="whatsappModal" class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center hidden z-50">
    <div class="bg-white p-8 rounded-xl shadow-2xl w-full max-w-lg m-4 transform transition-all duration-300 scale-95 opacity-0">
        <div class="flex items-center justify-between mb-6">
            <h3 class="text-2xl font-bold text-[var(--color-primary)] flex items-center gap-3">
                <i data-lucide="message-circle" class="w-7 h-7 text-[var(--color-primary)]"></i> Generar Mensaje para WhatsApp
            </h3>
            <button id="closeModalBtn" class="text-gray-400 hover:text-gray-600"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <p class="text-gray-600 mb-4">El siguiente mensaje está listo para ser copiado. Puedes editarlo aquí si es necesario.</p>
        <textarea id="whatsappMessageText" rows="5" class="w-full p-3 border rounded-lg bg-gray-50 text-gray-800 focus:ring-2 focus:ring-[var(--color-primary)]"></textarea>
        <div class="flex justify-end space-x-4 mt-6">
            <button id="copyAndOpenWhatsAppBtn" class="bg-[var(--color-primary)] hover:bg-[var(--color-primary)] text-white font-bold py-3 px-6 rounded-lg uppercase flex items-center gap-2 w-full justify-center transition-colors duration-200">
                <i data-lucide="copy" class="w-5 h-5"></i><span>Copiar Mensaje y Abrir WhatsApp</span>
            </button>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // --- LÓGICA DE UI Y TOASTS (SIN CAMBIOS FUNCIONALES) ---
    const panelOverlay = document.createElement('div');
    panelOverlay.className = 'fixed inset-0 bg-gray-900 bg-opacity-75 z-40 hidden';
    document.body.appendChild(panelOverlay);
    const closeAllPanels = () => {
        document.querySelectorAll('.fixed.inset-y-0.right-0').forEach(p => p.classList.add('translate-x-full'));
        panelOverlay.classList.add('hidden');
    };
    panelOverlay.addEventListener('click', closeAllPanels);
    window.openPanel = (id) => { document.getElementById(id)?.classList.remove('translate-x-full'); panelOverlay.classList.remove('hidden'); };
    window.closePanel = (id) => { document.getElementById(id)?.classList.add('translate-x-full'); panelOverlay.classList.add('hidden'); };
    
    // Función de Toast 
    window.showToast = function(message, type = 'info') {
        const toast = document.createElement('div');
        let icon, colors;
        if (type === 'success') {
            icon = 'check-circle'; colors = 'bg-[var(--color-primary)] text-white';
        } else if (type === 'error') {
            icon = 'alert-triangle'; colors = 'bg-[var(--color-secondary)] text-white';
        } else {
            icon = 'info'; colors = 'bg-[var(--color-primary)] text-white';
        }
        
        toast.className = `fixed top-5 right-5 p-4 rounded-lg shadow-xl flex items-center gap-3 transform translate-x-full transition-transform duration-300 ease-in-out ${colors} z-[100]`;
        toast.innerHTML = `<i data-lucide="${icon}" class="w-6 h-6"></i><p class="font-semibold">${message}</p>`;
        document.body.appendChild(toast);
        lucide.createIcons();
        setTimeout(() => toast.classList.remove('translate-x-full'), 50);
        setTimeout(() => { toast.classList.add('translate-x-full'); setTimeout(() => toast.remove(), 300); }, 3500);
    };

    // --- DATOS Y VARIABLES ---
    let complaintsData = <?php echo $complaints_json; ?>;
    let archivedComplaints = <?php echo $archived_complaints_json; ?>;
    let currentViewingComplaintId = null;
    let pendingDeletionId = null;

    const API_UPDATE_URL = 'db/complaints-update.php';
    const API_DELETE_URL = 'db/complaints-delete.php';
    const STATUS_COLORS = { 
        'Recibido': 'border-gray-500', 
        'Resolviendo': 'border-[var(--color-highlight)]', 
        'Acción Requerida': 'border-[var(--color-secondary)]', 
        'Resuelto': 'border-[var(--color-primary)]' 
    };
    
    // --- GESTIÓN DEL PANEL DE DETALLES ---
    function openComplaintDetailsPanel(complaintId) {
        currentViewingComplaintId = complaintId;
        const allComplaints = {...complaintsData, ...archivedComplaints.reduce((acc, p) => ({...acc, [p.id]: p}), {})};
        const complaint = allComplaints[complaintId];
        if (!complaint) return;
        
        // Asignación de Contenido
        document.getElementById('view-complaint-title').textContent = complaint.title;
        document.getElementById('view-complaint-client').innerHTML = `<i data-lucide="user" class="w-4 h-4 text-gray-500 inline-block mr-2"></i> Cliente: <strong>${complaint.client_name}</strong>`;
        document.getElementById('view-complaint-service').innerHTML = `<i data-lucide="tag" class="w-4 h-4 text-gray-500 inline-block mr-2"></i> Servicio: <strong>${complaint.service_name}</strong>`;
        document.getElementById('view-complaint-description').textContent = complaint.description || 'No hay descripción.';
        
        // Gestión del Tag de Estado
        const statusTagContainer = document.getElementById('status-tag-container');
        let tagColor, tagIcon;
        if (complaint.status === 'Archivado') { tagColor = 'bg-gray-500'; tagIcon = 'archive'; } 
        else if (complaint.status === 'Resuelto') { tagColor = 'bg-[var(--color-primary)]'; tagIcon = 'check-circle'; } 
        else if (complaint.status === 'Acción Requerida') { tagColor = 'bg-[var(--color-secondary)]'; tagIcon = 'alert-triangle'; } 
        else if (complaint.status === 'Resolviendo') { tagColor = 'bg-[var(--color-highlight)]'; tagIcon = 'wrench'; } 
        else { tagColor = 'bg-[var(--color-primary)]'; tagIcon = 'shield-check'; }
        
        statusTagContainer.innerHTML = `<span class="inline-flex items-center px-3 py-1 text-xs font-bold leading-none text-white ${tagColor} rounded-full uppercase"><i data-lucide="${tagIcon}" class="w-3 h-3 mr-1"></i> Estado: ${complaint.status}</span>`;
        
        const archiveBtn = document.getElementById('archive-complaint-btn-view');
        archiveBtn.classList.add('hidden');
        if (complaint.status === 'Resuelto') {
             archiveBtn.textContent = 'Archivar Caso';
             archiveBtn.classList.remove('hidden');
             archiveBtn.onclick = () => { archiveComplaint(complaint.id); closePanel('viewComplaintPanel'); };
        } else if (complaint.status === 'Archivado') {
             archiveBtn.textContent = 'Reabrir Caso';
             archiveBtn.classList.remove('hidden');
             archiveBtn.onclick = () => { reopenComplaint(complaint.id); closePanel('viewComplaintPanel'); };
        }
        
        document.getElementById('spanish-response-textarea').value = '';
        document.getElementById('translation-result-container').classList.add('hidden');
        loadComplaintHistory(complaintId);
        lucide.createIcons();
        openPanel('viewComplaintPanel');
    };

    // Funciones loadComplaintHistory, addComplaintUpdate 
    async function loadComplaintHistory(complaintId) {
        const historyLog = document.getElementById('complaint-history-log');
        historyLog.innerHTML = '<p class="text-gray-500 italic">Cargando historial...</p>';
        try {
            const response = await fetch(`db/complaints-get-history.php?id=${complaintId}`);
            const updates = await response.json();
            historyLog.innerHTML = '';
            if (updates.length === 0) { historyLog.innerHTML = '<p class="text-gray-500 italic">No hay actualizaciones para este caso.</p>'; return; }
            updates.forEach(update => {
                const isInternal = update.type === 'internal_note';
                const bgColor = isInternal ? 'bg-[var(--color-highlight)] border-[var(--color-highlight)]' : 'bg-[var(--color-primary)] border-[var(--color-primary)]';
                const icon = isInternal ? 'clipboard-list' : 'message-circle';
                const author = isInternal ? 'Nota Interna' : 'Mensaje al Cliente';
                const updateEl = document.createElement('div');
                updateEl.className = `p-3 rounded-lg ${bgColor} border`;
                updateEl.innerHTML = `<div class="flex justify-between items-center text-xs font-bold mb-2"><span class="flex items-center gap-2 text-gray-700"><i data-lucide="${icon}" class="w-4 h-4 text-[var(--color-secondary)]"></i> ${author}</span><span class="text-gray-500">${new Date(update.created_at).toLocaleString()}</span></div><p class="text-gray-800 text-sm whitespace-pre-wrap">${update.message}</p>`;
                historyLog.appendChild(updateEl);
            });
            lucide.createIcons();
        } catch (error) { historyLog.innerHTML = '<p class="text-[var(--color-secondary)]">Error al cargar el historial.</p>'; }
    }

    async function addComplaintUpdate(complaintId, message, type) {
        if (!message.trim()) return;
        const formData = new FormData();
        formData.append('complaint_id', complaintId);
        formData.append('message', message);
        formData.append('type', type);
        try {
            const response = await fetch('db/complaints-add-update.php', { method: 'POST', body: formData });
            const result = await response.json();
            if (result.success) {
                if(type === 'portal_message') document.getElementById('portal-message-input').value = '';
                else document.getElementById('internal-note-input').value = '';
                showToast('ACTUALIZACIÓN GUARDADA', 'success');
                loadComplaintHistory(complaintId);
            } else { showToast(result.message || 'Error al guardar.', 'error'); }
        } catch (error) { showToast('Error de conexión.', 'error'); }
    }

    document.getElementById('publish-portal-message-btn').addEventListener('click', () => addComplaintUpdate(currentViewingComplaintId, document.getElementById('portal-message-input').value, 'portal_message'));
    document.getElementById('save-internal-note-btn').addEventListener('click', () => addComplaintUpdate(currentViewingComplaintId, document.getElementById('internal-note-input').value, 'internal_note'));
    
    // RENDERIZADO DE TARJETAS (Ajustado a STATUS_COLORS)
    function renderComplaintCard(complaint) {
        const card = document.createElement('div');
        const statusColors = STATUS_COLORS;
        
        card.className = `p-4 bg-white rounded-xl shadow-md cursor-grab transition-all duration-300 border-l-4 ${statusColors[complaint.status] || 'border-gray-500'} hover:shadow-xl hover:scale-[1.01] active:cursor-grabbing kanban-card`;
        card.draggable = true;
        card.dataset.complaintId = complaint.id;
        
        let cardHTML = `<h5 class="font-bold text-gray-900 mb-1 leading-snug">${complaint.title}</h5>`;
        cardHTML += `<p class="text-xs text-gray-600 font-medium flex items-center mt-1"><i data-lucide="user" class="w-3 h-3 mr-1.5 text-gray-400"></i>${complaint.client_name}</p>`;
        if (complaint.service_name) {
            cardHTML += `<p class="text-[11px] text-gray-400 font-medium flex items-center mt-1"><i data-lucide="tag" class="w-3 h-3 mr-1.5"></i>Servicio: ${complaint.service_name}</p>`;
        }
        
        if (complaint.status === 'Resuelto') {
            cardHTML += `<div class="mt-4 text-right"><button class="archive-btn bg-[var(--color-secondary)] hover:bg-[#7c1020] text-white text-xs font-bold py-1 px-3 rounded-full uppercase transition-colors duration-200 shadow-md flex items-center justify-end ml-auto">Archivar Caso <i data-lucide="archive" class="w-3 h-3 ml-1"></i></button></div>`;
        }
        
        card.innerHTML = cardHTML;
        card.addEventListener('click', (e) => {
            if (!e.target.closest('.archive-btn')) openComplaintDetailsPanel(complaint.id);
        });
        card.querySelector('.archive-btn')?.addEventListener('click', (e) => {
            e.stopPropagation();
            archiveComplaint(complaint.id);
        });
        card.addEventListener('dragstart', e => e.dataTransfer.setData('text/plain', complaint.id));
        return card;
    }

    // RENDERIZADO DE TABLA DE ARCHIVADOS
    function renderArchivedTable() {
        const tableBody = document.getElementById('archived-complaints-table-body');
        tableBody.innerHTML = '';
        if (archivedComplaints.length === 0) {
            tableBody.innerHTML = `<tr><td colspan="5" class="text-center py-6 text-gray-500 italic">No hay reclamos archivados.</td></tr>`;
            return;
        }
        archivedComplaints.forEach(complaint => {
            const date = new Date(complaint.updated_at).toLocaleDateString('es-ES');
            const row = document.createElement('tr');
            row.className = 'border-b hover:bg-gray-50 transition-colors duration-150';
            row.innerHTML = `<td class="py-4 px-6 font-medium">${complaint.title}</td>
                             <td class="py-4 px-6 hidden md:table-cell">${complaint.client_name}</td>
                             <td class="py-4 px-6 hidden lg:table-cell">${complaint.service_name}</td>
                             <td class="py-4 px-6 hidden lg:table-cell">${date}</td>
                             <td class="py-4 px-6 text-center">
                                 <div class="flex items-center justify-center space-x-2">
                                     <button class="reopen-complaint-btn text-[var(--color-primary)] hover:text-[var(--color-primary)] p-1 rounded-full hover:bg-gray-50" data-id="${complaint.id}" title="Reabrir Reclamo"><i data-lucide="arrow-up-circle" class="w-5 h-5"></i></button>
                                     <button class="view-complaint-btn text-gray-500 hover:text-gray-700 p-1 rounded-full hover:bg-gray-50" data-id="${complaint.id}" title="Ver Detalles"><i data-lucide="eye" class="w-5 h-5"></i></button>
                                     <button class="delete-complaint-btn text-[var(--color-secondary)] hover:text-[var(--color-secondary)] p-1 rounded-full hover:bg-white" data-id="${complaint.id}" title="Eliminar Permanentemente"><i data-lucide="trash-2" class="w-5 h-5"></i></button>
                                 </div>
                             </td>`;
            tableBody.appendChild(row);
        });
        
        tableBody.querySelectorAll('.view-complaint-btn').forEach(btn => {
            btn.addEventListener('click', (e) => openComplaintDetailsPanel(e.currentTarget.dataset.id));
        });
        
        lucide.createIcons();
    }

    // RENDERIZADO PRINCIPAL (Ajustado para usar los contadores de columna)
    function renderAll(filterStatus = 'all') {
        // 1. Limpiar y re-renderizar tarjetas
        document.querySelectorAll('.complaint-column').forEach(col => {
            col.innerHTML = '';
            // Reiniciar contadores de columna
            const slug = col.dataset.status.replace(/ /g, '-').toLowerCase();
            document.getElementById(`count-${slug}`).textContent = '0';
        });
        
        const columnCounts = {};
        
        Object.values(complaintsData).forEach(complaint => {
            const statusMatch = filterStatus === 'all' || complaint.status === filterStatus;
            
            if (statusMatch) {
                const slug = complaint.status.replace(/ /g, '-').toLowerCase();
                const column = document.getElementById(`column-${slug}`);
                if (column) {
                    column.appendChild(renderComplaintCard(complaint));
                    columnCounts[slug] = (columnCounts[slug] || 0) + 1;
                }
            }
        });
        
        // 2. Actualizar contadores de columna
        for (const slug in columnCounts) {
             document.getElementById(`count-${slug}`).textContent = columnCounts[slug];
        }

        // 3. Actualizar contadores de tarjetas
        const activeArray = Object.values(complaintsData);
        document.getElementById('count-abiertos').textContent = activeArray.filter(c => c.status === 'Recibido' || c.status === 'Acción Requerida').length;
        document.getElementById('count-resolviendo').textContent = activeArray.filter(c => c.status === 'Resolviendo').length;
        document.getElementById('count-resueltos').textContent = activeArray.filter(c => c.status === 'Resuelto').length;
        
        // 4. Renderizar tabla de archivados
        renderArchivedTable();
        
        lucide.createIcons();
    }
    
    // Evento de Filtro Rápido
    document.getElementById('status-filter').addEventListener('change', function() {
        renderAll(this.value);
    });

    // Funciones archiveComplaint, reopenComplaint, drag & drop (se mantienen)
    async function archiveComplaint(complaintId) {
        const formData = new FormData();
        formData.append('id', complaintId);
        formData.append('status', 'Archivado');
        formData.append('action', 'update_status');
        try {
            const response = await fetch(API_UPDATE_URL, { method: 'POST', body: formData });
            const result = await response.json();
            if (result.success && result.complaint) {
                const archivedItem = { ...complaintsData[complaintId], status: 'Archivado', updated_at: new Date().toISOString() };
                delete complaintsData[complaintId];
                archivedComplaints.unshift(archivedItem);
                renderAll(document.getElementById('status-filter').value);
                showToast('RECLAMO ARCHIVADO CON ÉXITO', 'success');
            } else { showToast(result.message || 'Error al archivar.', 'error'); }
        } catch (error) { showToast('Error de conexión al archivar.', 'error'); }
    }

    async function reopenComplaint(complaintId) {
        const formData = new FormData();
        formData.append('id', complaintId);
        formData.append('status', 'Recibido');
        formData.append('action', 'update_status');
        try {
            const response = await fetch(API_UPDATE_URL, { method: 'POST', body: formData });
            const result = await response.json();
            if (result.success && result.complaint) {
                const reopenedItem = archivedComplaints.find(c => c.id == complaintId);
                archivedComplaints = archivedComplaints.filter(c => c.id != complaintId);
                complaintsData[complaintId] = { ...reopenedItem, status: 'Recibido' };
                renderAll(document.getElementById('status-filter').value);
                showToast('RECLAMO REABIERTO".', 'success');
            } else { showToast(result.message || 'Error al reabrir.', 'error'); }
        } catch (error) { showToast('Error de conexión al reabrir.', 'error'); }
    }

    document.querySelectorAll('.complaint-column').forEach(column => {
        column.addEventListener('dragover', e => e.preventDefault());
        column.addEventListener('drop', async (e) => {
            e.preventDefault();
            const complaintId = e.dataTransfer.getData('text/plain');
            const newStatus = column.dataset.status;
            if (complaintsData[complaintId] && complaintsData[complaintId].status !== newStatus) {
                const formData = new FormData();
                formData.append('id', complaintId);
                formData.append('status', newStatus);
                formData.append('action', 'update_status');
                try {
                    const response = await fetch(API_UPDATE_URL, { method: 'POST', body: formData });
                    const result = await response.json();
                    if (result.success && result.complaint) {
                        complaintsData[complaintId] = result.complaint;
                        renderAll(document.getElementById('status-filter').value); 
                        showToast('ESTADO ACTUALIZADO', 'success');
                    } else { showToast(result.message || 'Error al actualizar', 'error'); }
                } catch(error) { showToast('Error de conexión.', 'error'); }
            }
        });
    });

    // --- GESTIÓN DE MODALES  ---
    function openDeleteModal(id) {
        pendingDeletionId = id;
        closePanel('viewComplaintPanel'); 
        const modal = document.getElementById('confirmDeleteModal');
        modal.classList.remove('hidden');
        setTimeout(() => modal.querySelector('div').classList.remove('scale-95', 'opacity-0'), 10);
    }
    function closeDeleteModal() {
        const modal = document.getElementById('confirmDeleteModal');
        modal.querySelector('div').classList.add('scale-95', 'opacity-0');
        setTimeout(() => modal.classList.add('hidden'), 300);
    }
    
    document.getElementById('archived-complaints-table-body').addEventListener('click', (e) => {
        const deleteBtn = e.target.closest('.delete-complaint-btn');
        const reopenBtn = e.target.closest('.reopen-complaint-btn');
        if (deleteBtn) {
            openDeleteModal(deleteBtn.dataset.id);
        } else if (reopenBtn) {
            reopenComplaint(reopenBtn.dataset.id);
        }
    });
    document.getElementById('delete-complaint-btn-view').addEventListener('click', () => openDeleteModal(currentViewingComplaintId));
    document.getElementById('cancel-delete-button').addEventListener('click', closeDeleteModal);
    document.getElementById('confirm-delete-button').addEventListener('click', () => {
        if (pendingDeletionId) {
            deleteComplaint(pendingDeletionId);
            closeDeleteModal();
        }
    });

    async function deleteComplaint(complaintId) {
        try {
            const response = await fetch(API_DELETE_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: complaintId }) });
            const result = await response.json();
            if (result.success) {
                archivedComplaints = archivedComplaints.filter(c => c.id != complaintId);
                if (complaintsData[complaintId]) delete complaintsData[complaintId];
                renderAll(document.getElementById('status-filter').value);
                showToast('RECLAMO ELIMINADO', 'success');
            } else { showToast(result.message || 'Error al eliminar.', 'error'); }
        } catch (error) { showToast('Error de conexión.', 'error'); }
    }
    
    const whatsappModal = document.getElementById('whatsappModal');
    const whatsappMessageText = document.getElementById('whatsappMessageText');
    const closeModalBtn = document.getElementById('closeModalBtn');
    const copyAndOpenWhatsAppBtn = document.getElementById('copyAndOpenWhatsAppBtn');
    
    function openWhatsAppModal() {
        whatsappModal.classList.remove('hidden');
        setTimeout(() => whatsappModal.querySelector('div').classList.remove('scale-95', 'opacity-0'), 10);
    }
    function closeWhatsAppModal() {
        whatsappModal.querySelector('div').classList.add('scale-95', 'opacity-0');
        setTimeout(() => whatsappModal.classList.add('hidden'), 300);
    }
    
    document.getElementById('generate-whatsapp-btn').addEventListener('click', () => {
        const allComplaints = {...complaintsData, ...archivedComplaints.reduce((acc, p) => ({...acc, [p.id]: p}), {})};
        const complaint = allComplaints[currentViewingComplaintId];
        if(!complaint) return;
        whatsappMessageText.value = `¡Hola ${complaint.client_name}! \n\nAcerca de su caso: "${complaint.title}", le informamos lo siguiente: `;
        openWhatsAppModal();
    });
    copyAndOpenWhatsAppBtn.addEventListener('click', () => {
        const message = encodeURIComponent(whatsappMessageText.value);
        
        navigator.clipboard.writeText(whatsappMessageText.value).then(() => {
            const originalBtnText = copyAndOpenWhatsAppBtn.innerHTML;
            copyAndOpenWhatsAppBtn.innerHTML = `<i data-lucide="check" class="w-5 h-5"></i> ¡Copiado! Abriendo WhatsApp...`;
            lucide.createIcons();
            
            window.open('https://wa.me/', '_blank'); 
            
            setTimeout(() => {
                copyAndOpenWhatsAppBtn.innerHTML = originalBtnText;
                lucide.createIcons();
                closeWhatsAppModal();
            }, 2000);
        }).catch(err => showToast('Error al copiar el mensaje.', 'error'));
    });
    closeModalBtn.addEventListener('click', closeWhatsAppModal);
    
    // --- LÓGICA DE TRADUCCIÓN IA ---
    const translateBtn = document.getElementById('translate-with-ia-btn');
    const spanishTextarea = document.getElementById('spanish-response-textarea');
    const translationResultContainer = document.getElementById('translation-result-container');
    const englishTextarea = document.getElementById('english-translation-textarea');
    const copyTranslationBtn = document.getElementById('copy-translation-btn');

    translateBtn.addEventListener('click', async () => {
        const textToTranslate = spanishTextarea.value;
        if (!textToTranslate.trim()) { showToast('Por favor, escribe un texto para traducir.', 'error'); return; }
        translateBtn.disabled = true;
        translateBtn.innerHTML = '<i data-lucide="loader" class="w-4 h-4 mr-2 animate-spin"></i> Traduciendo...';
        lucide.createIcons();
        translationResultContainer.classList.add('hidden');
        try {
            const response = await fetch('api/api-traductor-ingles-inteligente.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json; charset=utf-8' },
                body: JSON.stringify({ ad_text_es: textToTranslate, translation_type: 'Estrategica', translation_tone: 'Profesional y Formal' })
            });
            if (!response.ok) throw new Error(`Error del servidor: ${response.status} ${response.statusText}`);
            const data = await response.json();
            if (data.error) throw new Error(data.error);
            englishTextarea.value = data.traduccion;
            translationResultContainer.classList.remove('hidden');
        } catch (error) {
            console.error('Detalles completos del error de traducción:', error);
            let userMessage = `Error: No se pudo conectar al servicio de traducción.`;
            showToast(userMessage, 'error');
            translationResultContainer.innerHTML = `<div class="bg-[var(--color-secondary)] text-center p-4 text-white rounded-lg border border-[var(--color-secondary)]"><p><strong>Error:</strong> ${userMessage}</p></div>`;
            translationResultContainer.classList.remove('hidden');
        } finally {
            translateBtn.disabled = false;
            translateBtn.innerHTML = '<i data-lucide="bot" class="w-4 h-4 mr-2"></i> Traducir a Inglés con IA';
            lucide.createIcons();
        }
    });

    copyTranslationBtn.addEventListener('click', () => {
        navigator.clipboard.writeText(englishTextarea.value).then(() => {
            showToast('Traducción copiada al portapapeles.', 'success');
            const originalText = copyTranslationBtn.textContent;
            copyTranslationBtn.textContent = '¡Copiado!';
            setTimeout(() => { copyTranslationBtn.textContent = originalText; }, 2000);
        });
    });
    
    // Inicialización
    renderAll();
});
</script>
</body>
</html>