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

// CRITICAL FIX: The correct user ID variable from core/init.php is $user_id_session.
// All instances of $userId were replaced with $user_id_session to ensure data loading works.

$active_projects = [];
$archived_projects = [];
$projects_counts = ['activos' => 0, 'en_proceso' => 0, 'completado' => 0];
$clients_for_selector = [];
$services_for_selector = [];

try {
    // 1. CONTEO DE PROYECTOS (Seguro con prepare)
    $stmt_counts = $pdo->prepare("
        SELECT
            SUM(CASE WHEN status NOT IN ('Completado', 'Archivado') THEN 1 ELSE 0 END) as activos,
            SUM(CASE WHEN status = 'En Proceso' THEN 1 ELSE 0 END) as en_proceso,
            SUM(CASE WHEN status = 'Completado' THEN 1 ELSE 0 END) as completado
        FROM projects WHERE user_id = ?
    ");
    $stmt_counts->execute([$user_id_session]);
    $counts = $stmt_counts->fetch(PDO::FETCH_ASSOC);
    
    $projects_counts['activos'] = $counts['activos'] ?? 0;
    $projects_counts['en_proceso'] = $counts['en_proceso'] ?? 0;
    $projects_counts['completado'] = $counts['completado'] ?? 0;

    // Función de mapeo segura
    $mapProjectData = function($row) {
        return [
            'id' => $row['id'],
            'name' => htmlspecialchars($row['name'] ?? '', ENT_QUOTES, 'UTF-8'),
            'description' => htmlspecialchars($row['description'] ?? '', ENT_QUOTES, 'UTF-8'),
            'client_name' => trim(($row['first_name'] ?? 'Cliente') . ' ' . ($row['last_name'] ?? 'Desconocido')),
            'client_id' => $row['client_id'],
            'service_name' => $row['service_name'] ?? 'No asignado',
            'service_id' => $row['service_id'] ?? null,
            'start_date' => $row['start_date'],
            'due_date' => $row['due_date'],
            'status' => $row['status'],
            'updated_at' => $row['updated_at']
        ];
    };

    // 2. PROYECTOS ACTIVOS (Seguro con prepare)
    $stmt_active = $pdo->prepare("
        SELECT p.id, p.name, p.description, p.start_date, p.due_date, p.status, p.updated_at, 
              c.first_name, c.last_name, p.client_id, 
              s.name as service_name, s.id as service_id
        FROM projects p
        LEFT JOIN clients c ON p.client_id = c.id
        LEFT JOIN services s ON p.service_id = s.id
        WHERE p.user_id = ? AND p.status != 'Archivado'
        ORDER BY p.created_at DESC
    ");
    $stmt_active->execute([$user_id_session]);
    $active_projects = array_map($mapProjectData, $stmt_active->fetchAll(PDO::FETCH_ASSOC));
    
    // 3. PROYECTOS ARCHIVADOS (Seguro con prepare)
    $stmt_archived = $pdo->prepare("
        SELECT p.id, p.name, p.description, p.start_date, p.due_date, p.status, p.updated_at, 
              c.first_name, c.last_name, p.client_id, 
              s.name as service_name, s.id as service_id
        FROM projects p
        LEFT JOIN clients c ON p.client_id = c.id
        LEFT JOIN services s ON p.service_id = s.id
        WHERE p.user_id = ? AND p.status = 'Archivado'
        ORDER BY p.updated_at DESC 
    ");
    $stmt_archived->execute([$user_id_session]);
    $archived_projects = array_map($mapProjectData, $stmt_archived->fetchAll(PDO::FETCH_ASSOC));
    
    // 4. SELECTORES (Seguro con prepare)
    $stmt_clients = $pdo->prepare("SELECT id, first_name, last_name FROM clients WHERE user_id = ? ORDER BY first_name ASC");
    $stmt_clients->execute([$user_id_session]);
    $clients_for_selector = $stmt_clients->fetchAll(PDO::FETCH_ASSOC);

    $stmt_services = $pdo->prepare("SELECT id, name FROM services WHERE user_id = ? ORDER BY name ASC");
    $stmt_services->execute([$user_id_session]);
    $services_for_selector = $stmt_services->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    error_log("Error Base de Datos: " . $e->getMessage());
} catch (Exception $e) {
    error_log("Error General: " . $e->getMessage());
}

$active_projects_keyed = [];
foreach ($active_projects as $p) {
    $active_projects_keyed[$p['id']] = $p;
}

$json_flags = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE | JSON_PARTIAL_OUTPUT_ON_ERROR;
$projects_json = json_encode($active_projects_keyed, $json_flags);
$archived_projects_json = json_encode($archived_projects, $json_flags); 
$clients_json_selector = json_encode($clients_for_selector, $json_flags);
$services_json_selector = json_encode($services_for_selector, $json_flags);

if ($projects_json === false) $projects_json = '{}';
if ($archived_projects_json === false) $archived_projects_json = '[]';

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>Centro De Gestión De Proyectos <?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>
    <script src="https://unpkg.com/imask"></script>

    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>
    

</head>
<body data-page-title="Centro De Gestión De Proyectos"
data-page-subtitle="Organiza, Planifica Y Ejecuta Tus Trabajos"
data-page-icon="construction">
    
    <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>
    <div id="task-panel-overlay" class="fixed inset-0 bg-black/60 z-40 hidden transition-opacity duration-300"></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="alarm-clock" class="w-12 h-12 text-[var(--color-secondary)]"></i>
        <div>
            <h3 class="text-lg font-black text-gray-500 mb-1 uppercase">PROYECTOS ACTIVOS</h3>
            <p id="count-activos" class="text-5xl font-bold text-[var(--color-primary)]"><?php echo $projects_counts['activos']; ?></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="waypoints" class="w-12 h-12 text-[var(--color-secondary)]"></i>
        <div>
            <h3 class="text-lg font-black text-gray-500 mb-1 uppercase">EN PROCESO</h3>
            <p id="count-en-proceso" class="text-5xl font-bold text-[var(--color-primary)]"><?php echo $projects_counts['en_proceso']; ?></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-completado" class="text-5xl font-bold text-[var(--color-primary)]"><?php echo $projects_counts['completado']; ?></p>
        </div>
    </div>
    
</div>

            <section id="proyectos" class="dashboard-section">
                <div class="bg-white p-6 rounded-xl shadow-md">
                    <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> TABLERO DE PROYECTOS ACTIVOS</h3><p class="text-gray-500 text-sm mt-1 uppercase">ARRASTRA LAS TARJETAS PARA CAMBIAR EL ESTADO DE TUS PROYECTOS.</p></div>
                        <button class="btn-primary py-2 px-4 rounded-lg flex items-center w-full md:w-auto justify-center uppercase" onclick="openPanel('addProjectPanel')"><i data-lucide="plus" class="w-5 h-5"></i> NUEVO PROYECTO</button>
                    </div>
    <div class="space-y-6">
    <?php $columns = ["top" => ["Aprobado" => "check-square", "En Planificación" => "clipboard-list", "En Proceso" => "tool-case"],"bottom" => ["Listo para Revisión" => "user-star", "Esperando Aprobación" => "hourglass", "Completado" => "folder-check"]];
    foreach ($columns as $row_columns): ?>
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <?php foreach ($row_columns as $name => $icon): $slug = str_replace(' ', '-', strtolower($name)); ?>
        <div class="w-full bg-gray-50 rounded-b-lg">
            <h4 class="text-lg font-extrabold text-white p-3 border-b flex items-center gap-2 uppercase bg-[var(--color-primary)] rounded-t-lg">
                <i data-lucide="<?php echo $icon; ?>" class="w-5 h-5 text-[var(--color-highlight)]"></i>
                <span><?php echo $name; ?></span>
            </h4>
            <div id="column-<?php echo $slug; ?>" class="p-3 space-y-3 min-h-[40vh] project-column" data-status="<?php echo $name; ?>"></div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endforeach; ?>
</div>
                </div>

                <div class="bg-white p-6 rounded-xl shadow-md mt-8">
                    <h3 class="text-2xl font-extrabold text-gray-800 flex items-center gap-2 mb-4"><i data-lucide="list-checks" class="w-7 h-7 text-[var(--color-secondary)]"></i> LISTA DE PROYECTOS EN CURSO</h3>
                    <div class="overflow-x-auto">
                        <table class="min-w-full bg-white"><thead class="bg-gray-50"><tr class="text-left text-gray-500 uppercase text-sm"><th class="py-3 px-6 font-semibold">Proyecto</th><th class="py-3 px-6 font-semibold hidden md:table-cell">Cliente</th><th class="py-3 px-6 font-semibold hidden lg:table-cell">Entrega</th><th class="py-3 px-6 font-semibold text-center">Estado</th></tr></thead>
                            <tbody id="active-projects-table-body" class="text-gray-700 text-sm"></tbody>
                        </table>
                    </div>
                </div>

                <div class="bg-white p-6 rounded-xl shadow-md 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 PROYECTOS TERMINADOS</h3>
                    <div class="overflow-x-auto">
                        <table class="min-w-full bg-white"><thead class="bg-gray-50"><tr class="text-left text-gray-500 uppercase text-sm"><th class="py-3 px-6 font-semibold">Proyecto</th><th class="py-3 px-6 font-semibold hidden md:table-cell">Cliente</th><th class="py-3 px-6 font-semibold hidden lg:table-cell">Fecha de Entrega</th><th class="py-3 px-6 font-semibold text-center">Estado</th><th class="py-3 px-6 font-semibold text-center">Acciones</th></tr></thead>
                            <tbody id="archived-projects-table-body" class="text-gray-700 text-sm"></tbody>
                        </table>
                    </div>
                </div>
            </section>
        </div>
    </main>
</div>

<div id="addProjectPanel" class="fixed top-0 right-0 h-full w-full lg:w-1/3 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="folder-plus" class="w-8 h-8 mr-2 text-white"></i>
                CREAR PROYECTO
            </h3>
            <button onclick="closePanel('addProjectPanel')" 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 class="bg-white p-4 rounded-xl shadow-md transition duration-300">
                
                <div class="border-b pb-3 mb-4">
                    <h4 class="text-2xl font-black text-[var(--color-secondary)] uppercase flex items-center">
                        <i data-lucide="file-plus" class="w-5 h-5 mr-2"></i>
                        DETALLES DEL PROYECTO
                    </h4>
                </div>

                <form id="add-project-form" class="space-y-4">
                    <div>
                        <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Nombre del Proyecto</label>
                        <input type="text" name="name" id="project-name" 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="Ej: Rediseño Web Corporativo" required>
                    </div>

                    <div class="relative">
                        <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Buscar Cliente</label>
                        <input type="text" id="project-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="Escribe para buscar un cliente..." required>
                        <input type="hidden" name="client_id" id="project-client-id">
                        <div id="client-search-results" class="absolute z-10 w-full bg-white border rounded-lg shadow-xl mt-1 max-h-48 overflow-y-auto hidden"></div>
                    </div>

                    <div class="relative">
                        <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Vincular a Servicio</label>
                        <input type="text" id="project-service-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="Escribe para buscar un servicio..." required>
                        <input type="hidden" name="service_id" id="project-service-id">
                        <div id="service-search-results" class="absolute z-10 w-full bg-white border rounded-lg shadow-xl mt-1 max-h-48 overflow-y-auto hidden"></div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Fecha de Inicio</label>
                            <input type="date" name="start_date" id="project-start-date" 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>
                        </div>
                        <div>
                            <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Fecha de Entrega</label>
                            <input type="date" name="due_date" id="project-due-date" 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">
                        </div>
                    </div>

                    <div>
                        <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Descripción</label>
                        <textarea name="description" id="project-description" 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"></textarea>
                    </div>
                </form>
            </div>
        </div>

        <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0 z-10"> 
            <div class="grid grid-cols-2 gap-3">
                <button type="button" class="w-full btn-cancel uppercase flex items-center justify-center gap-2" onclick="closePanel('addProjectPanel')">
                    <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                </button>
                <button type="submit" form="add-project-form" class="w-full btn-confirm uppercase flex items-center justify-center gap-2">
                    <i data-lucide="save" class="w-5 h-5"></i> GUARDAR
                </button>
            </div>
        </div>
    </div>
</div>

<div id="viewProjectPanel" class="fixed top-0 right-0 h-full w-full lg:w-1/3 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="folder-open" class="w-8 h-8 mr-2 text-white"></i>
                FICHA DEL PROYECTO
            </h3>
            <button onclick="closePanel('viewProjectPanel')" 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-project-content" class="bg-white p-4 rounded-xl shadow-md transition duration-300 space-y-6">
                
                <div class="border-b pb-3 text-center">
                    <h2 id="view-project-name" class="text-2xl font-black text-gray-800 uppercase leading-tight"></h2>
                </div>
                
                <div class="space-y-4">
                    <div class="bg-gray-50 p-3 rounded-lg border border-gray-100">
                        <h4 class="text-xs font-bold text-gray-500 mb-2 uppercase flex items-center">
                            <i data-lucide="info" class="w-3 h-3 mr-1"></i> Información General
                        </h4>
                        <div class="space-y-2 pl-1">
                            <p id="view-project-client" class="text-sm font-semibold text-gray-800 flex items-center gap-2"></p>
                            <p id="view-project-service" class="text-sm font-semibold text-gray-800 flex items-center gap-2"></p>
                            <p id="view-project-status" class="text-sm font-semibold text-gray-800 flex items-center gap-2 mt-2"></p>
                        </div>
                    </div>
                    
                    <div class="bg-gray-50 p-3 rounded-lg border border-gray-100">
                        <h4 class="text-xs font-bold text-gray-500 mb-2 uppercase flex items-center">
                            <i data-lucide="calendar" class="w-3 h-3 mr-1"></i> Cronograma
                        </h4>
                        <div class="space-y-2 pl-1">
                            <p id="view-project-start-date" class="text-sm font-semibold text-gray-800 flex items-center gap-2"></p>
                            <p id="view-project-due-date" class="text-sm font-semibold text-gray-800 flex items-center gap-2"></p>
                        </div>
                    </div>

                    <div id="view-project-progress-container" class="hidden bg-blue-50 p-3 rounded-lg border border-blue-100">
                        </div>

                    <div class="bg-gray-50 p-3 rounded-lg border border-gray-100">
                        <h4 class="text-xs font-bold text-gray-500 mb-2 uppercase flex items-center">
                            <i data-lucide="align-left" class="w-3 h-3 mr-1"></i> Descripción
                        </h4>
                        <p id="view-project-description" class="text-sm text-gray-700 whitespace-pre-wrap leading-relaxed pl-1"></p>
                    </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-project-btn-view" type="button" class="w-full btn-confirm uppercase flex items-center justify-center gap-2">
                    <i data-lucide="trash-2" class="w-4 h-4"></i> ELIMINAR
                </button>

                <button type="button" class="w-full btn-cancel uppercase flex items-center justify-center gap-2" onclick="closePanel('viewProjectPanel')">
                    <i data-lucide="x-circle" class="w-5 h-5"></i> CERRAR
                </button>

                <button id="edit-project-btn-view" type="button" class="w-full btn-confirm uppercase flex items-center justify-center gap-2">
                    <i data-lucide="pencil" class="w-5 h-5"></i> EDITAR
                </button>
            </div>
        </div>
    </div>
</div>

<div id="editProjectPanel" class="fixed top-0 right-0 h-full w-full lg:w-1/3 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="folder-cog" class="w-8 h-8 mr-2 text-white"></i>
                EDITAR PROYECTO
            </b>
            <button onclick="closePanel('editProjectPanel')" 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 class="bg-white p-4 rounded-xl shadow-md transition duration-300">
                
                <div class="border-b pb-3 mb-4">
                    <h4 class="text-2xl font-black text-[var(--color-secondary)] uppercase flex items-center">
                        <i data-lucide="edit" class="w-5 h-5 mr-2"></i>
                        MODIFICAR DATOS
                    </h4>
                </div>

                <form id="edit-project-form" class="space-y-4">
                    <input type="hidden" name="id" id="edit-project-id">
                    <input type="hidden" name="action" value="edit_details">

                    <div>
                        <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Nombre del Proyecto</label>
                        <input type="text" name="name" id="edit-project-name" 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>
                    </div>

                    <div class="relative">
                        <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Buscar Cliente</label>
                        <input type="text" id="edit-project-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" required>
                        <input type="hidden" name="client_id" id="edit-project-client-id">
                        <div id="edit-client-search-results" class="absolute z-10 w-full bg-white border rounded-lg shadow-xl mt-1 max-h-48 overflow-y-auto hidden"></div>
                    </div>

                    <div class="relative">
                        <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Vincular a Servicio</label>
                        <input type="text" id="edit-project-service-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" required>
                        <input type="hidden" name="service_id" id="edit-project-service-id">
                        <div id="edit-service-search-results" class="absolute z-10 w-full bg-white border rounded-lg shadow-xl mt-1 max-h-48 overflow-y-auto hidden"></div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Fecha de Inicio</label>
                            <input type="date" name="start_date" id="edit-project-start-date" 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>
                        </div>
                        <div>
                            <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Fecha de Entrega</label>
                            <input type="date" name="due_date" id="edit-project-due-date" 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">
                        </div>
                    </div>

                    <div>
                        <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Descripción</label>
                        <textarea name="description" id="edit-project-description" 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"></textarea>
                    </div>
                </form>
            </div>
        </div>

        <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0 z-10"> 
            <div class="grid grid-cols-2 gap-3">
                <button type="button" class="w-full btn-cancel uppercase flex items-center justify-center gap-2" onclick="closePanel('editProjectPanel')">
                    <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                </button>
                <button type="submit" form="edit-project-form" class="w-full btn-confirm uppercase flex items-center justify-center gap-2">
                    <i data-lucide="save" class="w-5 h-5"></i> GUARDAR CAMBIOS
                </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 modal-dialog">
        <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-3xl font-black mb-4 uppercase">
            <span class="text-[var(--color-primary)]">CONFIRMAR</span> <span class="text-[var(--color-highlight)]">ELIMINACIÓN</span>
        </h3>
        <p class="text-lg text-gray-700 mb-6 uppercase">¿ESTÁS SEGURO DE QUE DESEAS ELIMINAR ESTE <span id="confirm-item-type" class="font-semibold">PROYECTO</span>? 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="btn-secondary w-full sm:w-auto" id="cancel-delete-button"><i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR</button>
            <button type="button" class="btn-primary w-full sm:w-auto" id="confirm-delete-button"><i data-lucide="check-circle" class="w-5 h-5"></i> CONFIRMAR</button>
        </div>
            </div>
</div>

<script>
    // --- GESTIÓN DE PANELES Y NOTIFICACIONES (GLOBAL) ---
    const panelOverlay = document.createElement('div');
    window.showToast = function(message, type = 'info') {
        const toast = document.createElement('div');
        const icon = type === 'success' ? 'check-circle' : 'alert-triangle';
        const colors = type === 'success' ? 'bg-[var(--color-primary)] text-white' : 'bg-[var(--color-secondary)] text-white';
        toast.className = `fixed top-5 right-5 p-4 rounded-lg shadow-lg 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);
    };
    document.addEventListener('DOMContentLoaded', () => {
        panelOverlay.id = 'panel-overlay';
        panelOverlay.className = 'fixed inset-0 bg-gray-900 bg-opacity-75 z-40 hidden';
        document.body.appendChild(panelOverlay);
        panelOverlay.addEventListener('click', () => {
            document.querySelectorAll('.fixed.inset-y-0.right-0').forEach(p => p.classList.add('translate-x-full'));
            panelOverlay.classList.add('hidden');
        });
        document.getElementById('mobile-menu-button')?.addEventListener('click', () => {
            document.getElementById('sidebar')?.classList.toggle('-translate-x-full');
            document.getElementById('sidebar-overlay')?.classList.toggle('hidden');
        });
        document.getElementById('sidebar-overlay')?.addEventListener('click', () => {
            document.getElementById('sidebar')?.classList.add('-translate-x-full');
            document.getElementById('sidebar-overlay')?.classList.add('hidden');
        });
    });
    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'); };

    // --- LÓGICA DE LA PÁGINA DE PROYECTOS ---
    document.addEventListener('DOMContentLoaded', function() {
        // FIX: Evitamos crash con objeto vacío si PHP falla
        let projectsData = <?php echo $projects_json ?: '{}'; ?>;
        let archivedProjects = <?php echo $archived_projects_json ?: '[]'; ?>;
        const clientsData = <?php echo $clients_json_selector ?: '[]'; ?>;
        const servicesData = <?php echo $services_json_selector ?: '[]'; ?>;
        
        let currentViewingProjectId = null;
        let pendingDeletionId = null;

        const API_UPDATE_URL = 'db/projects-update.php';
        const API_CREATE_URL = 'db/projects-create.php';
        const API_DELETE_URL = 'db/projects-delete.php';

        // --- FUNCIÓN HELPER: CÁLCULO DE PROGRESO ---
        // Se usa tanto en las tarjetas del tablero como en el panel de detalle
        function calculateProjectProgress(project) {
            if (!project.due_date || project.status === 'Completado' || project.status === 'Archivado') {
                return null;
            }
            const start = new Date(project.start_date + 'T00:00:00');
            const end = new Date(project.due_date + 'T00:00:00');
            const today = new Date();
            today.setHours(0,0,0,0);

            const totalDuration = end - start;
            const elapsed = today - start;
            const timeRemaining = end - today;
            const daysRemaining = Math.ceil(timeRemaining / (1000 * 60 * 60 * 24));
            
            let percent = 0;
            if (totalDuration > 0) {
                 percent = Math.max(0, Math.min(100, (elapsed / totalDuration) * 100));
            }

            let barColor = 'bg-green-500';
            let textColor = 'text-green-600';
            let statusLabel = daysRemaining >= 0 ? `${daysRemaining} días restantes` : 'ATRASADO';
            let statusIcon = 'timer';

            if (daysRemaining < 0) {
                barColor = 'bg-red-500';
                textColor = 'text-red-600';
                statusLabel = `${Math.abs(daysRemaining)} días de retraso`;
                percent = 100;
                statusIcon = 'alert-octagon';
            } else if (percent > 80 || daysRemaining <= 3) {
                barColor = 'bg-yellow-400';
                textColor = 'text-yellow-600';
                statusIcon = 'alert-triangle';
            }
            
            return {
                percent: Math.round(percent),
                daysRemaining,
                barColor,
                textColor,
                statusLabel,
                statusIcon
            };
        }

        function openProjectDetailsPanel(projectId) {
            currentViewingProjectId = projectId;
            
            let project = projectsData[projectId];
            if (!project) {
                project = archivedProjects.find(p => String(p.id) === String(projectId));
            }
            if (!project) return;
            
            document.getElementById('view-project-name').textContent = project.name; 
            
            document.getElementById('view-project-client').innerHTML = `<i data-lucide="user" class="w-4 h-4 text-gray-500"></i> Cliente: <strong>${project.client_name}</strong>`;
            document.getElementById('view-project-service').innerHTML = `<i data-lucide="briefcase" class="w-4 h-4 text-gray-500"></i> Servicio: <strong>${project.service_name}</strong>`;
            document.getElementById('view-project-status').innerHTML = `<i data-lucide="tag" class="w-4 h-4 text-gray-500"></i> Estado: <strong>${project.status}</strong>`;
            
            const startDate = project.start_date ? new Date(project.start_date+'T00:00:00').toLocaleDateString('es-ES') : 'No definida';
            const dueDate = project.due_date ? new Date(project.due_date+'T00:00:00').toLocaleDateString('es-ES') : 'No definida';
            
            document.getElementById('view-project-start-date').innerHTML = `<i data-lucide="calendar-plus" class="w-4 h-4 text-gray-500"></i> Inicio: <strong>${startDate}</strong>`;
            document.getElementById('view-project-due-date').innerHTML = `<i data-lucide="calendar-check" class="w-4 h-4 text-gray-500"></i> Entrega: <strong>${dueDate}</strong>`;
            
            // --- INYECCIÓN DE PROGRESO EN EL PANEL ---
            const progressContainer = document.getElementById('view-project-progress-container');
            const progressInfo = calculateProjectProgress(project);
            
            if (progressInfo) {
                progressContainer.className = "bg-gray-50 p-4 rounded-lg block shadow-inner"; // Hacemos visible
                progressContainer.innerHTML = `
                     <h4 class="text-sm font-bold text-gray-500 mb-2 uppercase border-b pb-1">Tiempo Restante</h4>
                     <div class="mt-1 pt-2">
                        <div class="flex justify-between items-center mb-1">
                             <span class="text-sm font-bold uppercase ${progressInfo.textColor} flex items-center gap-2">
                                <i data-lucide="${progressInfo.statusIcon}" class="w-4 h-4"></i>
                                ${progressInfo.statusLabel}
                             </span>
                             <span class="text-xs text-gray-400 font-bold">${progressInfo.percent}%</span>
                        </div>
                        <div class="w-full bg-gray-200 rounded-full h-2.5 mt-2">
                            <div class="${progressInfo.barColor} h-2.5 rounded-full transition-all duration-500" style="width: ${progressInfo.percent}%"></div>
                        </div>
                    </div>
                `;
            } else {
                progressContainer.className = "hidden"; // Ocultamos si no aplica
                progressContainer.innerHTML = '';
            }
            // ------------------------------------------

            document.getElementById('view-project-description').textContent = project.description || 'No hay descripción para este proyecto.';
            
            lucide.createIcons();
            openPanel('viewProjectPanel');
        };
        
        function setupSearchableInput(inputId, hiddenId, resultsId, data, nameKey1, nameKey2 = null) {
            const searchInput = document.getElementById(inputId);
            const hiddenInput = document.getElementById(hiddenId);
            const resultsDiv = document.getElementById(resultsId);

            searchInput.addEventListener('input', () => {
                const query = searchInput.value.toLowerCase();
                resultsDiv.innerHTML = '';
                hiddenInput.value = ''; 

                if (query.length < 1) {
                    resultsDiv.classList.add('hidden');
                    return;
                }
                const filtered = data.filter(item => 
                    ((nameKey2 ? `${item[nameKey1]} ${item[nameKey2]}` : item[nameKey1]) || '').toLowerCase().includes(query)
                );
                if (filtered.length > 0) {
                    filtered.forEach(item => {
                        const div = document.createElement('div');
                        div.className = 'p-2 cursor-pointer hover:bg-gray-100 search-result-item';
                        div.textContent = nameKey2 ? `${item[nameKey1]} ${item[nameKey2]}` : item[nameKey1]; 
                        div.dataset.id = item.id;
                        resultsDiv.appendChild(div);
                    });
                    resultsDiv.classList.remove('hidden');
                } else {
                    resultsDiv.classList.add('hidden');
                }
            });

            resultsDiv.addEventListener('mousedown', function(e) {
                if (e.target && e.target.classList.contains('search-result-item')) {
                    const target = e.target;
                    searchInput.value = target.textContent;
                    hiddenInput.value = target.dataset.id;
                    resultsDiv.classList.add('hidden');
                }
            });

            searchInput.addEventListener('blur', () => {
                setTimeout(() => {
                    resultsDiv.classList.add('hidden');
                }, 150);
            });
        }

        setupSearchableInput('project-client-search', 'project-client-id', 'client-search-results', clientsData, 'first_name', 'last_name');
        setupSearchableInput('project-service-search', 'project-service-id', 'service-search-results', servicesData, 'name');
        setupSearchableInput('edit-project-client-search', 'edit-project-client-id', 'edit-client-search-results', clientsData, 'first_name', 'last_name');
        setupSearchableInput('edit-project-service-search', 'edit-project-service-id', 'edit-service-search-results', servicesData, 'name');
        
        const getStatusClass = (status) => {
            const classes = { 'Aprobado': 'bg-[var(--color-secondary)] text-white', 'En Planificación': 'bg-purple-100 text-purple-800', 'En Proceso': 'bg-[var(--color-secondary)] text-white', 'Listo para Revisión': 'bg-[var(--color-highlight)] text-black', 'Esperando Aprobación': 'bg-[var(--color-secondary)] text-white', 'Completado': 'bg-[var(--color-primary)] text-white', 'Archivado': 'bg-gray-100 text-gray-800' };
            return classes[status] || 'bg-gray-100 text-gray-800';
        };

        function renderProjectCard(project) {
            const card = document.createElement('div');
            const statusColors = { 'Aprobado': 'border-[var(--color-secondary)]', 'En Planificación': 'border-purple-500', 'En Proceso': 'border-[var(--color-secondary)]', 'Listo para Revisión': 'border-[var(--color-highlight)]', 'Esperando Aprobación': 'border-[var(--color-secondary)]', 'Completado': 'border-[var(--color-primary)]' };
            card.className = `p-4 bg-white rounded-lg shadow-sm cursor-pointer hover:shadow-lg transition-shadow duration-200 border-l-4 ${statusColors[project.status] || 'border-gray-500'} relative`;
            card.draggable = true; card.dataset.projectId = project.id;
            
            // --- NUEVA LÓGICA VISUAL (Barra en la tarjeta) ---
            const progressInfo = calculateProjectProgress(project);
            let progressBarHtml = '';
            
            if (progressInfo) {
                progressBarHtml = `
                    <div class="mt-3">
                        <div class="flex justify-between items-center mb-1">
                             <span class="text-2xl font-black uppercase ${progressInfo.textColor}">${progressInfo.statusLabel}</span>
                             <span class="text-lg text-gray-400">${progressInfo.percent}%</span>
                        </div>
                        <div class="w-full bg-gray-200 rounded-full h-1.5">
                            <div class="${progressInfo.barColor} h-1.5 rounded-full" style="width: ${progressInfo.percent}%"></div>
                        </div>
                    </div>
                `;
            }

            const dueDate = project.due_date ? new Date(project.due_date + 'T00:00:00') : null;
            const formattedDate = dueDate ? dueDate.toLocaleDateString('es-ES', { day: 'numeric', month: 'short' }) : 'Sin fecha';
            const dateColor = dueDate && new Date() > dueDate ? 'text-red-500' : 'text-gray-500';
            
            card.innerHTML = `
                <h5 class="font-bold text-gray-900 mb-1 leading-tight text-md" data-name></h5>
                <p class="text-md text-gray-500 mb-3 font-medium flex items-center truncate"><i data-lucide="user" class="w-3 h-3 mr-1.5 flex-shrink-0"></i><span data-client-name></span></p>
                <div class="flex justify-between items-center text-xs border-t pt-2 border-gray-100">
                    <span class="font-semibold ${dateColor} flex items-center"><i data-lucide="calendar" class="w-3 h-3 mr-1.5"></i>${formattedDate}</span>
                </div>
                ${progressBarHtml}`;
            
            card.querySelector('[data-name]').textContent = project.name;
            card.querySelector('[data-client-name]').textContent = project.client_name;

            if (project.status === 'Completado') {
                const footer = card.querySelector('.flex.justify-between');
                if (footer) {
                      // Añadimos el botón de archivar al final de la tarjeta
                      const archiveBtn = document.createElement('button');
                      archiveBtn.className = 'archive-btn btn-primary font-bold text-[10px] py-1 px-2 rounded-md flex items-center gap-1 transition';
                      archiveBtn.innerHTML = `<i data-lucide="archive" class="w-3 h-3"></i>ARCHIVAR`;
                      footer.appendChild(archiveBtn);
                }
            }
            
            card.addEventListener('click', (e) => {
                if (!e.target.closest('.archive-btn')) {
                    openProjectDetailsPanel(project.id);
                }
            });
            card.querySelector('.archive-btn')?.addEventListener('click', (e) => { e.stopPropagation(); archiveProject(project.id); });
            card.addEventListener('dragstart', e => { if (e.target.tagName !== 'BUTTON') { e.dataTransfer.setData('text/plain', project.id); setTimeout(() => card.classList.add('opacity-50'), 0); } else { e.preventDefault(); } });
            card.addEventListener('dragend', () => card.classList.remove('opacity-50'));
            lucide.createIcons();
            return card;
        }

        async function archiveProject(projectId) {
            const projectToArchive = projectsData[projectId]; if (!projectToArchive) return;
            const formData = new FormData();
            formData.append('id', projectId);
            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.project) {
                    delete projectsData[projectId];
                    archivedProjects.unshift(result.project);
                    renderAll(); 
                    showToast('Proyecto archivado con éxito', 'success');
                } else { 
                    showToast(result.message || 'Error al archivar', 'error'); 
                }
            } catch(error) { 
                showToast('Error de conexión al archivar.', 'error'); 
            }
        }

        function renderTable(tableBodyId, projects) {
            const tableBody = document.getElementById(tableBodyId);
            tableBody.innerHTML = '';
            const isArchivedTable = tableBodyId === 'archived-projects-table-body';
            const message = isArchivedTable ? 'No hay proyectos archivados.' : 'No hay proyectos activos.';
            if (projects.length === 0) {
                tableBody.innerHTML = `<tr><td colspan="${isArchivedTable ? '5' : '4'}" class="text-center py-6 text-gray-500 italic">${message}</td></tr>`;
                return;
            }
            projects.forEach(p => {
                const statusClass = getStatusClass(p.status);
                const row = document.createElement('tr');
                row.className = 'border-b border-gray-200 hover:bg-gray-50 cursor-pointer'; // Añadir cursor pointer para indicar clic
                row.onclick = () => openProjectDetailsPanel(p.id);

                row.innerHTML = `
                    <td class="py-4 px-6 font-medium text-gray-900"></td>
                    <td class="py-4 px-6 hidden md:table-cell"></td>
                    <td class="py-4 px-6 hidden lg:table-cell">${p.due_date ? new Date(p.due_date+'T00:00:00').toLocaleDateString('es-ES') : 'N/A'}</td>
                    <td class="py-4 px-6 text-center"><span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-bold uppercase ${statusClass}">${p.status}</span></td>
                `;
                
                row.cells[0].textContent = p.name;
                row.cells[1].textContent = p.client_name;

                if (isArchivedTable) {
                    // Reemplazamos el botón por un div con el botón dentro para evitar que el clic de la fila lo active
                    const actionCell = document.createElement('td');
                    actionCell.className = 'py-4 px-6 text-center';
                    // Utilizamos la clase primaria para el botón eliminar (Rojo Vino)
                    actionCell.innerHTML = `<button class="delete-project-btn btn-primary p-2 rounded-lg" data-project-id="${p.id}" title="Eliminar Permanentemente"><i data-lucide="trash-2" class="w-5 h-5"></i></button>`;
                    row.appendChild(actionCell);
                    row.onclick = null; // Removemos el click de la fila en la tabla de archivados si hay acción
                } else {
                    row.cells[3].style.cursor = 'pointer'; // Mantener el indicador de clic en filas activas
                }
                tableBody.appendChild(row);
            });
            // Adjuntar evento a los botones de eliminar después de la renderización
            tableBody.querySelectorAll('.delete-project-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    e.stopPropagation(); // Evita que el evento de clic de la fila se dispare
                    openDeleteModal(e.currentTarget.dataset.projectId);
                });
            });

            lucide.createIcons();
        }
        
        function renderAll() {
            renderBoard();
            renderActiveTable();
            renderArchivedTable();
            updateCounts();
        }
        const renderActiveTable = () => renderTable('active-projects-table-body', Object.values(projectsData));
        const renderArchivedTable = () => renderTable('archived-projects-table-body', archivedProjects);

        function updateCounts() {
            let activos = 0, en_proceso = 0, completado = 0;
            Object.values(projectsData).forEach(p => {
                if (p.status !== 'Completado' && p.status !== 'Archivado') activos++;
                if (p.status === 'En Proceso') en_proceso++;
                if (p.status === 'Completado') completado++;
            });
            document.getElementById('count-activos').textContent = activos;
            document.getElementById('count-en-proceso').textContent = en_proceso;
            document.getElementById('count-completado').textContent = completado;
        }

        function renderBoard() {
            document.querySelectorAll('.project-column').forEach(col => col.innerHTML = '');
            Object.values(projectsData).forEach(project => {
                const slug = project.status.replace(/ /g, '-').toLowerCase();
                const column = document.getElementById(`column-${slug}`);
                if (column) {
                    column.appendChild(renderProjectCard(project));
                }
            });
            lucide.createIcons();
        }

        document.querySelectorAll('.project-column').forEach(column => {
            column.addEventListener('dragover', e => e.preventDefault());
            column.addEventListener('drop', async (e) => {
                e.preventDefault();
                const projectId = e.dataTransfer.getData('text/plain');
                const newStatus = column.dataset.status;
                if (projectsData[projectId] && projectsData[projectId].status !== newStatus) {
                    const formData = new FormData();
                    formData.append('id', projectId);
                    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.project) {
                            projectsData[projectId] = result.project;
                            renderAll();
                            showToast('Estado actualizado', 'success');
                        } else { 
                            showToast(result.message || 'Error al actualizar', 'error'); 
                        }
                    } catch(error) { 
                        showToast('Error de conexión.', 'error'); 
                    }
                }
            });
        });

        document.getElementById('add-project-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            const form = e.target;
            const formData = new FormData(form);

            if (!formData.get('client_id') || !formData.get('service_id')) {
                showToast('Debes seleccionar un cliente y un servicio de la lista.', 'error');
                return;
            }
            try {
                const response = await fetch(API_CREATE_URL, { method: 'POST', body: formData });
                const result = await response.json();
                if (result.success && result.project) {
                    projectsData[result.project.id] = result.project;
                    renderAll();
                    closePanel('addProjectPanel');
                    form.reset();
                    showToast('Proyecto creado con éxito', 'success');
                } else {
                    showToast(result.message || 'Error al crear proyecto.', 'error');
                }
            } catch (error) {
                showToast('Error de conexión al crear el proyecto.', 'error');
            }
        });
        
        document.getElementById('edit-project-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            const form = e.target;
            const formData = new FormData(form);
            const projectId = formData.get('id');

            if (!formData.get('client_id') || !formData.get('service_id')) {
                showToast('Debes seleccionar un cliente y un servicio de la lista.', 'error');
                return;
            }
            try {
                const response = await fetch(API_UPDATE_URL, { method: 'POST', body: formData });
                const result = await response.json();
                if (result.success && result.project) {
                    projectsData[projectId] = result.project;
                    renderAll();
                    closePanel('editProjectPanel');
                    showToast('Proyecto actualizado con éxito', 'success');
                } else {
                    showToast(result.message || 'Error al actualizar proyecto.', 'error');
                }
            } catch (error) {
                showToast('Error de conexión al actualizar.', 'error');
            }
        });

        function openEditPanel() {
            if (!currentViewingProjectId) return;
            const project = projectsData[currentViewingProjectId] || archivedProjects.find(p => String(p.id) === String(currentViewingProjectId));
            if (!project) return;

            document.getElementById('edit-project-id').value = project.id;
            document.getElementById('edit-project-name').value = project.name;
            document.getElementById('edit-project-description').value = project.description || '';
            document.getElementById('edit-project-start-date').value = project.start_date;
            document.getElementById('edit-project-due-date').value = project.due_date;
            
            document.getElementById('edit-project-client-search').value = project.client_name;
            document.getElementById('edit-project-client-id').value = project.client_id;
            document.getElementById('edit-project-service-search').value = project.service_name;
            document.getElementById('edit-project-service-id').value = project.service_id;

            closePanel('viewProjectPanel');
            openPanel('editProjectPanel');
        }

        document.getElementById('edit-project-btn-view').addEventListener('click', openEditPanel);

        function openDeleteModal(projectId) {
            pendingDeletionId = projectId;
            const modal = document.getElementById('confirmDeleteModal');
            modal.classList.remove('hidden');
            const modalInner = modal.querySelector('div');
            modalInner.classList.remove('scale-95', 'opacity-0');
            modalInner.classList.add('scale-100', 'opacity-100');
        }

        function closeDeleteModal() {
            const modal = document.getElementById('confirmDeleteModal');
            const modalInner = modal.querySelector('div');
            modalInner.classList.remove('scale-100', 'opacity-100');
            modalInner.classList.add('scale-95', 'opacity-0');
            setTimeout(() => { modal.classList.add('hidden'); }, 300);
        }

        document.getElementById('delete-project-btn-view').addEventListener('click', () => {
             if (currentViewingProjectId) {
                openDeleteModal(currentViewingProjectId);
             }
        });

        document.getElementById('archived-projects-table-body').addEventListener('click', function(e) {
            const button = e.target.closest('.delete-project-btn');
            if (button) {
                const projectId = button.dataset.projectId;
                openDeleteModal(projectId);
            }
        });

        document.getElementById('cancel-delete-button').addEventListener('click', closeDeleteModal);
        document.getElementById('confirm-delete-button').addEventListener('click', () => {
            if (pendingDeletionId) {
                deleteProject(pendingDeletionId);
                closePanel('viewProjectPanel'); // Forzamos el cierre del panel de vista si estaba abierto
                closeDeleteModal();
            }
        });
        
        async function deleteProject(projectId) {
            try {
                const response = await fetch(API_DELETE_URL, { 
                    method: 'POST', 
                    headers: { 'Content-Type': 'application/json' }, 
                    body: JSON.stringify({ id: projectId }) 
                });
                const result = await response.json();
                if (result.success) {
                    if (projectsData[projectId]) {
                        delete projectsData[projectId];
                    }
                    archivedProjects = archivedProjects.filter(p => String(p.id) !== String(projectId));
                    
                    renderAll();
                    closePanel('viewProjectPanel');
                    showToast('Proyecto eliminado con éxito', 'success');
                } else { 
                    showToast(result.message || 'Error al eliminar.', 'error'); 
                }
            } catch (error) { 
                showToast('Error de conexión.', 'error'); 
            }
        }

        renderAll();
    });
</script>
<script src="files/toast.js"></script>
</body>
</html>