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

    const imagePreviewContainer = document.getElementById('image-preview');
    const previewImage = document.getElementById('preview-image');
    const videoPreviewContainer = document.getElementById('video-preview');
    const previewVideo = document.getElementById('preview-video'); // ✅ Definido correctamente
    const textPreviewContainer = document.getElementById('text-preview');
    const previewText = document.getElementById('preview-text');
    const pdfPreviewContainer = document.getElementById('pdf-preview');
    const 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);

    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;
        }

        if (contentType.startsWith('image/')) {
            console.log("🖼️ Mostrando imagen...");
            previewImage.src = mediaUrl;
            imagePreviewContainer.classList.remove('d-none');
        } else if (contentType.startsWith('video/')) {
            console.log("🎥 Mostrando video...");

            // Forzar recarga del video
            previewVideo.src = "";
            setTimeout(() => {
                previewVideo.src = mediaUrl;
                previewVideo.load();
                previewVideo.play();
            }, 50);

            // Asegurar que el contenedor se muestra y ajustar estilos
            videoPreviewContainer.classList.remove('d-none');
            videoPreviewContainer.style.display = "block";

            previewVideo.style.objectFit = "contain";
            previewVideo.style.width = "auto";
            previewVideo.style.height = "auto";
        }
    });
});

