// 📌 Declaramos las variables globales para que sean accesibles en todo el script
let imagePreviewContainer, previewImage, videoPreviewContainer, previewVideo;
let textPreviewContainer, previewText, pdfPreviewContainer, previewPdfCanvas;

document.addEventListener("DOMContentLoaded", () => {
    console.log("✅ previews.js cargado correctamente");

    // 📌 Asignamos los elementos del DOM a las variables globales
    imagePreviewContainer = document.getElementById('image-preview');
    previewImage = document.getElementById('preview-image');
    videoPreviewContainer = document.getElementById('video-preview');
    previewVideo = document.querySelector('#video-preview video'); // 📌 Asegurar que apunta al video
    textPreviewContainer = document.getElementById('text-preview');
    previewText = document.getElementById('preview-text');
    pdfPreviewContainer = document.getElementById('pdf-preview');
    previewPdfCanvas = document.getElementById('preview-pdf-canvas');

    console.log("🎯 Elementos obtenidos:");
    console.log("🖼️ imagePreviewContainer:", imagePreviewContainer);
    console.log("📹 videoPreviewContainer:", videoPreviewContainer);
    console.log("📜 textPreviewContainer:", textPreviewContainer);
    console.log("📄 pdfPreviewContainer:", pdfPreviewContainer);
});

// 📌 Delegación de eventos para manejar las previsualizaciones
document.body.addEventListener('mouseover', (event) => {
    const button = event.target.closest('.view-btn');
    if (!button) return;

    const mediaUrl = button.getAttribute('data-url');
    const contentType = button.getAttribute('data-type');

    console.log("🖱️ Hover en botón:", button);
    console.log("📄 URL:", mediaUrl);
    console.log("📂 Tipo de contenido:", contentType);

    if (!mediaUrl) {
        console.warn("❌ data-url es NULL o vacío.");
        return;
    }

    // 📌 Obtener la posición del botón
    let rect = button.getBoundingClientRect();

    // 📌 Mostrar previsualización de imagen
    if (contentType.startsWith('image/')) {
        console.log("🖼️ Mostrando imagen...");
        previewImage.src = mediaUrl;
        imagePreviewContainer.classList.remove('d-none');

        imagePreviewContainer.style.position = "absolute";
        imagePreviewContainer.style.top = `${rect.top + window.scrollY}px`;
        imagePreviewContainer.style.left = `${rect.left + window.scrollX + rect.width + 10}px`;

        imagePreviewContainer.style.width = "160px";
        imagePreviewContainer.style.height = "90px";

    // 📌 Mostrar previsualización de video
    } else if (contentType.startsWith('video/')) {
        console.log("🎥 Mostrando video...");

        previewVideo.src = "";
        setTimeout(() => {
            previewVideo.src = mediaUrl;
            previewVideo.load();
            previewVideo.play();
        }, 50);

        videoPreviewContainer.classList.remove('d-none');
        videoPreviewContainer.style.display = "block";

        videoPreviewContainer.style.position = "absolute";
        videoPreviewContainer.style.top = `${rect.top + window.scrollY}px`;
        videoPreviewContainer.style.left = `${rect.left + window.scrollX + rect.width + 10}px`;

        videoPreviewContainer.style.width = "160px";
        videoPreviewContainer.style.height = "90px";

        previewVideo.style.objectFit = "contain";
        previewVideo.style.width = "100%";
        previewVideo.style.height = "100%";

    // 📌 Mostrar previsualización de texto
    } else if (contentType.startsWith('text/')) {
        console.log("📜 Mostrando texto...");
        fetch(mediaUrl)
            .then(response => response.text())
            .then(text => {
                previewText.textContent = text.split('\n').slice(0, 20).join('\n');
                textPreviewContainer.classList.remove('d-none');

                textPreviewContainer.style.position = "absolute";
                textPreviewContainer.style.top = `${rect.top + window.scrollY}px`;
                textPreviewContainer.style.left = `${rect.left + window.scrollX + rect.width + 10}px`;

                textPreviewContainer.style.width = "160px";
                textPreviewContainer.style.height = "90px";
            })
            .catch(error => console.error('❌ Error al obtener texto:', error));

    // 📌 Mostrar previsualización de PDF
    } else if (contentType === 'application/pdf') {
        console.log("📄 Mostrando PDF...");
        fetch(mediaUrl)
            .then(response => response.arrayBuffer())
            .then(data => {
                const loadingTask = pdfjsLib.getDocument({ data });
                loadingTask.promise.then(pdf => {
                    pdf.getPage(1).then(page => {
                        const viewport = page.getViewport({ scale: 0.5 });
                        const context = previewPdfCanvas.getContext('2d');
                        previewPdfCanvas.height = viewport.height;
                        previewPdfCanvas.width = viewport.width;
                        page.render({ canvasContext: context, viewport: viewport });
                        pdfPreviewContainer.classList.remove('d-none');

                        pdfPreviewContainer.style.position = "absolute";
                        pdfPreviewContainer.style.top = `${rect.top + window.scrollY}px`;
                        pdfPreviewContainer.style.left = `${rect.left + window.scrollX + rect.width + 10}px`;

                        pdfPreviewContainer.style.width = "160px";
                        pdfPreviewContainer.style.height = "90px";
                    });
                });
            })
            .catch(error => console.error('❌ Error al cargar PDF:', error));
    }

    // 📌 Evento para ocultar el preview cuando el mouse salga del botón
    button.addEventListener('mouseleave', () => {
        console.log("👋 Saliendo del botón, ocultando previsualización...");
        imagePreviewContainer.classList.add('d-none');
        videoPreviewContainer.classList.add('d-none');
        textPreviewContainer.classList.add('d-none');
        pdfPreviewContainer.classList.add('d-none');
        
        // 📌 Detener el video cuando se oculta
        previewVideo.pause();
        previewVideo.src = "";
    }, { once: true }); // 📌 Se ejecuta solo una vez para evitar múltiples activaciones
});

