class EnhancedImageZoom {
  constructor(container) {
    this.container = container;
    this.image = container.querySelector('.zoomable-image');
    this.controlsPanel = container.querySelector('.zoom-controls-panel');
    this.zoomPercentage = container.querySelector('.zoom-percentage');
    this.zoomSlider = container.querySelector('.zoom-slider');
    this.modal = document.querySelector('.fullscreen-zoom-modal');
    this.modalImage = this.modal?.querySelector('.fullscreen-image');
    this.modalZoomLevel = this.modal?.querySelector('.modal-zoom-level');
    this.modalZoomSlider = this.modal?.querySelector('.modal-zoom-slider');
    this.zoomLens = container.querySelector('.zoom-lens');
    
    this.zoomLevel = 1;
    this.maxZoom = parseFloat(container.dataset.maxZoom) || 4;
    this.minZoom = 0.5;
    this.position = { x: 0, y: 0 };
    this.isDragging = false;
    this.dragStart = { x: 0, y: 0 };
    this.currentRotation = 0;
    
    this.init();
  }
  
  init() {
    this.setupEventListeners();
    this.setupModal();
    this.updateZoomDisplay();
  }
  
  setupEventListeners() {
    // Zoom com roda do mouse
    this.container.addEventListener('wheel', (e) => {
      if (e.ctrlKey || e.metaKey) {
        e.preventDefault();
        const delta = e.deltaY > 0 ? -0.1 : 0.1;
        this.setZoom(this.zoomLevel + delta);
      }
    }, { passive: false });
    
    // Arrastar imagem
    this.image.addEventListener('mousedown', this.startDrag.bind(this));
    document.addEventListener('mousemove', this.drag.bind(this));
    document.addEventListener('mouseup', this.stopDrag.bind(this));
    
    // Toque para mobile
    this.image.addEventListener('touchstart', this.startTouchDrag.bind(this));
    document.addEventListener('touchmove', this.touchDrag.bind(this));
    document.addEventListener('touchend', this.stopDrag.bind(this));
    
    // Zoom com pinça (mobile)
    let initialDistance = null;
    this.container.addEventListener('touchstart', (e) => {
      if (e.touches.length === 2) {
        initialDistance = this.getTouchDistance(e);
      }
    });
    
    this.container.addEventListener('touchmove', (e) => {
      if (e.touches.length === 2) {
        e.preventDefault();
        const currentDistance = this.getTouchDistance(e);
        if (initialDistance) {
          const scaleChange = (currentDistance - initialDistance) / 100;
          this.setZoom(this.zoomLevel + scaleChange * 0.5);
          initialDistance = currentDistance;
        }
      }
    });
    
    // Botões de zoom
    this.container.querySelector('.zoom-in-btn')?.addEventListener('click', () => {
      this.setZoom(this.zoomLevel + 0.25);
    });
    
    this.container.querySelector('.zoom-out-btn')?.addEventListener('click', () => {
      this.setZoom(this.zoomLevel - 0.25);
    });
    
    this.container.querySelector('.zoom-reset-btn')?.addEventListener('click', () => {
      this.resetZoom();
    });
    
    this.container.querySelector('.zoom-fullscreen-btn')?.addEventListener('click', () => {
      this.openFullscreen();
    });
    
    this.container.querySelector('.zoom-download-btn')?.addEventListener('click', () => {
      this.downloadImage();
    });
    
    // Slider de zoom
    this.zoomSlider?.addEventListener('input', (e) => {
      const value = parseInt(e.target.value);
      this.setZoom(value / 100);
    });
    
    // Lente de zoom (hover)
    if (this.zoomLens) {
      this.container.addEventListener('mousemove', (e) => {
        if (this.zoomLevel === 1) {
          this.showZoomLens(e);
        }
      });
      
      this.container.addEventListener('mouseleave', () => {
        this.hideZoomLens();
      });
    }
    
    // Atalhos de teclado
    document.addEventListener('keydown', (e) => {
      if (e.target === document.body || !e.target.matches('input, textarea, select')) {
        if ((e.ctrlKey || e.metaKey) && e.key === '=') {
          e.preventDefault();
          this.setZoom(this.zoomLevel + 0.25);
        } else if ((e.ctrlKey || e.metaKey) && e.key === '-') {
          e.preventDefault();
          this.setZoom(this.zoomLevel - 0.25);
        } else if (e.key === 'r' || e.key === 'R') {
          e.preventDefault();
          this.resetZoom();
        } else if (e.key === 'f' || e.key === 'F') {
          e.preventDefault();
          this.openFullscreen();
        } else if (e.key === 'Escape' && this.modal.style.display === 'block') {
          this.closeFullscreen();
        }
      }
    });
  }
  
  setupModal() {
    if (!this.modal) return;
    
    // Botão de fechar
    this.modal.querySelector('.modal-close-btn').addEventListener('click', () => {
      this.closeFullscreen();
    });
    
    // Fechar ao clicar fora
    this.modal.addEventListener('click', (e) => {
      if (e.target === this.modal) {
        this.closeFullscreen();
      }
    });
    
    // Controles do modal
    this.modal.querySelector('.modal-zoom-in')?.addEventListener('click', () => {
      this.setModalZoom(this.getModalZoom() + 0.1);
    });
    
    this.modal.querySelector('.modal-zoom-out')?.addEventListener('click', () => {
      this.setModalZoom(this.getModalZoom() - 0.1);
    });
    
    this.modalZoomSlider?.addEventListener('input', (e) => {
      const value = parseInt(e.target.value);
      this.setModalZoom(value / 100);
    });
    
    // Rotação
    this.modal.querySelector('.rotate-left')?.addEventListener('click', () => {
      this.rotateImage(-90);
    });
    
    this.modal.querySelector('.rotate-right')?.addEventListener('click', () => {
      this.rotateImage(90);
    });
    
    // Download HD
    this.modal.querySelector('.download-hd')?.addEventListener('click', () => {
      this.downloadHD();
    });
    
    // Navegação
    this.modal.querySelector('.prev-btn')?.addEventListener('click', () => {
      this.navigateImage(-1);
    });
    
    this.modal.querySelector('.next-btn')?.addEventListener('click', () => {
      this.navigateImage(1);
    });
    
    // Arrastar imagem no modal
    let modalIsDragging = false;
    let modalStartX, modalStartY;
    let modalTranslateX = 0, modalTranslateY = 0;
    
    this.modalImage.addEventListener('mousedown', (e) => {
      modalIsDragging = true;
      modalStartX = e.clientX - modalTranslateX;
      modalStartY = e.clientY - modalTranslateY;
      this.modalImage.style.cursor = 'grabbing';
    });
    
    document.addEventListener('mousemove', (e) => {
      if (!modalIsDragging) return;
      e.preventDefault();
      modalTranslateX = e.clientX - modalStartX;
      modalTranslateY = e.clientY - modalStartY;
      this.modalImage.style.transform = 
        `scale(${this.getModalZoom()}) translate(${modalTranslateX}px, ${modalTranslateY}px) rotate(${this.currentRotation}deg)`;
    });
    
    document.addEventListener('mouseup', () => {
      modalIsDragging = false;
      this.modalImage.style.cursor = 'grab';
    });
  }
  
  setZoom(level) {
    // Limitar zoom máximo e mínimo
    level = Math.max(this.minZoom, Math.min(this.maxZoom, level));
    
    // Aplicar zoom
    this.zoomLevel = level;
    this.image.style.transform = `scale(${level}) translate(${this.position.x}px, ${this.position.y}px)`;
    
    // Atualizar controles
    this.updateZoomDisplay();
    
    // Animação
    this.image.classList.add('zoom-in-effect');
    setTimeout(() => this.image.classList.remove('zoom-in-effect'), 300);
  }
  
  setModalZoom(level) {
    level = Math.max(0.5, Math.min(5, level));
    this.modalImage.style.transform = `scale(${level})`;
    this.modalZoomLevel.textContent = `${Math.round(level * 100)}%`;
    this.modalZoomSlider.value = level * 100;
  }
  
  getModalZoom() {
    const transform = this.modalImage.style.transform;
    const match = transform.match(/scale\(([^)]+)\)/);
    return match ? parseFloat(match[1]) : 1;
  }
  
  updateZoomDisplay() {
    const percentage = Math.round(this.zoomLevel * 100);
    this.zoomPercentage.textContent = `${percentage}%`;
    this.zoomSlider.value = percentage;
  }
  
  resetZoom() {
    this.zoomLevel = 1;
    this.position = { x: 0, y: 0 };
    this.image.style.transform = 'scale(1) translate(0, 0)';
    this.updateZoomDisplay();
    this.image.classList.add('zoom-out-effect');
    setTimeout(() => this.image.classList.remove('zoom-out-effect'), 300);
  }
  
  startDrag(e) {
    if (this.zoomLevel > 1) {
      this.isDragging = true;
      this.dragStart = {
        x: e.clientX - this.position.x,
        y: e.clientY - this.position.y
      };
      this.image.style.cursor = 'grabbing';
    }
  }
  
  startTouchDrag(e) {
    if (this.zoomLevel > 1 && e.touches.length === 1) {
      this.isDragging = true;
      this.dragStart = {
        x: e.touches[0].clientX - this.position.x,
        y: e.touches[0].clientY - this.position.y
      };
    }
  }
  
  drag(e) {
    if (!this.isDragging) return;
    e.preventDefault();
    
    this.position.x = e.clientX - this.dragStart.x;
    this.position.y = e.clientY - this.dragStart.y;
    
    // Limitar arraste para não sair da viewport
    const maxX = (this.zoomLevel - 1) * this.image.offsetWidth / 2;
    const maxY = (this.zoomLevel - 1) * this.image.offsetHeight / 2;
    
    this.position.x = Math.max(-maxX, Math.min(maxX, this.position.x));
    this.position.y = Math.max(-maxY, Math.min(maxY, this.position.y));
    
    this.image.style.transform = `scale(${this.zoomLevel}) translate(${this.position.x}px, ${this.position.y}px)`;
  }
  
  touchDrag(e) {
    if (!this.isDragging || e.touches.length !== 1) return;
    e.preventDefault();
    
    this.position.x = e.touches[0].clientX - this.dragStart.x;
    this.position.y = e.touches[0].clientY - this.dragStart.y;
    
    const maxX = (this.zoomLevel - 1) * this.image.offsetWidth / 2;
    const maxY = (this.zoomLevel - 1) * this.image.offsetHeight / 2;
    
    this.position.x = Math.max(-maxX, Math.min(maxX, this.position.x));
    this.position.y = Math.max(-maxY, Math.min(maxY, this.position.y));
    
    this.image.style.transform = `scale(${this.zoomLevel}) translate(${this.position.x}px, ${this.position.y}px)`;
  }
  
  stopDrag() {
    this.isDragging = false;
    this.image.style.cursor = this.zoomLevel > 1 ? 'grab' : 'default';
  }
  
  showZoomLens(e) {
    const rect = this.container.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    // Posicionar lente
    this.zoomLens.style.left = `${x - 100}px`;
    this.zoomLens.style.top = `${y - 100}px`;
    this.zoomLens.style.display = 'block';
    
    // Criar efeito de lupa
    const zoom = 2;
    const bgX = (x / this.image.offsetWidth) * 100;
    const bgY = (y / this.image.offsetHeight) * 100;
    this.zoomLens.style.backgroundImage = `url(${this.image.src})`;
    this.zoomLens.style.backgroundSize = `${this.image.offsetWidth * zoom}px ${this.image.offsetHeight * zoom}px`;
    this.zoomLens.style.backgroundPosition = `${bgX}% ${bgY}%`;
  }
  
  hideZoomLens() {
    this.zoomLens.style.display = 'none';
  }
  
  getTouchDistance(e) {
    const dx = e.touches[0].clientX - e.touches[1].clientX;
    const dy = e.touches[0].clientY - e.touches[1].clientY;
    return Math.sqrt(dx * dx + dy * dy);
  }
  
  openFullscreen() {
    if (!this.modal || !this.modalImage) return;
    
    const hdSrc = this.image.dataset.zoomSrc || this.image.src;
    this.modalImage.src = hdSrc;
    this.setModalZoom(1);
    this.currentRotation = 0;
    this.modalImage.style.transform = 'scale(1) rotate(0deg)';
    
    this.modal.style.display = 'block';
    document.body.style.overflow = 'hidden';
    
    // Animação de entrada
    this.modal.style.animation = 'modalFadeIn 0.3s ease';
  }
  
  closeFullscreen() {
    this.modal.style.display = 'none';
    document.body.style.overflow = 'auto';
  }
  
  rotateImage(degrees) {
    this.currentRotation += degrees;
    const currentScale = this.getModalZoom();
    this.modalImage.style.transform = 
      `scale(${currentScale}) rotate(${this.currentRotation}deg)`;
  }
  
  downloadImage() {
    const link = document.createElement('a');
    link.href = this.image.src;
    link.download = `construction-project-${Date.now()}.jpg`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
  
  downloadHD() {
    const hdSrc = this.image.dataset.zoomSrc || this.image.src;
    const link = document.createElement('a');
    link.href = hdSrc;
    link.download = `construction-project-hd-${Date.now()}.jpg`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
  
  navigateImage(direction) {
    // Implemente a navegação entre imagens conforme necessário
    console.log('Navegar para imagem:', direction);
  }
}

// Inicializar quando o DOM estiver pronto
document.addEventListener('DOMContentLoaded', () => {
  const zoomContainers = document.querySelectorAll('.enhanced-zoom-container');
  zoomContainers.forEach(container => {
    new EnhancedImageZoom(container);
  });
});