<?php
require_once __DIR__ . '/../../config/bootstrap.php';
require_once __DIR__ . '/../../includes/require-auth.php';

use App\Services\AuthService;
use App\Services\TemplateService;
use App\Services\SecurityService;

$auth = new AuthService();
$templateService = new TemplateService();
$security = new SecurityService();

$user = requireAuth($auth);
$rol = $user['rol'] ?? 'asesor';

// Verificar permisos
$esAdmin = ($rol === 'administrador');

// Obtener plantillas y estadísticas
// Administradores ven todas (incluyendo inactivas), asesores solo activas
$templates = $esAdmin ? $templateService->listAll() : $templateService->list();
$stats = $templateService->getStats();
$categories = $templateService->getCategories();

$csrfToken = $security->generateCSRFToken();
?>
<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestión de Plantillas - Sistema de Contratos</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>

    <!-- TinyMCE Editor -->
    <script src="https://cdn.jsdelivr.net/npm/tinymce@7.0.1/tinymce.min.js"></script>

    <style>
        * {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", "Helvetica Neue", Arial, sans-serif;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            letter-spacing: -0.011em;
        }

        .tox-tinymce {
            border-radius: 0.5rem !important;
            border-color: #d1d5db !important;
        }

        .tox .tox-toolbar,
        .tox .tox-toolbar__overflow,
        .tox .tox-toolbar__primary {
            background: #f9fafb !important;
        }

        /* Estilos para contenido readonly en modal */
        #template-contenido-readonly {
            line-height: 1.6;
        }

        #template-contenido-readonly h1,
        #template-contenido-readonly h2,
        #template-contenido-readonly h3 {
            font-weight: 600;
            margin-top: 1rem;
            margin-bottom: 0.5rem;
        }

        #template-contenido-readonly h1 { font-size: 1.5rem; }
        #template-contenido-readonly h2 { font-size: 1.25rem; }
        #template-contenido-readonly h3 { font-size: 1.125rem; }

        #template-contenido-readonly p {
            margin-bottom: 0.75rem;
        }

        #template-contenido-readonly ul,
        #template-contenido-readonly ol {
            margin-left: 1.5rem;
            margin-bottom: 0.75rem;
        }

        #template-contenido-readonly ul { list-style-type: disc; }
        #template-contenido-readonly ol { list-style-type: decimal; }

        #template-contenido-readonly strong {
            font-weight: 600;
        }

        #template-contenido-readonly img {
            max-width: 100%;
            height: auto;
            margin: 1rem 0;
            border-radius: 0.375rem;
        }
    </style>
</head>

<body class="bg-gray-50 flex flex-col min-h-screen">
    <?php include __DIR__ . '/../../includes/admin-nav.php'; ?>

    <main class="flex-1 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 w-full">
        <div class="mb-6 flex items-center justify-between">
            <div>
                <h1 class="text-2xl font-bold text-gray-900">Librería de Plantillas</h1>
                <p class="text-sm text-gray-500 mt-1">
                    <?= $esAdmin ? 'Gestiona plantillas reutilizables de contratos' : 'Crea y utiliza plantillas predefinidas en tus contratos' ?>
                </p>
            </div>
            <!-- ✅ Asesores también pueden crear plantillas -->
            <button onclick="openCreateModal()" class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors">
                <svg class="w-5 h-5 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                </svg>
                Nueva Plantilla
            </button>
        </div>

        <!-- Estadísticas -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="flex-shrink-0 bg-indigo-100 rounded-lg p-3">
                        <svg class="w-6 h-6 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                        </svg>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-500">Total</p>
                        <p class="text-2xl font-bold text-gray-900"><?= $stats['total'] ?></p>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="flex-shrink-0 bg-green-100 rounded-lg p-3">
                        <svg class="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-500">Activas</p>
                        <p class="text-2xl font-bold text-gray-900"><?= $stats['activas'] ?></p>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="flex-shrink-0 bg-gray-100 rounded-lg p-3">
                        <svg class="w-6 h-6 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"></path>
                        </svg>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-500">Inactivas</p>
                        <p class="text-2xl font-bold text-gray-900"><?= $stats['inactivas'] ?></p>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="flex-shrink-0 bg-blue-100 rounded-lg p-3">
                        <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"></path>
                        </svg>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-500">Usos Totales</p>
                        <p class="text-2xl font-bold text-gray-900"><?= $stats['total_usos'] ?></p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Lista de Plantillas -->
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-semibold text-gray-900">Todas las Plantillas</h2>
            </div>

            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nombre</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Categoría</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Usos</th>
                            <?php if ($esAdmin): ?>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Estado</th>
                            <?php endif; ?>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Fecha</th>
                            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Acciones</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php if (empty($templates)): ?>
                            <tr>
                                <td colspan="<?= $esAdmin ? '6' : '5' ?>" class="px-6 py-12 text-center text-gray-500">
                                    <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                                    </svg>
                                    <p class="mt-2 text-sm">No hay plantillas disponibles</p>
                                    <!-- ✅ Asesores también pueden crear plantillas -->
                                    <button onclick="openCreateModal()" class="mt-4 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700">
                                        Crear Primera Plantilla
                                    </button>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($templates as $template): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-6 py-4">
                                        <div class="text-sm font-medium text-gray-900"><?= htmlspecialchars($template['nombre']) ?></div>
                                        <?php if ($template['descripcion']): ?>
                                            <div class="text-sm text-gray-500"><?= htmlspecialchars(substr($template['descripcion'], 0, 60)) ?><?= strlen($template['descripcion']) > 60 ? '...' : '' ?></div>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <span class="px-2 py-1 text-xs font-medium rounded-full bg-indigo-100 text-indigo-800">
                                            <?= htmlspecialchars(ucfirst($template['categoria'])) ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                        <?= (int)$template['uso_count'] ?>
                                    </td>
                                    <?php if ($esAdmin): ?>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <?php if ($template['activo']): ?>
                                            <span class="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">Activa</span>
                                        <?php else: ?>
                                            <span class="px-2 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-800">Inactiva</span>
                                        <?php endif; ?>
                                    </td>
                                    <?php endif; ?>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                        <?= date('d/m/Y', strtotime($template['created_at'])) ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                        <button onclick='viewTemplate(<?= json_encode($template) ?>)' class="text-indigo-600 hover:text-indigo-900 mr-3">
                                            Ver
                                        </button>
                                        <!-- ✅ Asesores pueden editar plantillas -->
                                        <button onclick='editTemplate(<?= json_encode($template) ?>)' class="text-indigo-600 hover:text-indigo-900 mr-3">
                                            Editar
                                        </button>
                                        <!-- ⚠️ Solo administradores pueden activar/desactivar y eliminar -->
                                        <?php if ($esAdmin): ?>
                                        <button onclick="toggleTemplate(<?= $template['id'] ?>, <?= $template['activo'] ? 'false' : 'true' ?>)" class="text-gray-600 hover:text-gray-900 mr-3">
                                            <?= $template['activo'] ? 'Desactivar' : 'Activar' ?>
                                        </button>
                                        <button onclick="deleteTemplate(<?= $template['id'] ?>, '<?= htmlspecialchars($template['nombre']) ?>')" class="text-red-600 hover:text-red-900">
                                            Eliminar
                                        </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>

    <!-- Modal Crear/Editar Plantilla -->
    <div id="template-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
        <div class="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-y-auto">
            <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between sticky top-0 bg-white">
                <h3 id="modal-title" class="text-lg font-semibold text-gray-900">Nueva Plantilla</h3>
                <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                </button>
            </div>

            <form id="template-form" class="p-6 space-y-4">
                <input type="hidden" id="template-id" value="">
                <input type="hidden" id="template-mode" value="edit">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Nombre de la Plantilla *</label>
                    <input type="text" id="template-nombre" required class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Descripción</label>
                    <textarea id="template-descripcion" rows="2" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500" placeholder="Breve descripción de la plantilla (opcional)"></textarea>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Categoría</label>
                    <select id="template-categoria" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500 bg-white">
                        <option value="general">General</option>
                        <option value="servicios">Servicios</option>
                        <option value="confidencialidad">Confidencialidad</option>
                        <option value="arrendamiento">Arrendamiento</option>
                        <option value="compraventa">Compraventa</option>
                        <option value="laboral">Laboral</option>
                    </select>
                </div>

                <div>
                    <div class="flex items-center justify-between mb-2">
                        <label class="block text-sm font-medium text-gray-700">Contenido de la Plantilla *</label>
                        <label id="upload-btn"
                            class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-indigo-700 bg-indigo-50 border border-indigo-200 rounded-lg cursor-pointer hover:bg-indigo-100 transition-colors"
                            title="Sube un archivo TXT, DOCX, PDF o RTF y su contenido se cargará en el editor">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
                            </svg>
                            Importar desde archivo
                            <input type="file" id="file-import" accept=".txt,.pdf,.docx,.doc,.rtf"
                                class="hidden" onchange="importFile(this)">
                        </label>
                    </div>

                    <!-- Indicador de carga del archivo -->
                    <div id="import-status" class="hidden mb-2 px-3 py-2 rounded-lg text-sm"></div>

                    <div id="template-contenido-readonly" class="hidden w-full px-4 py-2 border rounded-lg bg-gray-50 max-h-96 overflow-y-auto"></div>
                    <textarea id="template-contenido" name="contenido"></textarea>
                    <p class="mt-2 text-xs text-gray-500">Usa la barra de herramientas para dar formato. También puedes importar archivos DOCX, PDF, TXT o RTF.</p>
                </div>

                <div class="flex justify-end gap-3 pt-4">
                    <button type="button" onclick="closeModal()" class="px-6 py-2 border rounded-lg hover:bg-gray-50">Cerrar</button>
                    <button type="submit" id="template-save-btn" class="px-6 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700">Guardar</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Inicializar TinyMCE
        let editorInitialized = false;

        function initEditor() {
            if (editorInitialized) return;

            tinymce.init({
                selector: '#template-contenido',
                height: 400,
                license_key: 'gpl',
                language: 'es',
                menubar: 'edit view insert format',
                plugins: 'anchor autolink charmap link lists searchreplace visualblocks wordcount code fullscreen image',
                toolbar: 'undo redo | blocks fontsize | bold italic underline | link image | numlist bullist | removeformat code fullscreen',
                content_style: 'body { font-family: Inter, Georgia, serif; font-size: 14px; line-height: 1.7; padding: 15px; }',
                font_size_formats: '8pt 10pt 12pt 14pt 16pt 18pt 24pt 36pt',
                block_formats: 'Párrafo=p; Título 1=h1; Título 2=h2; Título 3=h3',
                images_upload_handler: function(blobInfo, progress) {
                    return new Promise(function(resolve, reject) {
                        const reader = new FileReader();
                        reader.onloadend = function() {
                            resolve(reader.result);
                        };
                        reader.onerror = reject;
                        reader.readAsDataURL(blobInfo.blob());
                    });
                },
                paste_data_images: true,
                automatic_uploads: true,
                branding: false,
                promotion: false
            });

            editorInitialized = true;
        }

        const esAdmin = <?= json_encode($esAdmin) ?>;

        function openCreateModal() {
            document.getElementById('modal-title').textContent = 'Nueva Plantilla';
            document.getElementById('template-id').value = '';
            document.getElementById('template-mode').value = 'create';
            document.getElementById('template-form').reset();
            setModalEditable(true);
            document.getElementById('template-modal').classList.remove('hidden');
            initEditor();
            if (tinymce.get('template-contenido')) {
                tinymce.get('template-contenido').setContent('');
            }
        }

        function viewTemplate(template) {
            document.getElementById('modal-title').textContent = 'Vista Previa: ' + template.nombre;
            document.getElementById('template-id').value = template.id;
            document.getElementById('template-mode').value = 'view';
            document.getElementById('template-nombre').value = template.nombre;
            document.getElementById('template-descripcion').value = template.descripcion || '';
            document.getElementById('template-categoria').value = template.categoria;

            // Modo solo lectura
            setModalEditable(false);

            // Mostrar contenido como HTML (sin editor)
            document.getElementById('template-contenido-readonly').innerHTML = template.contenido;
            document.getElementById('template-contenido-readonly').classList.remove('hidden');
            if (tinymce.get('template-contenido')) {
                tinymce.get('template-contenido').getContainer().style.display = 'none';
            }

            document.getElementById('template-modal').classList.remove('hidden');
        }

        function editTemplate(template) {
            document.getElementById('modal-title').textContent = 'Editar Plantilla';
            document.getElementById('template-id').value = template.id;
            document.getElementById('template-mode').value = 'edit';
            document.getElementById('template-nombre').value = template.nombre;
            document.getElementById('template-descripcion').value = template.descripcion || '';
            document.getElementById('template-categoria').value = template.categoria;

            setModalEditable(true);
            document.getElementById('template-modal').classList.remove('hidden');
            initEditor();
            setTimeout(() => {
                if (tinymce.get('template-contenido')) {
                    tinymce.get('template-contenido').setContent(template.contenido);
                }
            }, 100);
        }

        function setModalEditable(editable) {
            document.getElementById('template-nombre').disabled = !editable;
            document.getElementById('template-descripcion').disabled = !editable;
            document.getElementById('template-categoria').disabled = !editable;
            document.getElementById('template-save-btn').style.display = editable ? 'block' : 'none';

            if (!editable) {
                document.getElementById('template-contenido-readonly').classList.remove('hidden');
                if (tinymce.get('template-contenido')) {
                    tinymce.get('template-contenido').getContainer().style.display = 'none';
                }
            } else {
                document.getElementById('template-contenido-readonly').classList.add('hidden');
                if (tinymce.get('template-contenido')) {
                    tinymce.get('template-contenido').getContainer().style.display = 'block';
                }
            }
        }

        function closeModal() {
            document.getElementById('template-modal').classList.add('hidden');
        }

        // Guardar plantilla
        document.getElementById('template-form').addEventListener('submit', async function(e) {
            e.preventDefault();

            const mode = document.getElementById('template-mode').value;
            if (mode === 'view') {
                closeModal();
                return;
            }

            const templateId = document.getElementById('template-id').value;
            const nombre = document.getElementById('template-nombre').value.trim();
            const descripcion = document.getElementById('template-descripcion').value.trim();
            const categoria = document.getElementById('template-categoria').value;
            const contenido = tinymce.get('template-contenido').getContent();

            if (!nombre || !contenido) {
                alert('Por favor, completa todos los campos obligatorios.');
                return;
            }

            const formData = new FormData();
            formData.append('nombre', nombre);
            formData.append('descripcion', descripcion);
            formData.append('categoria', categoria);
            formData.append('contenido', contenido);
            formData.append('csrf_token', document.querySelector('input[name="csrf_token"]').value);

            if (templateId) {
                formData.append('id', templateId);
            }

            try {
                const url = templateId ? 'api/update-template.php' : 'api/create-template.php';
                const res = await fetch(url, {
                    method: 'POST',
                    body: formData
                });
                const data = await res.json();

                if (data.success) {
                    alert(data.message);
                    window.location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            } catch (err) {
                alert('Error al guardar la plantilla.');
                console.error(err);
            }
        });

        async function toggleTemplate(id, activate) {
            if (!confirm(`¿Estás seguro de ${activate ? 'activar' : 'desactivar'} esta plantilla?`)) {
                return;
            }

            try {
                const formData = new FormData();
                formData.append('id', id);
                formData.append('activo', activate ? '1' : '0');

                const res = await fetch('api/update-template.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await res.json();

                if (data.success) {
                    window.location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            } catch (err) {
                alert('Error al actualizar la plantilla.');
                console.error(err);
            }
        }

        async function deleteTemplate(id, nombre) {
            if (!confirm(`¿Estás seguro de eliminar la plantilla "${nombre}"?\n\nEsta acción no se puede deshacer.`)) {
                return;
            }

            try {
                const res = await fetch(`api/delete-template.php?id=${id}`, {
                    method: 'DELETE'
                });
                const data = await res.json();

                if (data.success) {
                    alert(data.message);
                    window.location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            } catch (err) {
                alert('Error al eliminar la plantilla.');
                console.error(err);
            }
        }

        // ── Importar archivo ──────────────────────────────────────────────────
        async function importFile(input) {
            const file = input.files[0];
            if (!file) return;

            const status = document.getElementById('import-status');
            const btn = document.getElementById('upload-btn');
            const maxSize = 5 * 1024 * 1024; // 5MB

            if (file.size > maxSize) {
                status.className = 'mb-2 px-3 py-2 rounded-lg text-sm bg-red-50 text-red-700 border border-red-200';
                status.textContent = 'El archivo es demasiado grande. Máximo 5MB.';
                status.classList.remove('hidden');
                input.value = '';
                return;
            }

            // Verificar que TinyMCE esté listo
            if (!tinymce.get('template-contenido')) {
                status.className = 'mb-2 px-3 py-2 rounded-lg text-sm bg-yellow-50 text-yellow-700 border border-yellow-200';
                status.textContent = 'El editor aún se está cargando. Por favor, espera un momento.';
                status.classList.remove('hidden');
                input.value = '';
                return;
            }

            // Confirmar si ya hay contenido
            const currentContent = tinymce.get('template-contenido').getContent({format: 'text'}).trim();
            if (currentContent.length > 10) {
                if (!confirm('Ya hay contenido en el editor. ¿Deseas reemplazarlo con el archivo seleccionado?')) {
                    input.value = '';
                    return;
                }
            }

            status.className = 'mb-2 px-3 py-2 rounded-lg text-sm bg-blue-50 text-blue-700 border border-blue-200';
            status.textContent = `Procesando ${file.name}...`;
            status.classList.remove('hidden');
            btn.classList.add('opacity-50', 'pointer-events-none');

            const formData = new FormData();
            formData.append('archivo', file);

            try {
                const res = await fetch('api/extract-contract.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await res.json();

                if (data.success) {
                    tinymce.get('template-contenido').setContent(data.html);

                    status.className = 'mb-2 px-3 py-2 rounded-lg text-sm bg-green-50 text-green-700 border border-green-200';
                    status.textContent = `✓ Archivo importado correctamente: ${file.name}`;

                    setTimeout(() => {
                        status.classList.add('hidden');
                    }, 4000);
                } else {
                    status.className = 'mb-2 px-3 py-2 rounded-lg text-sm bg-red-50 text-red-700 border border-red-200';
                    status.textContent = data.message || 'Error al procesar el archivo.';
                }
            } catch (err) {
                status.className = 'mb-2 px-3 py-2 rounded-lg text-sm bg-red-50 text-red-700 border border-red-200';
                status.textContent = 'Error al comunicarse con el servidor.';
                console.error(err);
            } finally {
                btn.classList.remove('opacity-50', 'pointer-events-none');
                input.value = '';
            }
        }
    </script>

    <?php include __DIR__ . '/../../includes/admin-footer.php'; ?>
</body>

</html>
