document.addEventListener('DOMContentLoaded', function() {
    const modal = document.querySelector('.modal');
    const modalImage = document.querySelector('.modal-main-image');
    let isZoomed = false;
    let lastX = 0;
    let lastY = 0;
    let isDragging = false;

    modalImage.addEventListener('click', function(e) {
        e.preventDefault();
        
        if (!isZoomed) {
            // Aplicar zoom
            this.classList.add('zoomed');
            // Centrar el zoom en el punto del clic
            const rect = this.getBoundingClientRect();
            const x = (e.clientX - rect.left) / rect.width;
            const y = (e.clientY - rect.top) / rect.height;
            this.style.transformOrigin = `${x * 100}% ${y * 100}%`;
        } else {
            // Quitar zoom
            this.classList.remove('zoomed');
            this.style.transform = 'none';
        }
        
        isZoomed = !isZoomed;
    });

    // Manejar el arrastre
    modalImage.addEventListener('mousedown', function(e) {
        if (!isZoomed) return;
        isDragging = true;
        lastX = e.clientX;
        lastY = e.clientY;
        this.style.cursor = 'grabbing';
    });

    document.addEventListener('mousemove', function(e) {
        if (!isDragging) return;
        
        const deltaX = e.clientX - lastX;
        const deltaY = e.clientY - lastY;
        lastX = e.clientX;
        lastY = e.clientY;

        const img = modalImage;
        const rect = img.getBoundingClientRect();
        
        // Actualizar la posición con transformación
        const currentTransform = window.getComputedStyle(img).transform;
        const matrix = new DOMMatrix(currentTransform);
        const newX = matrix.m41 + deltaX;
        const newY = matrix.m42 + deltaY;
        
        img.style.transform = `translate(${newX}px, ${newY}px) scale(2.5)`;
    });

    document.addEventListener('mouseup', function() {
        if (isDragging) {
            isDragging = false;
            modalImage.style.cursor = 'grab';
        }
    });

    // Prevenir que el zoom del navegador interfiera
    modal.addEventListener('wheel', function(e) {
        if (isZoomed) {
            e.preventDefault();
        }
    }, { passive: false });
});
