class ImageUploader {
  constructor() {
    this.uploadArea = document.getElementById('upload-area');
    this.fileInput = document.getElementById('image-upload');
    this.uploadBtn = document.getElementById('upload-btn');
    this.previewContainer = document.getElementById('upload-preview');
    this.previewImage = document.getElementById('preview-image');
    this.fileName = document.getElementById('file-name');
    this.removeBtn = document.getElementById('remove-image');
    this.alertContainer = document.getElementById('upload-alert');
    this.alertIcon = document.getElementById('alert-icon');
    this.alertMessage = document.getElementById('alert-message');
    this.opacityControl = document.getElementById('opacity-control');
    this.opacitySlider = document.getElementById('opacity-slider');
    this.opacityValue = document.getElementById('opacity-value');
    this.removeBgBtn = document.getElementById('remove-bg-btn');
    this.chartContainer = document.getElementById('chartContainer');
    this.chartCanvas = document.getElementById('chartCanvas');
    this.selectedFile = null;
    this.currentBackgroundImage = null;

    this.init();
  }

  init() {
    this.setupEventListeners();
    this.checkExistingImage();
  }

  setupEventListeners() {
    // Click to browse
    this.uploadArea.addEventListener('click', () => {
      this.fileInput.click();
    });

    // Browse link click
    const browseLink = document.querySelector('.browse-link');
    if (browseLink) {
      browseLink.addEventListener('click', (e) => {
        e.stopPropagation();
        this.fileInput.click();
      });
    }

    // File input change
    this.fileInput.addEventListener('change', (e) => {
      this.handleFileSelect(e.target.files[0]);
    });

    // Drag and drop
    this.uploadArea.addEventListener('dragover', (e) => {
      e.preventDefault();
      this.uploadArea.classList.add('dragover');
    });

    this.uploadArea.addEventListener('dragleave', () => {
      this.uploadArea.classList.remove('dragover');
    });

    this.uploadArea.addEventListener('drop', (e) => {
      e.preventDefault();
      this.uploadArea.classList.remove('dragover');
      const file = e.dataTransfer.files[0];
      if (file && this.isValidFile(file)) {
        this.handleFileSelect(file);
      }
    });

    // Remove image
    this.removeBtn.addEventListener('click', () => {
      this.clearSelection();
    });

    // Upload button
    this.uploadBtn.addEventListener('click', () => {
      this.uploadImage();
    });

    // Opacity slider - handled by OpacityController
    // Remove this listener as OpacityController handles it

    // Remove background button
    this.removeBgBtn.addEventListener('click', () => {
      this.deleteImageFile();
    });
  }

  isValidFile(file) {
    const validTypes = ['image/jpeg', 'image/jpg', 'image/png'];
    return validTypes.includes(file.type);
  }

  handleFileSelect(file) {
    if (!file || !this.isValidFile(file)) {
      this.showAlert('Please select a valid JPG or PNG image file.', 'error');
      return;
    }

    this.hideAlert();
    this.selectedFile = file;
    this.showPreview(file);
    this.uploadBtn.disabled = false;
  }

  showPreview(file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      this.previewImage.src = e.target.result;
      this.fileName.textContent = file.name;
      this.previewContainer.style.display = 'flex';
    };
    reader.readAsDataURL(file);
  }

  showAlert(message, type) {
    this.alertMessage.textContent = message;
    this.alertContainer.className = `upload-alert ${type}`;
    this.alertIcon.className = type === 'success' ? 'fas fa-check-circle' : 'fas fa-exclamation-circle';
    this.alertContainer.style.display = 'flex';
  }

  hideAlert() {
    this.alertContainer.style.display = 'none';
  }

  setChartBackground(imagePath) {

    
    // Set CSS variable for background image
    document.documentElement.style.setProperty('--bg-image', `url('${imagePath}')`);
    
    // Add chart-has-background class
    const mainContent = document.querySelector('.main-content');
    if (mainContent) {
      mainContent.classList.add('chart-has-background');
    }
    
    // Set default opacity if none exists
    const savedOpacity = localStorage.getItem('chart-bg-opacity');
    if (savedOpacity === null) {
      // Set initial opacity to 50% for new images
      if (window.opacityController) {
        window.opacityController.updateOpacity(50);
      }
    }
    
    // Create background overlay for margin coverage
    this.createBackgroundOverlay(imagePath);
    
    // Canvas background for chart area
    this.backgroundImage = new Image();
    this.backgroundImage.crossOrigin = 'anonymous';
    
    this.backgroundImage.onload = () => {

      this.setupCanvasHook();
      this.drawBackground();
      this.startBackgroundMonitor();
      
      // Dispatch custom event to notify background image detector
      const event = new CustomEvent('backgroundImageSet', {
        detail: { imagePath, element: 'chartContainer' }
      });
      document.dispatchEvent(event);

    };
    
    this.backgroundImage.src = imagePath;
    this.opacityControl.style.display = 'block';
  }

  createBackgroundOverlay(imagePath) {
    if (!this.backgroundOverlay) {
      this.backgroundOverlay = document.createElement('div');
      this.backgroundOverlay.style.position = 'absolute';
      this.backgroundOverlay.style.top = '-25px';
      this.backgroundOverlay.style.left = '-25px';
      this.backgroundOverlay.style.width = 'calc(100% + 50px)';
      this.backgroundOverlay.style.height = 'calc(100% + 50px)';
      this.backgroundOverlay.style.pointerEvents = 'none';
      this.backgroundOverlay.style.zIndex = '-1';
      this.backgroundOverlay.style.overflow = 'hidden';
      this.chartContainer.appendChild(this.backgroundOverlay);
    }
    
    const opacity = this.opacitySlider.value / 100;
    this.backgroundOverlay.style.backgroundImage = `url('${imagePath}')`;
    this.backgroundOverlay.style.backgroundSize = 'cover';
    this.backgroundOverlay.style.backgroundPosition = 'center';
    this.backgroundOverlay.style.backgroundRepeat = 'no-repeat';
    this.backgroundOverlay.style.opacity = opacity;
  }

  updateChartBackground() {
    // Get opacity from CSS variable set by OpacityController
    const opacity = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--bg-opacity')) || 0;
    
    // Update background overlay opacity
    if (this.backgroundOverlay) {
      this.backgroundOverlay.style.opacity = opacity;
    }
    
    // Update canvas background
    if (this.backgroundImage && this.backgroundImage.complete) {
      this.drawBackground();
    }
  }

  setupCanvasHook() {
    if (this.canvasHooked) {
  
      return;
    }
    

    const ctx = this.chartCanvas.getContext('2d');
    const originalClearRect = ctx.clearRect;
    const originalFillRect = ctx.fillRect;
    
    // Hook clearRect to redraw background
    ctx.clearRect = (...args) => {

      originalClearRect.apply(ctx, args);
      if (this.backgroundImage && args[2] === this.chartCanvas.width) {

        this.drawBackground();
      }
    };
    
    // Hook fillRect for background fills
    ctx.fillRect = (...args) => {

      originalFillRect.apply(ctx, args);
      if (args[2] === this.chartCanvas.width && args[3] === this.chartCanvas.height) {

        this.drawBackground();
      }
    };
    
    this.canvasHooked = true;

  }

  drawBackground() {
    if (!this.chartCanvas || !this.backgroundImage || !this.backgroundImage.complete) {
      return;
    }
    
    const ctx = this.chartCanvas.getContext('2d');
    const opacity = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--bg-opacity')) || 0;
    
    // Add large margins to prevent edge bleeding during zoom
    const marginX = 50;
    const marginY = 50;
    const canvasWidth = this.chartCanvas.width + marginX * 2;
    const canvasHeight = this.chartCanvas.height + marginY * 2;
    const imageWidth = this.backgroundImage.width;
    const imageHeight = this.backgroundImage.height;
    
    const canvasRatio = canvasWidth / canvasHeight;
    const imageRatio = imageWidth / imageHeight;
    
    let drawWidth, drawHeight, offsetX, offsetY;
    
    if (imageRatio > canvasRatio) {
      // Image is wider, fit to extended canvas height and crop sides
      drawHeight = canvasHeight;
      drawWidth = canvasHeight * imageRatio;
      offsetX = -marginX + (canvasWidth - drawWidth) / 2;
      offsetY = -marginY;
    } else {
      // Image is taller, fit to extended canvas width and crop top/bottom
      drawWidth = canvasWidth;
      drawHeight = canvasWidth / imageRatio;
      offsetX = -marginX;
      offsetY = -marginY + (canvasHeight - drawHeight) / 2;
    }
    
    ctx.save();
    ctx.globalCompositeOperation = 'source-over';
    ctx.globalAlpha = opacity;
    
    try {
      ctx.drawImage(this.backgroundImage, offsetX, offsetY, drawWidth, drawHeight);
    } catch (error) {
      console.log('Background draw error:', error);
    }
    
    ctx.restore();
  }

  removeChartBackground() {
    this.backgroundImage = null;
    this.currentBackgroundImage = null;
    this.canvasHooked = false;
    
    // Clear opacity when removing background
    if (window.opacityController) {
      window.opacityController.clearOpacity();
    }
    
    this.opacityControl.style.display = 'none';
    this.showAlert('Background image removed', 'success');
  }

  clearSelection() {
    this.selectedFile = null;
    this.fileInput.value = '';
    this.previewContainer.style.display = 'none';
    this.uploadBtn.disabled = false;
  }

  generateFileName() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    
    const extension = this.selectedFile.name.split('.').pop().toLowerCase();
    return `photo_${year}-${month}-${day}_${hours}-${minutes}-${seconds}.${extension}`;
  }

  async uploadImage() {

    if (!this.selectedFile) {

      return;
    }

    const formData = new FormData();
    const fileName = this.generateFileName();
    formData.append('image', this.selectedFile, fileName);


    try {
      this.uploadBtn.disabled = true;
      this.uploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Uploading...';


      const response = await fetch('php/upload-image.php', {
        method: 'POST',
        body: formData
      });

      const result = await response.json();


      if (result.success) {
        this.showAlert(`Image uploaded successfully as: ${fileName}`, 'success');
        this.currentBackgroundImage = result.path;
        this.setChartBackground(result.path);
        this.clearSelection();
        this.showControlsOnly();
      } else {

        this.showAlert(`Upload failed: ${result.message}`, 'error');
      }
    } catch (error) {
      this.showAlert('Upload failed: Network error', 'error');

    } finally {
      this.uploadBtn.disabled = false;
      this.uploadBtn.innerHTML = '<i class="fas fa-upload"></i> Upload Image';
    }
  }

  async checkExistingImage() {
    try {

      const response = await fetch('php/check-image.php');
      const result = await response.json();
      

      
      if (result.exists && result.path) {

        
        // Test if image loads
        const img = new Image();
        img.onload = () => {

          this.currentBackgroundImage = result.path;
          this.setChartBackground(result.path);
          this.showControlsOnly();
        };
        img.onerror = () => {

          this.showUploaderOnly();
        };
        img.src = result.path;
      } else {

        this.showUploaderOnly();
      }
    } catch (error) {

      this.showUploaderOnly();
    }
  }
  
  resetToUploader() {

    this.currentBackgroundImage = null;
    this.removeChartBackground();
    this.showUploaderOnly();
  }

  startBackgroundMonitor() {
    if (this.backgroundMonitor) return;
    
    this.backgroundMonitor = setInterval(() => {
      if (this.backgroundImage && this.chartCanvas) {
        const ctx = this.chartCanvas.getContext('2d');
        const imageData = ctx.getImageData(0, 0, 1, 1);
        if (imageData.data[3] === 0) {
          this.drawBackground();
        }
      }
    }, 500);
  }

  showUploaderOnly() {
    this.uploadArea.style.display = 'block';
    this.opacityControl.style.display = 'none';
    if (this.uploadBtn) {
      this.uploadBtn.style.display = 'block';
      this.uploadBtn.disabled = false;
    }
  }

  showControlsOnly() {
    this.uploadArea.style.display = 'none';
    this.opacityControl.style.display = 'block';
    if (this.uploadBtn) this.uploadBtn.style.display = 'none';
    if (this.previewContainer) this.previewContainer.style.display = 'none';
  }

  async deleteImageFile() {
    if (!this.currentBackgroundImage) return;

    try {

      
      const response = await fetch('php/delete-image.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ imagePath: this.currentBackgroundImage })
      });

      const result = await response.json();

      if (result.success) {

        const mainContent = document.querySelector('.main-content');
        if (mainContent) {
          mainContent.classList.remove('chart-has-background');
        }
        this.currentBackgroundImage = null;
        this.showUploaderOnly();
        this.showAlert('Background image deleted successfully', 'success');
        
        // Dispatch custom event to notify background image detector
        const event = new CustomEvent('backgroundImageRemoved', {
          detail: { element: 'chartContainer' }
        });
        document.dispatchEvent(event);

      } else {

        // If delete fails, reset to uploader (file probably doesn't exist)
        this.resetToUploader();
        this.showAlert('Image not found, reset to upload mode', 'success');
      }
    } catch (error) {
      this.showAlert('Error deleting image', 'error');

    }
  }
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {

  window.imageUploader = new ImageUploader();

  
  // Auto-check for existing images after a short delay
  setTimeout(() => {
    window.imageUploader.checkExistingImage();
  }, 500);
});