<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init.php');

// Inicialización
$active_complaints = [];
$archived_complaints = [];
$complaints_counts = ['Recibido' => 0, 'Resolviendo' => 0, 'Acción Requerida' => 0, 'Resuelto' => 0];
$cards_counts = ['abiertos' => 0, 'resolviendo' => 0, 'resueltos' => 0]; 

    // 1. OPTIMIZACIÓN SQL Y MITIGACIÓN SQLI
    $sql = "
        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
        LIMIT 200 
    ";
    
    $stmt_complaints = $pdo->prepare($sql);
    $stmt_complaints->execute();
    
    while ($row = $stmt_complaints->fetch(PDO::FETCH_ASSOC)) {
        
        // 2. SEGURIDAD (Sanitización Preventiva):
        $complaint_data = [
            'id' => $row['id'],
            'title' => htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8'),
            'description' => htmlspecialchars($row['description'], ENT_QUOTES, 'UTF-8'),
            'client_name' => $row['first_name'] ? htmlspecialchars(trim($row['first_name'] . ' ' . $row['last_name']), ENT_QUOTES, 'UTF-8') : 'Cliente no encontrado',
            'client_id' => $row['client_id'],
            'service_name' => $row['service_name'] ? htmlspecialchars($row['service_name'], ENT_QUOTES, 'UTF-8') : 'No asignado',
            'service_id' => $row['service_id'] ?? null,
            'created_at' => $row['created_at'],
            'status' => $row['status'],
            'updated_at' => $row['updated_at']
        ];
        
        // Separación lógica
        if ($row['status'] === 'Archivado') {
            $archived_complaints[] = $complaint_data;
        } else {
            $active_complaints[$row['id']] = $complaint_data;
            
            if (isset($complaints_counts[$row['status']])) {
                $complaints_counts[$row['status']]++;
            }
        }
    }
    
    // Recálculo de tarjetas resumen
    $cards_counts = [
        'abiertos' => ($complaints_counts['Recibido'] ?? 0) + ($complaints_counts['Acción Requerida'] ?? 0),
        'resolviendo' => $complaints_counts['Resolviendo'] ?? 0,
        'resueltos' => $complaints_counts['Resuelto'] ?? 0
    ];

    // Carga de servicios (MITIGACIÓN SQLI)
    $services = [];
    $stmt_services = $pdo->prepare("SELECT id, name FROM services ORDER BY name");
    $stmt_services->execute();
    while($svc = $stmt_services->fetch(PDO::FETCH_ASSOC)){
        $services[] = [
            'id' => $svc['id'],
            'name' => htmlspecialchars($svc['name'], ENT_QUOTES, 'UTF-8')
        ];
    }

} catch (PDOException $e) {
    error_log("Error crítico en complaints dashboard: " . $e->getMessage());
} catch (Exception $e) {
    error_log("Error general en complaints dashboard: " . $e->getMessage());
}

// JSON Payload seguro
$complaints_json = json_encode($active_complaints);
$archived_complaints_json = json_encode($archived_complaints);
$services_json = json_encode($services);

if (ob_get_level() > 0) {
    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>Panel De Gestión De Reclamos <?php echo htmlspecialchars($branding['full_title']); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url); ?>">

    <?php include 'files/gtm-head.php'; ?>
    
    <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">
            
            <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-highlight)]">
        <i data-lucide="inbox" class="w-12 h-12 text-[var(--color-secondary)]"></i>
        <div>
            <h3 class="text-lg font-black 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-[var(--color-secondary)]"></i>
        <div>
            <h3 class="text-lg font-black text-gray-500 mb-1text-lg font-black text-gray-500 mb-1 uppercase">EN PROCESO</h3>
            <p id="count-resolviendo" class="text-5xl font-bold text-[var(--color-primary)]"><?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-highlight)]">
        <i data-lucide="check-circle-2" class="w-12 h-12 text-[var(--color-secondary)]"></i>
        <div>
            <h3 class="text-lg font-black 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>
            <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="flex flex-col md:flex-row items-center gap-4 w-full md:w-auto">
                            <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 w-full">
                                    <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>
                            
                            <button id="open-create-complaint-btn" class="btn-primary w-full md:w-auto font-bold py-2 px-4 rounded-lg uppercase flex items-center justify-center shadow-lg hover:shadow-xl transition-all duration-200 flex-shrink-0">
                                <i data-lucide="plus-circle" class="w-5 h-5 mr-2"></i>
                                Nuevo Reclamo
                            </button>
                        </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">
                                        <?php echo $complaints_counts[$name] ?? 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 top-0 right-0 h-full w-full lg:w-2/5 bg-[var(--color-background)] z-50 transform translate-x-full transition-transform duration-300 ease-in-out shadow-2xl">
    
    <div class="flex flex-col h-full">
        <div class="flex-shrink-0 flex justify-between items-center p-4 border-b border-gray-200 bg-[var(--color-primary)] text-white shadow z-20">
            <h3 class="text-3xl font-black text-[var(--color-highlight)] flex items-center uppercase">
                <i data-lucide="message-square-text" class="w-8 h-8 mr-2 text-white"></i>
                FICHA Y SEGUIMIENTO
            </h3>
            <button onclick="closePanel('viewComplaintPanel')" class="bg-[var(--color-secondary)] text-white hover:text-[var(--color-highlight)] p-1 rounded-md transition-colors duration-200">
                <i data-lucide="x" class="w-8 h-8"></i>
            </button>
        </div>

        <div class="flex-grow overflow-y-auto p-4 space-y-6 relative">
            
            <div id="view-complaint-content" class="bg-white p-4 rounded-xl shadow-md transition duration-300">
                
                <div class="border-b pb-3 mb-4 text-center">
                    <h2 id="view-complaint-title" class="text-2xl font-black text-gray-800 uppercase leading-tight"></h2>
                </div>
                
                <div class="bg-gray-50 p-3 rounded-lg border border-gray-100 mb-4">
                    <h4 class="text-xs font-bold text-gray-500 uppercase mb-2 flex items-center">
                        <i data-lucide="user" class="w-3 h-3 mr-1"></i> Cliente
                    </h4>
                    <p id="view-complaint-client" class="text-lg font-black text-gray-700 mb-3"></p>
                    
                    <div class="space-y-2">
                        <div>
                            <label for="view-complaint-service-select" class="block text-xs font-bold text-gray-500 uppercase mb-1">Servicio Relacionado</label>
                            <select id="view-complaint-service-select" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm bg-white">
                                <option value="">No asignado</option>
                            </select>
                        </div>
                        
                        <div id="status-tag-container" class="pt-2">
                            </div>
                    </div>
                </div>

                <div>
                    <h4 class="text-xs font-bold text-gray-500 uppercase mb-2 flex items-center">
                        <i data-lucide="align-left" class="w-3 h-3 mr-1"></i> Descripción
                    </h4>
                    <div class="p-3 border border-gray-200 rounded-lg bg-gray-50">
                        <p id="view-complaint-description" class="text-sm text-gray-700 whitespace-pre-wrap"></p>
                    </div>
                </div>

                <button id="archive-complaint-btn-view" type="button" class="w-full mt-4 bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded-lg uppercase hidden transition-colors duration-200 flex items-center justify-center text-xs">
                    <i data-lucide="archive" class="w-4 h-4 mr-2"></i> Archivar Caso
                </button>
            </div>

            <div class="bg-white p-4 rounded-xl shadow-md transition duration-300 border-l-4 border-[var(--color-secondary)]">
                <div class="border-b pb-3 mb-4">
                    <h4 class="text-xl font-black text-[var(--color-secondary)] uppercase flex items-center">
                        <i data-lucide="bot" class="w-5 h-5 mr-2"></i>
                        ASISTENTE IA
                    </h4>
                </div>

                <div class="space-y-4">
                    <div>
                        <label for="spanish-response-textarea" class="block text-md font-bold text-gray-600 mb-1 uppercase">Respuesta en Español</label>
                        <textarea id="spanish-response-textarea" rows="3" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="Escribe aquí..."></textarea>
                    </div>
                    
                    <button id="translate-with-ia-btn" class="w-full bg-gray-200 hover:bg-gray-300 text-gray-700 font-bold py-2 px-4 rounded-lg uppercase transition-colors duration-200 flex items-center justify-center text-xs border border-gray-300">
                        <i data-lucide="languages" class="w-4 h-4 mr-2"></i> Traducir a Inglés
                    </button>

                    <div id="translation-result-container" class="hidden pt-3 border-t border-gray-100">
                        <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Traducción (Inglés)</label>
                        <div class="relative">
                            <textarea id="english-translation-textarea" rows="3" readonly class="w-full p-2 border border-gray-300 rounded-lg bg-gray-50 text-gray-700 text-sm"></textarea>
                            <button id="copy-translation-btn" class="absolute top-2 right-2 bg-white border border-gray-300 text-gray-600 font-bold p-1 rounded hover:bg-gray-50 transition-colors duration-200">
                                <i data-lucide="copy" class="w-4 h-4"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-white p-4 rounded-xl shadow-md transition duration-300">
                <div class="border-b pb-3 mb-4">
                    <h4 class="text-xl font-black text-[var(--color-secondary)] uppercase flex items-center">
                        <i data-lucide="history" class="w-5 h-5 mr-2"></i>
                        HISTORIAL
                    </h4>
                </div>
                <div id="complaint-history-log" class="space-y-4 max-h-60 overflow-y-auto pr-2 custom-scrollbar bg-gray-50 p-2 rounded border border-gray-100">
                    </div>
            </div>
            
            <div class="bg-white p-4 rounded-xl shadow-md transition duration-300">
                <div class="border-b pb-3 mb-4">
                    <h4 class="text-xl font-black text-[var(--color-secondary)] uppercase flex items-center">
                        <i data-lucide="send" class="w-5 h-5 mr-2"></i>
                        ACCIONES
                    </h4>
                </div>
                <div class="space-y-4">
                    <div>
                        <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Publicar en Portal</label>
                        <textarea id="portal-message-input" rows="2" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="Mensaje visible para el cliente..."></textarea>
                        <button id="publish-portal-message-btn" class="w-full mt-2 bg-[var(--color-primary)] hover:bg-[var(--color-highlight)] text-white font-bold py-2 px-4 rounded-lg uppercase flex items-center justify-center text-sm shadow-sm transition-all">
                            <i data-lucide="send" class="w-4 h-4 mr-2"></i> ENVIAR
                        </button>
                    </div>
                    
                    <div class="border-t pt-3">
                        <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Nota Interna</label>
                        <textarea id="internal-note-input" rows="2" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-secondary)] focus:ring-[var(--color-secondary)] focus:ring-1 transition duration-150 text-sm" placeholder="Solo visible para el equipo..."></textarea>
                        <button id="save-internal-note-btn" class="w-full mt-2 bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg uppercase flex items-center justify-center text-sm shadow-sm transition-all">
                            <i data-lucide="bookmark" class="w-4 h-4 mr-2"></i> GUARDAR NOTA
                        </button>
                    </div>
                </div>
            </div>

        </div>

        <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0 z-10"> 
            <div class="grid grid-cols-3 gap-2">
                <button id="delete-complaint-btn-view" type="button" class="w-full bg-red-600 hover:bg-red-700 text-white font-black py-2 rounded-lg uppercase flex items-center justify-center gap-1 shadow-md text-xs md:text-sm transition-all duration-200">
                    <i data-lucide="trash-2" class="w-4 h-4"></i> ELIMINAR
                </button>

                <button type="button" class="w-full btn-cancel font-black py-2 rounded-lg uppercase flex items-center justify-center gap-1 text-xs md:text-sm" onclick="closePanel('viewComplaintPanel')">
                    <i data-lucide="x-circle" class="w-4 h-4"></i> CERRAR
                </button>

                <button id="generate-whatsapp-btn" type="button" class="w-full bg-[#25D366] hover:bg-[#128C7E] text-white font-black py-2 rounded-lg uppercase flex items-center justify-center gap-1 shadow-md text-xs md:text-sm transition-all duration-200">
                    <i data-lucide="message-circle" class="w-4 h-4"></i> WHATSAPP
                </button>
            </div>
        </div>
    </div>
</div>

<div id="createComplaintPanel" class="fixed inset-0 bg-gray-900 bg-opacity-90 flex items-center justify-center hidden z-50 font-barlow" onclick="if(event.target === this) closePanel('createComplaintPanel')">
    
    <div class="modal-dialog relative mx-auto p-0 border-0 shadow-2xl rounded-xl bg-white w-full max-w-lg transform transition-all duration-300 scale-95 opacity-0 overflow-hidden">
        
        <div class="modal-header-container bg-[var(--color-primary)] p-6">
            <h3 class="modal-primary-title text-3xl font-black text-[var(--color-highlight)] uppercase leading-none">
                NUEVO RECLAMO
            </h3>
            <p class="text-xs font-bold text-gray-200 uppercase mt-2 tracking-wider">REGISTRO DE INCIDENTE</p>
        </div>

        <div class="p-8">
            <form id="create-complaint-form" class="space-y-4 text-left">
                <div>
                    <label for="complaint-title-create" class="block text-md font-bold text-gray-600 mb-1 uppercase">Título Del Reclamo</label>
                    <input type="text" id="complaint-title-create" name="title" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" required placeholder="Ej: Problema Con El Servicio">
                </div>

                <div>
                    <label for="complaint-client-search" class="block text-md font-bold text-gray-600 mb-1 uppercase">Cliente</label>
                    <input type="hidden" id="complaint-client-id" name="client_id" required>
                    
                    <div id="selected-client-display" class="hidden p-2 mb-2 border border-green-200 bg-green-50 rounded-lg flex justify-between items-center">
                        <span class="font-bold text-green-800 text-sm flex items-center uppercase">
                            <i data-lucide="check-circle" class="w-4 h-4 mr-2"></i> <span class="client-name-text"></span>
                        </span>
                        <button type="button" id="clear-client-btn" class="text-red-500 hover:text-red-700 font-bold p-1">
                            <i data-lucide="x" class="w-4 h-4"></i>
                        </button>
                    </div>

                    <div class="relative">
                        <input type="text" id="complaint-client-search" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="Buscar cliente..." autocomplete="off">
                        <i data-lucide="search" class="w-4 h-4 text-gray-400 absolute right-3 top-1/2 -translate-y-1/2"></i>
                    </div>
                    
                    <div id="client-search-results" class="relative z-10 mt-1"></div>
                </div>

                <div>
                    <label for="complaint-service" class="block text-md font-bold text-gray-600 mb-1 uppercase">Servicio Relacionado (Opcional)</label>
                    <select id="complaint-service" name="service_id" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm bg-white">
                        <option value="">Ningún Servicio Asignado</option>
                    </select>
                </div>

                <div>
                    <label for="complaint-description-create" class="block text-md font-bold text-gray-600 mb-1 uppercase">Descripción Detallada</label>
                    <textarea id="complaint-description-create" name="description" rows="4" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" required placeholder="Describa el problema en detalle..."></textarea>
                </div>
            </form>

            <div class="flex flex-col sm:flex-row justify-center space-y-3 sm:space-y-0 sm:space-x-4 mt-8">
                <button type="button" class="btn-modal-cancel font-black py-2.5 px-6 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 shadow-sm" onclick="closePanel('createComplaintPanel')">
                    <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                </button>
                <button id="save-complaint-btn" type="submit" form="create-complaint-form" class="btn-modal-confirm font-black py-2.5 px-6 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 shadow-md">
                    <i data-lucide="save" class="w-5 h-5"></i> GUARDAR
                </button>
            </div>
        </div>
    </div>
</div>


<div id="confirmDeleteModal" 
     class="fixed inset-0 bg-gray-900 bg-opacity-90 flex items-center justify-center hidden z-50 font-barlow"
     onclick="if(event.target === this) document.querySelector('#confirmDeleteModal .close-modal-btn, #confirmDeleteModal #cancel-delete-button').click()">
    
    <div class="modal-dialog relative mx-auto p-0 border-0 shadow-2xl rounded-xl bg-white w-full max-w-sm m-4 text-center transform transition-all duration-300 scale-95 opacity-0 overflow-hidden">
        
        <div class="modal-header-container bg-[var(--color-primary)] p-6">
            <h3 class="modal-primary-title text-3xl font-black text-[var(--color-highlight)] uppercase leading-none">ADVERTENCIA</h3>
        </div>

        <div class="p-8">
            <div class="flex justify-center mb-6">
                <i data-lucide="alert-triangle" class="w-16 h-16 text-[var(--color-secondary)]"></i>
            </div>
            
            <p class="text-[var(--color-primary)] mb-6 uppercase text-lg font-bold leading-tight">
                ¿ELIMINAR PERMANENTEMENTE EL CASO 
                <span id="confirm-dynamic-name" class="font-black text-[var(--color-secondary)] text-xl inline-block uppercase mx-1"></span>
                ?
            </p>

            <input type="hidden" id="confirm-action-type">
            <input type="hidden" id="confirm-client-id">
            <input type="hidden" id="confirm-route-id">
            <input type="hidden" id="confirm-week-number">
            <input type="hidden" id="confirm-update-id"> 

            <div class="flex flex-col sm:flex-row justify-center space-y-3 sm:space-y-0 sm:space-x-4">
                <button type="button" class="btn-modal-cancel font-black py-2.5 px-6 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 close-modal-btn" id="cancel-delete-button">
                    <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                </button>
                
                <button type="button" class="btn-modal-confirm font-black py-2.5 px-6 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 shadow-md" id="confirm-delete-button">
                    <i data-lucide="trash-2" class="w-5 h-5"></i> ELIMINAR
                </button>
            </div>
            
            <p class="mt-6 uppercase text-xs font-black text-gray-500 tracking-wider"> 
                ESTA ACCIÓN NO SE PUEDE DESHACER
            </p>

            <p id="confirm-modal-message" class="hidden"></p>
        </div>
    </div>
</div>

<div id="whatsappModal" 
     class="fixed inset-0 bg-gray-900 bg-opacity-90 flex items-center justify-center hidden z-50 font-barlow"
     onclick="if(event.target === this) document.querySelector('#whatsappModal #closeModalBtn').click()">
    
    <div class="modal-dialog relative mx-auto p-0 border-0 shadow-2xl rounded-xl bg-white w-full max-w-lg m-4 text-center transform transition-all duration-300 scale-95 opacity-0 overflow-hidden">
        
        <div class="modal-header-container bg-[var(--color-primary)] p-4 text-white shadow z-20">
            <div class="flex justify-between items-center">
                <h3 class="text-2xl font-black text-[var(--color-highlight)] flex items-center gap-3 uppercase leading-none">
                    <i data-lucide="message-circle" class="w-8 h-8 text-[var(--color-highlight)]"></i> 
                    GENERAR MENSAJE
                </h3>
                <button id="closeModalBtn" class="bg-[var(--color-secondary)] text-white hover:text-[var(--color-highlight)] p-1 rounded-md transition-colors duration-200">
                    <i data-lucide="x" class="w-6 h-6"></i>
                </button>
            </div>
        </div>

        <div class="p-6">
            <p class="text-[var(--color-primary)] font-black mb-4 uppercase text-lg">
                MENSAJE LISTO PARA COPIAR.
            </p>
            
            <textarea id="whatsappMessageText" rows="5" class="w-full p-3 border-2 border-gray-300 rounded-lg bg-gray-50 text-gray-800 focus:ring-2 focus:ring-[var(--color-primary)] focus:border-[var(--color-primary)] transition-all duration-200 font-medium"></textarea>
            
            <div class="flex flex-col sm:flex-row justify-center space-y-3 sm:space-y-0 sm:space-x-4 mt-6">
                <button type="button" 
                        class="btn-modal-cancel font-black py-2.5 px-6 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2"
                        onclick="document.querySelector('#whatsappModal #closeModalBtn').click()">
                    <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                </button>
                
                <button id="copyAndOpenWhatsAppBtn" 
                        class="w-full btn-modal-confirm font-black py-2.5 px-6 rounded-lg uppercase flex items-center justify-center gap-2 shadow-md">
                    <i data-lucide="copy" class="w-5 h-5"></i>
                    <span>COPIAR MENSAJE</span>
                </button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    
    // --- 1. UTILIDADES Y CONFIGURACIÓN INICIAL ---
    
    // UI: Control de Paneles Laterales
    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) => { 
        // Si es un modal en lugar de panel lateral, usar showModal
        if(id === 'createComplaintPanel') {
             showModal('createComplaintPanel');
        } else {
             document.getElementById(id)?.classList.remove('translate-x-full'); 
             panelOverlay.classList.remove('hidden'); 
        }
    };
    window.closePanel = (id) => { 
        if(id === 'createComplaintPanel') {
             hideModal('createComplaintPanel');
        } else {
             document.getElementById(id)?.classList.add('translate-x-full'); 
             panelOverlay.classList.add('hidden'); 
        }
    };
    
    // SEGURIDAD: Función Helper anti-XSS
    function escapeHtml(text) {
        if (!text) return '';
        return text.toString()
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }
    
    // Función para mostrar cualquier modal estandarizado
    function showModal(modalId) {
        const modal = document.getElementById(modalId);
        if (!modal) return;
        const modalBox = modal.querySelector('.modal-dialog');
        modal.classList.remove('hidden');
        setTimeout(() => { 
            modalBox.classList.remove('scale-95', 'opacity-0'); 
            modalBox.classList.add('scale-100', 'opacity-100'); 
        }, 10);
        document.body.style.overflow = 'hidden'; // Evitar scroll de fondo
        lucide.createIcons();
    }
    
    // Función para cerrar cualquier modal estandarizado
    function hideModal(modalId) {
        const modal = document.getElementById(modalId);
        if (!modal) return;
        const modalBox = modal.querySelector('.modal-dialog');
        modalBox.classList.remove('scale-100', 'opacity-100');
        modalBox.classList.add('scale-95', 'opacity-0');
        setTimeout(() => { 
            modal.classList.add('hidden'); 
            document.body.style.overflow = ''; // Restaurar scroll
        }, 300);
    }
    

    // --- 2. DATOS Y VARIABLES GLOBALES ---
    // NOTA: Asegúrate de que PHP está inyectando estos JSON correctamente.
    let complaintsData = <?php echo $complaints_json ?: '{}'; ?>; 
    let archivedComplaints = <?php echo $archived_complaints_json ?: '[]'; ?>;
    let allServices = <?php echo $services_json ?: '[]'; ?>;
    let currentViewingComplaintId = null;
    let onConfirmDeleteAction = null;
    let currentConfirmActionType = null;

    // Endpoints API
    const API_UPDATE_URL = 'db/complaints-update.php';
    const API_DELETE_URL = 'db/complaints-delete.php';
    const API_CREATE_URL = 'db/complaints-create.php';
    const API_SEARCH_CLIENTS_URL = 'db/complaints-search-clients.php';
    const API_DELETE_UPDATE_URL = 'db/complaints-delete-update.php'; 

    // Colores de estado
    const STATUS_COLORS = { 
        'Recibido': 'border-gray-500', 
        'Resolviendo': 'border-[var(--color-highlight)]', 
        'Acción Requerida': 'border-[var(--color-secondary)]', 
        'Resuelto': 'border-[var(--color-primary)]' 
    };
    
    // --- 3. FUNCIONES CORE (RENDERIZADO) ---

    // Renderizar Tarjeta Individual (SEGURA)
    function renderComplaintCard(complaint) {
        const card = document.createElement('div');
        const borderColor = STATUS_COLORS[complaint.status] || 'border-gray-500';
        
        card.className = `p-4 bg-white rounded-xl shadow-md cursor-grab transition-all duration-300 border-l-4 ${borderColor} hover:shadow-xl hover:scale-[1.01] active:cursor-grabbing kanban-card`;
        card.draggable = true;
        card.dataset.complaintId = complaint.id;
        
        // Sanitización visual
        const safeTitle = escapeHtml(complaint.title);
        const safeClient = escapeHtml(complaint.client_name);
        const safeService = escapeHtml(complaint.service_name);

        let cardHTML = `
            <h5 class="font-bold text-gray-900 mb-1 leading-snug">${safeTitle}</h5>
            <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>${safeClient}
            </p>`;
            
        if (complaint.service_name && complaint.service_name !== 'No asignado') {
            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: ${safeService}
            </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;

        // Event Listeners Tarjeta
        card.addEventListener('click', (e) => {
            if (!e.target.closest('.archive-btn')) openComplaintDetailsPanel(complaint.id);
        });
        
        const archiveBtn = card.querySelector('.archive-btn');
        if (archiveBtn) {
            archiveBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                archiveComplaint(complaint.id);
            });
        }
        
        card.addEventListener('dragstart', e => e.dataTransfer.setData('text/plain', complaint.id));
        
        return card;
    }

    // Renderizar 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 safeTitle = escapeHtml(complaint.title);
            const safeClient = escapeHtml(complaint.client_name);
            const safeService = escapeHtml(complaint.service_name);

            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">${safeTitle}</td>
                             <td class="py-4 px-6 hidden md:table-cell">${safeClient}</td>
                             <td class="py-4 px-6 hidden lg:table-cell">${safeService}</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();
    }

    // Renderizar Todo (Dashboard)
    function renderAll(filterStatus = 'all') {
        const columnCounts = {
            'recibido': 0, 'resolviendo': 0, 'acción-requerida': 0, 'resuelto': 0
        };
        const activeArray = Object.values(complaintsData);

        activeArray.forEach(complaint => {
            const slug = complaint.status.replace(/ /g, '-').toLowerCase();
            if (columnCounts.hasOwnProperty(slug)) {
                columnCounts[slug]++;
            }
        });

        // Actualizar contadores visuales
        for (const slug in columnCounts) {
            const countEl = document.getElementById(`count-${slug}`);
            if (countEl) countEl.textContent = columnCounts[slug];
        }
        document.getElementById('count-abiertos').textContent = columnCounts['recibido'] + columnCounts['acción-requerida'];
        document.getElementById('count-resolviendo').textContent = columnCounts['resolviendo'];
        document.getElementById('count-resueltos').textContent = columnCounts['resuelto'];

        // Limpiar columnas
        document.querySelectorAll('.complaint-column').forEach(col => col.innerHTML = '');

        // Llenar columnas
        activeArray.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));
                }
            }
        });
        
        renderArchivedTable();
        lucide.createIcons();
    }

    // --- 4. CREACIÓN DE RECLAMOS (LÓGICA) ---
    const createComplaintPanel = document.getElementById('createComplaintPanel');
    const createComplaintForm = document.getElementById('create-complaint-form');
    const saveComplaintBtn = document.getElementById('save-complaint-btn');
    const serviceSelectCreate = document.getElementById('complaint-service');
    
    // Buscador
    const clientSearchInput = document.getElementById('complaint-client-search');
    const clientSearchResults = document.getElementById('client-search-results');
    const hiddenClientIdInput = document.getElementById('complaint-client-id');
    const selectedClientDisplay = document.getElementById('selected-client-display');
    const selectedClientNameSpan = selectedClientDisplay.querySelector('span');
    const clearClientBtn = document.getElementById('clear-client-btn');

    // Poblar select
    allServices.forEach(service => {
        const option = document.createElement('option');
        option.value = service.id;
        option.textContent = service.name;
        serviceSelectCreate.appendChild(option);
    });

    function debounce(func, delay) {
        let timeout;
        return function(...args) {
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(this, args), delay);
        };
    }

    const searchClients = async (term) => {
        if (term.length < 2) {
            clientSearchResults.innerHTML = '';
            clientSearchResults.classList.add('hidden');
            return;
        }
        try {
            const response = await fetch(`${API_SEARCH_CLIENTS_URL}?term=${encodeURIComponent(term)}`);
            const result = await response.json();
            clientSearchResults.innerHTML = '';
            clientSearchResults.classList.remove('hidden');
            clientSearchResults.classList.add('absolute', 'w-full', 'bg-white', 'border', 'border-gray-300', 'rounded-b-lg', 'shadow-lg', 'max-h-48', 'overflow-y-auto');

            if (result.success && result.data.length > 0) {
                result.data.forEach(client => {
                    const resultItem = document.createElement('div');
                    resultItem.className = 'p-3 hover:bg-gray-100 cursor-pointer';
                    resultItem.textContent = `${client.first_name} ${client.last_name}`;
                    resultItem.addEventListener('click', () => selectClient(client));
                    clientSearchResults.appendChild(resultItem);
                });
            } else {
                clientSearchResults.innerHTML = '<div class="p-3 text-gray-500 italic">No se encontraron clientes.</div>';
            }
        } catch (error) {
            clientSearchResults.innerHTML = '<div class="p-3 text-red-500">Error al cargar.</div>';
        }
    };

    const selectClient = (client) => {
        hiddenClientIdInput.value = client.id;
        selectedClientNameSpan.textContent = `${client.first_name} ${client.last_name}`;
        selectedClientDisplay.classList.remove('hidden');
        clientSearchInput.value = '';
        clientSearchInput.classList.add('hidden');
        clientSearchResults.innerHTML = '';
        clientSearchResults.classList.add('hidden');
    };

    const clearClient = () => {
        hiddenClientIdInput.value = '';
        selectedClientNameSpan.textContent = '';
        selectedClientDisplay.classList.add('hidden');
        clientSearchInput.classList.remove('hidden');
        clientSearchInput.focus();
    };

    clientSearchInput.addEventListener('input', debounce(e => searchClients(e.target.value), 300));
    clearClientBtn.addEventListener('click', clearClient);

    document.getElementById('open-create-complaint-btn').addEventListener('click', () => {
        createComplaintForm.reset();
        clearClient();
        openPanel('createComplaintPanel');
    });

    createComplaintForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        if (!hiddenClientIdInput.value) {
            showToast('Por favor, seleccione un cliente.', 'error');
            return;
        }
        saveComplaintBtn.disabled = true;
        saveComplaintBtn.innerHTML = '<i data-lucide="loader" class="w-4 h-4 mr-2 animate-spin"></i> GUARDANDO...';
        lucide.createIcons();

        const formData = new FormData(createComplaintForm);
        try {
            const response = await fetch(API_CREATE_URL, { method: 'POST', body: formData });
            const result = await response.json();
            if (result.success && result.complaint) {
                complaintsData[result.complaint.id] = result.complaint;
                renderAll(document.getElementById('status-filter').value);
                closePanel('createComplaintPanel');
                showToast('RECLAMO CREADO CON ÉXITO', 'success');
            } else {
                showToast(result.message || 'Error al crear el reclamo.', 'error');
            }
        } catch (error) {
            showToast('Error de conexión al guardar.', 'error');
        } finally {
            saveComplaintBtn.disabled = false;
            saveComplaintBtn.innerHTML = '<i data-lucide="save" class="w-4 h-4 mr-2"></i> Guardar Reclamo';
            lucide.createIcons();
        }
    });

    // --- 5. DETALLES, HISTORIAL Y ACTUALIZACIONES ---
    function openComplaintDetailsPanel(complaintId) {
        currentViewingComplaintId = complaintId;
        const allComplaints = {...complaintsData, ...archivedComplaints.reduce((acc, p) => ({...acc, [p.id]: p}), {})};
        const complaint = allComplaints[complaintId];
        if (!complaint) return;
        
        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>${escapeHtml(complaint.client_name)}</strong>`;
        document.getElementById('view-complaint-description').textContent = complaint.description || 'No hay descripción.';
        
        // Dropdown servicio
        const serviceSelectView = document.getElementById('view-complaint-service-select');
        while (serviceSelectView.options.length > 1) serviceSelectView.remove(1);
        allServices.forEach(service => {
            const option = document.createElement('option');
            option.value = service.id;
            option.textContent = service.name;
            serviceSelectView.appendChild(option);
        });
        serviceSelectView.value = complaint.service_id || '';

        // Tag 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-gray-600'; 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>`;
        
        // Botón Archivar/Reabrir
        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');
    }

    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 result = await response.json(); 
            historyLog.innerHTML = '';
            
            if (result.success && result.data) {
                if (result.data.length === 0) { 
                    historyLog.innerHTML = '<p class="text-gray-500 italic">No hay actualizaciones para este caso.</p>'; 
                    return; 
                }
                
                result.data.forEach(update => {
                    const isInternal = update.type === 'internal_note';
                    const bgColor = isInternal ? 'bg-yellow-100 border-yellow-300' : 'bg-blue-100 border-blue-300';
                    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-gray-600"></i> ${author}
                            </span>
                            <span class="flex items-center gap-2">
                                <span class="text-gray-500">${new Date(update.created_at).toLocaleString()}</span>
                                <button class="delete-update-btn text-red-500 hover:text-red-700 p-0.5 rounded-full" data-id="${update.id}" title="Borrar esta nota">
                                    <i data-lucide="trash-2" class="w-4 h-4" style="pointer-events: none;"></i>
                                </button>
                            </span>
                        </div>
                        <p class="text-gray-800 text-sm whitespace-pre-wrap">${escapeHtml(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'));
    
    // Cambio de Servicio
    async function updateComplaintService(complaintId, newServiceId) {
        const formData = new FormData();
        formData.append('id', complaintId);
        formData.append('service_id', newServiceId || ''); 
        formData.append('action', 'update_service');
        
        const originalComplaint = complaintsData[complaintId] || archivedComplaints.find(c => c.id == complaintId);
        const originalServiceId = originalComplaint?.service_id || '';

        try {
            const response = await fetch(API_UPDATE_URL, { method: 'POST', body: formData });
            const result = await response.json();
            if (result.success && result.complaint) {
                if(complaintsData[complaintId]) complaintsData[complaintId] = result.complaint;
                else {
                    const index = archivedComplaints.findIndex(c => c.id == complaintId);
                    if (index > -1) archivedComplaints[index] = result.complaint;
                }
                showToast('Servicio actualizado', 'success');
                renderAll(document.getElementById('status-filter').value); 
            } else {
                showToast(result.message || 'Error al actualizar', 'error');
                document.getElementById('view-complaint-service-select').value = originalServiceId;
            }
        } catch (error) {
            showToast('Error de conexión.', 'error');
            document.getElementById('view-complaint-service-select').value = originalServiceId;
        }
    }

    document.getElementById('view-complaint-service-select').addEventListener('change', function() {
        if (currentViewingComplaintId) updateComplaintService(currentViewingComplaintId, this.value);
    });

    // --- 6. ACCIONES: ARCHIVAR, REABRIR, BORRAR, DRAG&DROP ---
    
    // Filtro Rápido
    document.getElementById('status-filter').addEventListener('change', function() { renderAll(this.value); });

    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) {
                delete complaintsData[complaintId];
                result.complaint.updated_at = new Date().toISOString(); 
                archivedComplaints.unshift(result.complaint);
                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) {
                archivedComplaints = archivedComplaints.filter(c => c.id != complaintId);
                complaintsData[complaintId] = result.complaint;
                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'); }
    }

    // Drag & Drop
    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) return;

            const originalStatus = complaintsData[complaintId].status;
            complaintsData[complaintId].status = newStatus;
            renderAll(document.getElementById('status-filter').value); 

            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;
                    showToast('ESTADO ACTUALIZADO', 'success');
                } else { 
                    complaintsData[complaintId].status = originalStatus;
                    renderAll(document.getElementById('status-filter').value);
                    showToast(result.message || 'Error al actualizar', 'error'); 
                }
            } catch(error) { 
                complaintsData[complaintId].status = originalStatus;
                renderAll(document.getElementById('status-filter').value);
                showToast('Error de conexión.', 'error'); 
            }
        });
    });

    // --- 7. MODALES DE CONFIRMACIÓN Y BORRADO (ESTANDARIZADO) ---
    
    /**
     * Muestra el modal estandarizado con contenido dinámico.
     * @param {string} dynamicName - El nombre del ítem principal (Reclamo o Nota).
     * @param {function} callback - Función a ejecutar al confirmar.
     * @param {string} actionType - 'delete_complaint' o 'delete_update'.
     */
    function openCustomConfirmModal(dynamicName, callback, actionType) {
        onConfirmDeleteAction = callback;
        currentConfirmActionType = actionType;
        const modal = document.getElementById('confirmDeleteModal');
        
        const actionText = actionType === 'delete_complaint' ? 'ELIMINAR PERMANENTEMENTE EL CASO' : 'BORRAR NOTA';
        const nameDisplay = document.getElementById('confirm-dynamic-name');
        
        // 1. Inyectar contenido dinámico en el SPAN
        nameDisplay.textContent = dynamicName.toUpperCase();
        
        // 2. Ajustar título estático (Pregunta) y botón de acción
        if (actionType === 'delete_complaint') {
             // Pregunta completa inyectada en HTML, JS solo inyecta el nombre
             document.getElementById('confirm-delete-button').innerHTML = '<i data-lucide="trash-2" class="w-5 h-5"></i> ELIMINAR';
        } else if (actionType === 'delete_update') {
             // La pregunta de borrado de nota es simple, solo se inyecta el nombre
             document.querySelector('#confirmDeleteModal .text-lg.font-bold').innerHTML = `¿SEGURO QUE QUIERES ${actionText} ${dynamicName.toUpperCase()}?`;
             document.getElementById('confirm-delete-button').innerHTML = '<i data-lucide="trash-2" class="w-5 h-5"></i> BORRAR';
        }
        
        showModal('confirmDeleteModal');
    }
    
    function closeDeleteModal() {
        hideModal('confirmDeleteModal');
        onConfirmDeleteAction = null;
        currentConfirmActionType = null;
    }
    
    // Asignación de evento de cierre
    document.getElementById('cancel-delete-button').addEventListener('click', closeDeleteModal);
    document.getElementById('confirm-delete-button').addEventListener('click', () => {
        if (typeof onConfirmDeleteAction === 'function') onConfirmDeleteAction();
        closeDeleteModal();
    });

    // Listeners de Borrado (Adaptados a la nueva función estandarizada)
    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) {
            const complaintId = deleteBtn.dataset.id;
            const complaint = archivedComplaints.find(c => c.id == complaintId);
            const complaintTitle = complaint ? complaint.title : 'ESTE RECLAMO';
            openCustomConfirmModal(complaintTitle, () => deleteComplaint(complaintId), 'delete_complaint');
        } else if (reopenBtn) {
            reopenComplaint(reopenBtn.dataset.id);
        }
    });

    document.getElementById('delete-complaint-btn-view').addEventListener('click', () => {
        const complaint = complaintsData[currentViewingComplaintId] || archivedComplaints.find(c => c.id == currentViewingComplaintId);
        const complaintTitle = complaint ? complaint.title : 'ESTE RECLAMO';
        
        closePanel('viewComplaintPanel');
        openCustomConfirmModal(complaintTitle, () => deleteComplaint(currentViewingComplaintId), 'delete_complaint');
    });

    document.getElementById('complaint-history-log').addEventListener('click', async function(e) {
        const deleteBtn = e.target.closest('.delete-update-btn');
        if (deleteBtn) {
            const updateId = deleteBtn.dataset.id;
            const noteTitle = 'ESTA NOTA INTERNA'; 
            
            openCustomConfirmModal(noteTitle, async () => {
                try {
                    const response = await fetch(API_DELETE_UPDATE_URL, {
                        method: 'POST', headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ id: updateId })
                    });
                    const result = await response.json();
                    if (result.success) {
                        showToast('Nota borrada con éxito', 'success');
                        loadComplaintHistory(currentViewingComplaintId);
                    } else showToast(result.message || 'Error al borrar la nota.', 'error');
                } catch (error) { showToast('Error de conexión al borrar.', 'error'); }
            }, 'delete_update');
        }
    });

    async function deleteComplaint(complaintId) {
        if (!complaintId) return;
        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'); }
    }
    
    // --- 8. WHATSAPP Y TRADUCTOR (AJUSTADO A LA NUEVA FUNCIÓN DE MODALES) ---
    const whatsappModal = document.getElementById('whatsappModal');
    const whatsappMessageText = document.getElementById('whatsappMessageText');
    const closeModalBtn = document.getElementById('closeModalBtn');
    const copyAndOpenWhatsAppBtn = document.getElementById('copyAndOpenWhatsAppBtn');
    
    function openWhatsAppModal() {
        showModal('whatsappModal');
    }
    function closeWhatsAppModal() {
        hideModal('whatsappModal');
    }
    
    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\nCon respecto a tu caso: "${complaint.title}", Te informamos lo siguiente:`;
        openWhatsAppModal();
    });
    
    copyAndOpenWhatsAppBtn.addEventListener('click', () => {
        navigator.clipboard.writeText(whatsappMessageText.value).then(() => {
            
            // --- CÓDIGO CORREGIDO: SOLO COPIAR Y CERRAR ---
            const originalBtnText = copyAndOpenWhatsAppBtn.innerHTML;
            copyAndOpenWhatsAppBtn.innerHTML = `<i data-lucide="check" class="w-5 h-5"></i> ¡COPIADO!`;
            lucide.createIcons();
            
            showToast('Mensaje copiado con éxito.', 'success');
            
            setTimeout(() => {
                copyAndOpenWhatsAppBtn.innerHTML = originalBtnText;
                lucide.createIcons();
                closeWhatsAppModal(); // Cierra el modal después de copiar
            }, 1500);
            // --- FIN DEL CÓDIGO CORREGIDO ---

        }).catch(err => showToast('Error al copiar el mensaje.', 'error'));
    });
    closeModalBtn.addEventListener('click', closeWhatsAppModal);
    
    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-english-translator.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) {
            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>
<script src="files/toast.js"></script>
</body>
</html>