/**
 * MODAL GALLERY SYSTEM - Gestor de modales con efecto 3D flip y animaciones
 * @supports Imágenes, videos, GIFs, múltiples formatos
 * @responsive Totalmente responsivo con gestos móviles
 */

class ModalGallery {
    constructor(options = {}) {
        this.options = {
            autoCloseOnEsc: true,
            autoCloseOnOverlay: true,
            preloadNextPrev: true,
            animationDuration: 600,
            ...options
        };

        this.currentIndex = -1;
        this.mediaItems = [];
        this.isOpen = false;
        this.touchStartX = 0;
        this.touchEndX = 0;

        this.init();
    }

    /**
     * Inicializar el sistema
     */
    init() {
        this.createModal();
        this.collectMediaItems();
        this.attachEventListeners();
        console.log('✓ ModalGallery initialized');
    }

    /**
     * Crear estructura del modal
     */
    createModal() {
        const modalHTML = `
        <div class="modal-overlay" id="mediaModalOverlay">
        <button class="modal-close" id="modalCloseBtn" aria-label="Cerrar modal">✕</button>
        <div class="modal-container" id="modalContainer">
        <div class="modal-content" id="modalContent">
        <div class="modal-header">
        <div>
        <div class="modal-title" id="modalTitle"></div>
        <div class="modal-meta" id="modalMeta"></div>
        </div>
        </div>
        <div class="modal-media" id="modalMedia"></div>
        <div class="modal-text-content" id="modalTextContent"></div>
        <div class="modal-footer">
        <button class="modal-nav-btn" id="prevBtn" aria-label="Anterior">← Anterior</button>
        <span class="modal-counter" id="counter"></span>
        <button class="modal-nav-btn" id="nextBtn" aria-label="Siguiente">Siguiente →</button>
        </div>
        </div>
        </div>
        </div>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHTML);

        // Referenciar elementos del DOM
        this.overlay = document.getElementById('mediaModalOverlay');
        this.container = document.getElementById('modalContainer');
        this.content = document.getElementById('modalContent');
        this.mediaArea = document.getElementById('modalMedia');
        this.textArea = document.getElementById('modalTextContent');
        this.titleEl = document.getElementById('modalTitle');
        this.metaEl = document.getElementById('modalMeta');
        this.closeBtn = document.getElementById('modalCloseBtn');
        this.prevBtn = document.getElementById('prevBtn');
        this.nextBtn = document.getElementById('nextBtn');
        this.counter = document.getElementById('counter');
    }

    /**
     * Recolectar todos los elementos con atributo data-media
     */
    collectMediaItems() {
        this.mediaItems = Array.from(
            document.querySelectorAll('[data-media-id], .media-container[data-media-id]')
        ).map((el, idx) => ({
            element: el,
            id: el.getAttribute('data-media-id') || `media-${idx}`,
                            type: el.getAttribute('data-media-type') || 'image', // image, video, gif
                            src: el.getAttribute('data-media-src') || '',
                            title: el.getAttribute('data-media-title') || 'Media',
                            description: el.getAttribute('data-media-description') || '',
                            content: el.getAttribute('data-media-content') || '', // Contenido adicional
                            thumbnail: el.getAttribute('data-media-thumb') || ''
        }));

        console.log(`Found ${this.mediaItems.length} media items`);
    }

    /**
     * Adjuntar event listeners
     */
    attachEventListeners() {
        // Clicks en contenedores media
        this.mediaItems.forEach((item, idx) => {
            item.element.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                this.open(idx);
            });
        });

        // Controles del modal
        this.closeBtn.addEventListener('click', () => this.close());
        this.overlay.addEventListener('click', (e) => {
            if (e.target === this.overlay && this.options.autoCloseOnOverlay) {
                this.close();
            }
        });

        this.prevBtn.addEventListener('click', () => this.prev());
        this.nextBtn.addEventListener('click', () => this.next());

        // Teclado
        if (this.options.autoCloseOnEsc) {
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape' && this.isOpen) {
                    this.close();
                }
                if (e.key === 'ArrowLeft' && this.isOpen) {
                    this.prev();
                }
                if (e.key === 'ArrowRight' && this.isOpen) {
                    this.next();
                }
            });
        }

        // Touch/Swipe
        this.overlay.addEventListener('touchstart', (e) => {
            this.touchStartX = e.changedTouches[0].screenX;
        });

        this.overlay.addEventListener('touchend', (e) => {
            this.touchEndX = e.changedTouches[0].screenX;
            this.handleSwipe();
        });

        // Prevenir scroll del body cuando modal está abierto
        this.setupScrollLock();
    }

    /**
     * Abrir modal en índice específico
     */
    open(index) {
        if (index < 0 || index >= this.mediaItems.length) return;

        this.currentIndex = index;
        this.isOpen = true;

        // Activar overlay y modal con animación
        this.overlay.classList.add('active');
        this.container.classList.remove('closing');

        // Esperar a que se active el overlay, luego cargar contenido
        setTimeout(() => {
            this.loadMedia(index);
        }, 50);

        // Lock scroll
        document.body.style.overflow = 'hidden';
    }

    /**
     * Cerrar modal con animación
     */
    close() {
        if (!this.isOpen) return;

        this.isOpen = false;
        this.container.classList.add('closing');

        setTimeout(() => {
            this.overlay.classList.remove('active');
            this.container.classList.remove('closing');
            document.body.style.overflow = '';
        this.currentIndex = -1;
        }, this.options.animationDuration);
    }

    /**
     * Cargar contenido del media actual
     */
    loadMedia(index) {
        const item = this.mediaItems[index];
        if (!item) return;

        // Actualizar header
        this.titleEl.textContent = item.title;
        this.metaEl.textContent = item.type.toUpperCase();
        this.counter.textContent = `${index + 1} de ${this.mediaItems.length}`;

        // Limpiar área de media
        this.mediaArea.innerHTML = '';

        // Cargar media según tipo
        switch (item.type.toLowerCase()) {
            case 'image':
            case 'png':
            case 'jpg':
            case 'jpeg':
                this.loadImage(item);
                break;
            case 'video':
                this.loadVideo(item);
                break;
            case 'gif':
                this.loadGif(item);
                break;
            default:
                this.loadImage(item);
        }

        // Cargar contenido adicional
        this.loadTextContent(item);

        // Actualizar botones de navegación
        this.updateNavButtons(index);

        // Precargar siguiente/anterior
        if (this.options.preloadNextPrev) {
            if (index > 0) this.preloadMedia(index - 1);
            if (index < this.mediaItems.length - 1) this.preloadMedia(index + 1);
        }
    }

    /**
     * Cargar imagen
     */
    loadImage(item) {
        const img = document.createElement('img');
        img.src = item.src;
        img.alt = item.title;
        img.loading = 'lazy';

        // Mostrar loading
        const loading = document.createElement('div');
        loading.className = 'media-loading';
        this.mediaArea.appendChild(loading);

        img.onload = () => {
            loading.remove();
            this.mediaArea.innerHTML = '';
            this.mediaArea.appendChild(img);
        };

        img.onerror = () => {
            loading.remove();
            this.showError('No se pudo cargar la imagen');
        };
    }

    /**
     * Cargar video
     */
    loadVideo(item) {
        const video = document.createElement('video');
        video.src = item.src;
        video.controls = true;
        video.autoplay = true;
        video.loop = false;
        video.style.width = '100%';
        video.style.height = '100%';
        video.style.objectFit = 'contain';

        this.mediaArea.appendChild(video);

        // Capturar errores de video
        video.onerror = () => {
            this.showError('No se pudo cargar el video');
        };
    }

    /**
     * Cargar GIF (misma técnica que imagen)
     */
    loadGif(item) {
        const img = document.createElement('img');
        img.src = item.src;
        img.alt = item.title;
        img.style.width = '100%';
        img.style.height = '100%';
        img.style.objectFit = 'contain';

        const loading = document.createElement('div');
        loading.className = 'media-loading';
        this.mediaArea.appendChild(loading);

        img.onload = () => {
            loading.remove();
            this.mediaArea.innerHTML = '';
            this.mediaArea.appendChild(img);
        };

        img.onerror = () => {
            loading.remove();
            this.showError('No se pudo cargar el GIF');
        };
    }

    /**
     * Cargar contenido de texto adicional
     */
    loadTextContent(item) {
        this.textArea.innerHTML = '';

        if (item.description || item.content) {
            const desc = document.createElement('p');
            desc.textContent = item.description;
            if (item.description) this.textArea.appendChild(desc);

            // Renderizar content como HTML si está disponible
            if (item.content) {
                const contentDiv = document.createElement('div');
                contentDiv.innerHTML = item.content; // Usar HTML si se proporciona
                this.textArea.appendChild(contentDiv);
            }
        }
    }

    /**
     * Mostrar error
     */
    showError(message) {
        const error = document.createElement('div');
        error.className = 'media-error';
        error.innerHTML = `
        <div>
        <div class="media-error-icon">⚠️</div>
        <p>${message}</p>
        </div>
        `;
        this.mediaArea.innerHTML = '';
        this.mediaArea.appendChild(error);
    }

    /**
     * Precargar media (para performance)
     */
    preloadMedia(index) {
        const item = this.mediaItems[index];
        if (!item) return;

        if (['image', 'png', 'jpg', 'jpeg', 'gif'].includes(item.type.toLowerCase())) {
            const img = new Image();
            img.src = item.src;
        }
    }

    /**
     * Actualizar estado de botones de navegación
     */
    updateNavButtons(index) {
        this.prevBtn.disabled = index === 0;
        this.nextBtn.disabled = index === this.mediaItems.length - 1;
    }

    /**
     * Navegar al anterior
     */
    prev() {
        if (this.currentIndex > 0) {
            this.loadMedia(this.currentIndex - 1);
            this.currentIndex--;
            this.animateNavigation(-1);
        }
    }

    /**
     * Navegar al siguiente
     */
    next() {
        if (this.currentIndex < this.mediaItems.length - 1) {
            this.loadMedia(this.currentIndex + 1);
            this.currentIndex++;
            this.animateNavigation(1);
        }
    }

    /**
     * Animación de transición entre items
     */
    animateNavigation(direction) {
        this.container.style.animation = 'none';
        // Force reflow
        void this.container.offsetWidth;
        // Aplicar animación dependiendo de dirección
        this.container.style.transform = `rotateY(${direction > 0 ? -15 : 15}deg) scale(0.95)`;
        this.container.style.opacity = '0.7';

        setTimeout(() => {
            this.container.style.transition = 'all 0.4s cubic-bezier(0.23, 1, 0.320, 1)';
        this.container.style.transform = 'rotateY(0deg) scale(1)';
        this.container.style.opacity = '1';
        }, 50);
    }

    /**
     * Manejar swipe en móvil
     */
    handleSwipe() {
        const diff = this.touchStartX - this.touchEndX;
        const threshold = 50;

        if (Math.abs(diff) > threshold) {
            if (diff > 0) {
                // Swipe left → siguiente
                this.next();
            } else {
                // Swipe right → anterior
                this.prev();
            }
        }
    }

    /**
     * Setup scroll lock cuando modal está abierto
     */
    setupScrollLock() {
        // Ya manejado en open() y close()
    }

    /**
     * API pública: agregar nuevo item dinámicamente
     */
    addItem(mediaData) {
        this.mediaItems.push({
            id: mediaData.id || `media-${Date.now()}`,
                             type: mediaData.type || 'image',
                             src: mediaData.src,
                             title: mediaData.title || 'Media',
                             description: mediaData.description || '',
                             content: mediaData.content || '',
                             thumbnail: mediaData.thumbnail || '',
                             element: mediaData.element || null
        });

        // Si hay elemento, adjuntar listener
        if (mediaData.element) {
            mediaData.element.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                this.open(this.mediaItems.length - 1);
            });
        }
    }

    /**
     * API pública: remover item
     */
    removeItem(id) {
        this.mediaItems = this.mediaItems.filter(item => item.id !== id);
    }

    /**
     * API pública: limpiar todo
     */
    destroy() {
        this.overlay.remove();
        this.mediaItems = [];
        this.currentIndex = -1;
        this.isOpen = false;
    }
}

// ===================== INICIALIZACIÓN AUTOMÁTICA =====================
document.addEventListener('DOMContentLoaded', () => {
    // Inicializar si hay contenedores media en la página
    if (document.querySelectorAll('[data-media-id], .media-container').length > 0) {
        window.modalGallery = new ModalGallery({
            autoCloseOnEsc: true,
            autoCloseOnOverlay: true,
            preloadNextPrev: true,
            animationDuration: 600
        });

        console.log('✓ Modal Gallery System ready');
    }
});

// Exportar para uso en otros scripts
if (typeof module !== 'undefined' && module.exports) {
    module.exports = ModalGallery;
}
