// Fallback for effect toggle functions (in case effect-toggle.js hasn't loaded yet)
if (typeof shouldApplyEffect === 'undefined') {
  window.shouldApplyEffect = function() { return true; };
}
if (typeof isEffectEnabled === 'undefined') {
  window.isEffectEnabled = function() { return true; };
}
if (typeof getAdjustmentValue === 'undefined') {
  window.getAdjustmentValue = function(name, value) { return value; };
}

// Elements
const fileInput = document.getElementById('fileInput');
const selectFileBtn = document.getElementById('selectFileBtn');
const headerUploadBtn = document.getElementById('headerUploadBtn');
const headerClearBtn = document.getElementById('headerClearBtn');
const previewImage = document.getElementById('previewImage');
const imageContainer = document.getElementById('imageContainer');
const canvasPlaceholder = document.getElementById('canvasPlaceholder');
const canvasContent = document.getElementById('canvasContent');
const propertiesSection = document.getElementById('propertiesSection');
const adjustmentsSection = document.getElementById('adjustmentsSection');
const statusIndicator = document.getElementById('statusIndicator');
const canvasInfo = document.getElementById('canvasInfo');
const zoomInBtn = document.getElementById('zoomInBtn');
const zoomOutBtn = document.getElementById('zoomOutBtn');
const zoomResetBtn = document.getElementById('zoomResetBtn');
const zoomLevel = document.getElementById('zoomLevel');

// Adjustment sliders
const brightnessSlider = document.getElementById('brightnessSlider');
const contrastSlider = document.getElementById('contrastSlider');
const saturationSlider = document.getElementById('saturationSlider');
const hueSlider = document.getElementById('hueSlider');
const lightnessSlider = document.getElementById('lightnessSlider');
const temperatureSlider = document.getElementById('temperatureSlider');
const tintSlider = document.getElementById('tintSlider');
const resetAdjustmentsBtn = document.getElementById('resetAdjustments');

// Color preview elements
const colorSwatch = document.getElementById('colorSwatch');
const rgbValue = document.getElementById('rgbValue');
const hslValue = document.getElementById('hslValue');
const hexValue = document.getElementById('hexValue');

let selectedFile = null;
let originalImageData = null; // Store original image for curve processing
let currentZoom = 1;
let isPanning = false;
let startX = 0;
let startY = 0;
let scrollLeft = 0;
let scrollTop = 0;

// History system
let historyStack = [];
let historyIndex = -1;
const MAX_HISTORY = 30;
let isApplyingHistory = false;

// Adjustment values
let adjustments = {
  brightness: 0,
  contrast: 0,
  saturation: 0,
  hue: 0,
  lightness: 0,
  temperature: 0,
  tint: 0,
  // Color Balance
  shadowsCyan: 0,
  shadowsMagenta: 0,
  shadowsYellow: 0,
  midtonesCyan: 0,
  midtonesMagenta: 0,
  midtonesYellow: 0,
  highlightsCyan: 0,
  highlightsMagenta: 0,
  highlightsYellow: 0,
  // Black & White
  bwRed: 40,
  bwYellow: 60,
  bwGreen: 40,
  bwCyan: 60,
  bwBlue: 20,
  bwMagenta: 80,
  bwTint: 0,
  // Exposure
  exposure: 0,
  offset: 0,
  gammaCorrection: 1.0,
  // Vibrance
  vibrance: 0,
  saturationVibrance: 0,
  // Selective Color
  selectiveColorRange: 'reds',
  scCyan: 0,
  scMagenta: 0,
  scYellow: 0,
  scBlack: 0,
  // Photo Filter
  photoFilterType: 'none',
  filterDensity: 25,
  preserveLuminosity: true,
  // Gradient Map
  gradientMapPreset: 'none',
  gradientOpacity: 100,
  // Channel Mixer
  mixerOutputChannel: 'red',
  mixerRed: 100,
  mixerGreen: 0,
  mixerBlue: 0,
  mixerConstant: 0,
  // Color Lookup (LUT)
  lutPreset: 'none',
  lutIntensity: 100,
  // Invert
  invertEnabled: false,
  // Threshold
  thresholdEnabled: false,
  thresholdLevel: 128,
  // Posterize
  posterizeEnabled: false,
  posterizeLevels: 4,
  // Sharpen
  sharpenAmount: 0,
  sharpenRadius: 1,
  sharpenThreshold: 0,
  // Blur
  blurAmount: 0,
  // Flip
  flipHorizontal: false,
  flipVertical: false,
  // Rotate
  rotateAngle: 0
};

// Click button để chọn file
selectFileBtn.addEventListener('click', () => {
  fileInput.click();
});

// Xử lý khi chọn file
fileInput.addEventListener('change', (e) => {
  handleFile(e.target.files[0]);
});

// Drag and drop trên canvas
canvasContent.addEventListener('dragover', (e) => {
  e.preventDefault();
  if (!previewImage.src) {
    canvasContent.style.background = '#2a2a2a';
  }
});

canvasContent.addEventListener('dragleave', () => {
  canvasContent.style.background = '#1e1e1e';
});

canvasContent.addEventListener('drop', (e) => {
  e.preventDefault();
  canvasContent.style.background = '#1e1e1e';
  if (e.dataTransfer.files.length > 0) {
    const file = e.dataTransfer.files[0];
    // Check if it's a project file
    if (file.name.endsWith('.oedit')) {
      if (typeof importProject === 'function') {
        importProject(file);
      }
    } else {
      handleFile(file);
    }
  }
});

// Xử lý file được chọn
function handleFile(file) {
  if (!file) return;
  
  if (!file.type.startsWith('image/')) {
    showMessage('Vui lòng chọn file hình ảnh', 'error');
    updateStatus('Lỗi: File không hợp lệ', false);
    return;
  }
  
  selectedFile = file;
  headerUploadBtn.disabled = false;
  headerClearBtn.style.display = 'flex';
  
  // Enable download button
  const downloadBtn = document.getElementById('downloadBtn');
  if (downloadBtn) {
    downloadBtn.disabled = false;
  }
  
  // Enable export project button
  const exportProjectBtn = document.getElementById('exportProjectBtn');
  if (exportProjectBtn) {
    exportProjectBtn.disabled = false;
  }
  
  // Enable remove background button
  const removeBackgroundBtn = document.getElementById('removeBackgroundBtn');
  if (removeBackgroundBtn) {
    removeBackgroundBtn.disabled = false;
  }
  
  // Enable AI sharpen button
  const aiSharpenBtn = document.getElementById('aiSharpenBtn');
  if (aiSharpenBtn) {
    aiSharpenBtn.disabled = false;
  }
  
  // Show tabs
  const panelTabs = document.getElementById('panelTabs');
  if (panelTabs) {
    panelTabs.style.display = 'flex';
  }
  
  // Hiển thị thông tin file
  displayFileInfo(file);
  
  // Hiển thị preview
  const reader = new FileReader();
  reader.onload = (e) => {
    originalImageData = e.target.result; // Store original
    previewImage.src = e.target.result;
    imageContainer.style.display = 'flex';
    canvasPlaceholder.style.display = 'none';
    adjustmentsSection.style.display = 'block';
    
    // Show effects section
    const effectsSection = document.getElementById('effectsSection');
    if (effectsSection) {
      effectsSection.style.display = 'block';
    }
    
    // Show presets section
    const presetsSection = document.getElementById('presetsSection');
    if (presetsSection) {
      presetsSection.style.display = 'block';
    }
    
    // Lấy kích thước ảnh và tự động fit
    const img = new Image();
    img.onload = () => {
      const dimensions = `${img.width} x ${img.height}px`;
      document.getElementById('imageDimensions').textContent = dimensions;
      canvasInfo.textContent = dimensions;
      
      // Tự động fit ảnh vào canvas
      fitImageToCanvas(img.width, img.height);
    };
    img.src = e.target.result;
    
    // Update color preview
    updateColorPreview();
    
    // Calculate histogram
    calculateHistogram();
  };
  reader.readAsDataURL(file);
  
  updateStatus('File đã sẵn sàng', true);
}

// Tự động fit ảnh vào canvas
function fitImageToCanvas(imgWidth, imgHeight) {
  const containerWidth = canvasContent.clientWidth - 40;
  const containerHeight = canvasContent.clientHeight - 40;
  
  const scaleX = containerWidth / imgWidth;
  const scaleY = containerHeight / imgHeight;
  
  const scale = Math.min(scaleX, scaleY, 1);
  
  currentZoom = Math.max(0.1, scale);
  updateZoom();
}

// Hiển thị thông tin file
function displayFileInfo(file) {
  document.getElementById('fileName').textContent = file.name;
  document.getElementById('fileSize').textContent = formatFileSize(file.size);
  document.getElementById('fileType').textContent = file.type;
  propertiesSection.style.display = 'block';
}

// Format kích thước file
function formatFileSize(bytes) {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];
}

// HSL to RGB conversion
function hslToRgb(h, s, l) {
  h = h / 360;
  s = s / 100;
  l = l / 100;
  
  let r, g, b;
  
  if (s === 0) {
    r = g = b = l;
  } else {
    const hue2rgb = (p, q, t) => {
      if (t < 0) t += 1;
      if (t > 1) t -= 1;
      if (t < 1/6) return p + (q - p) * 6 * t;
      if (t < 1/2) return q;
      if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
      return p;
    };
    
    const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
    const p = 2 * l - q;
    
    r = hue2rgb(p, q, h + 1/3);
    g = hue2rgb(p, q, h);
    b = hue2rgb(p, q, h - 1/3);
  }
  
  return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}

// RGB to HEX conversion
function rgbToHex(r, g, b) {
  return '#' + [r, g, b].map(x => {
    const hex = x.toString(16);
    return hex.length === 1 ? '0' + hex : hex;
  }).join('').toUpperCase();
}

// Update color preview
function updateColorPreview() {
  const h = adjustments.hue;
  const s = 100 + adjustments.saturation;
  const l = 50 + adjustments.lightness;
  
  // Update swatch color
  colorSwatch.style.background = `hsl(${h}, ${s}%, ${l}%)`;
  
  // Convert to RGB
  const [r, g, b] = hslToRgb(h, s, l);
  
  // Update values
  rgbValue.textContent = `rgb(${r}, ${g}, ${b})`;
  hslValue.textContent = `hsl(${h}°, ${s}%, ${l}%)`;
  hexValue.textContent = rgbToHex(r, g, b);
}

// Apply all filters to image using Canvas
function applyFilters(saveHistory = true) {
  if (!previewImage.src || !previewImage.complete || !selectedFile) {
    return;
  }
  
  // Determine which adjustment was changed for history
  if (saveHistory && !isApplyingHistory) {
    // This will be called after the filter is applied
    setTimeout(() => {
      const lastAction = getLastChangedAdjustment();
      if (lastAction) {
        saveToHistory(lastAction.action, lastAction.details);
      }
    }, 100);
  }
  
  const tempCanvas = document.createElement('canvas');
  const tempCtx = tempCanvas.getContext('2d');
  
  const img = new Image();
  img.crossOrigin = 'anonymous';
  
  img.onload = () => {
    tempCanvas.width = img.width;
    tempCanvas.height = img.height;
    tempCtx.drawImage(img, 0, 0);
    
    const imageData = tempCtx.getImageData(0, 0, tempCanvas.width, tempCanvas.height);
    const data = imageData.data;
    
    // Process each pixel
    for (let i = 0; i < data.length; i += 4) {
      let r = data[i];
      let g = data[i + 1];
      let b = data[i + 2];
      
      // Calculate luminance for tonal adjustments
      const lum = 0.299 * r + 0.587 * g + 0.114 * b;
      const lumNorm = lum / 255;
      
      // 1. Exposure
      if (adjustments.exposure !== 0 && shouldApplyEffect('exposure')) {
        const exposureFactor = Math.pow(2, adjustments.exposure);
        r *= exposureFactor;
        g *= exposureFactor;
        b *= exposureFactor;
      }
      
      // 2. Offset
      if (adjustments.offset !== 0 && shouldApplyEffect('exposure')) {
        r += adjustments.offset * 2.55;
        g += adjustments.offset * 2.55;
        b += adjustments.offset * 2.55;
      }
      
      // 3. Gamma Correction
      if (adjustments.gammaCorrection !== 1.0 && shouldApplyEffect('exposure')) {
        r = 255 * Math.pow(r / 255, 1 / adjustments.gammaCorrection);
        g = 255 * Math.pow(g / 255, 1 / adjustments.gammaCorrection);
        b = 255 * Math.pow(b / 255, 1 / adjustments.gammaCorrection);
      }
      
      // 4. Color Balance
      if (shouldApplyEffect('colorBalance')) {
        // Shadows (dark areas)
        if (lumNorm < 0.33) {
          const shadowWeight = (0.33 - lumNorm) / 0.33;
          r += adjustments.shadowsCyan * shadowWeight * -0.5;
          r += adjustments.shadowsMagenta * shadowWeight * 0.3;
          r += adjustments.shadowsYellow * shadowWeight * 0.5;
          
          g += adjustments.shadowsCyan * shadowWeight * 0.3;
          g += adjustments.shadowsMagenta * shadowWeight * -0.5;
          g += adjustments.shadowsYellow * shadowWeight * 0.5;
          
          b += adjustments.shadowsCyan * shadowWeight * 0.5;
          b += adjustments.shadowsMagenta * shadowWeight * 0.3;
          b += adjustments.shadowsYellow * shadowWeight * -0.5;
        }
        
        // Midtones
        if (lumNorm >= 0.33 && lumNorm <= 0.66) {
          const midWeight = 1 - Math.abs(lumNorm - 0.5) * 3;
          r += adjustments.midtonesCyan * midWeight * -0.5;
          r += adjustments.midtonesMagenta * midWeight * 0.3;
          r += adjustments.midtonesYellow * midWeight * 0.5;
          
          g += adjustments.midtonesCyan * midWeight * 0.3;
          g += adjustments.midtonesMagenta * midWeight * -0.5;
          g += adjustments.midtonesYellow * midWeight * 0.5;
          
          b += adjustments.midtonesCyan * midWeight * 0.5;
          b += adjustments.midtonesMagenta * midWeight * 0.3;
          b += adjustments.midtonesYellow * midWeight * -0.5;
        }
        
        // Highlights (bright areas)
        if (lumNorm > 0.66) {
          const highlightWeight = (lumNorm - 0.66) / 0.34;
          r += adjustments.highlightsCyan * highlightWeight * -0.5;
          r += adjustments.highlightsMagenta * highlightWeight * 0.3;
          r += adjustments.highlightsYellow * highlightWeight * 0.5;
          
          g += adjustments.highlightsCyan * highlightWeight * 0.3;
          g += adjustments.highlightsMagenta * highlightWeight * -0.5;
          g += adjustments.highlightsYellow * highlightWeight * 0.5;
          
          b += adjustments.highlightsCyan * highlightWeight * 0.5;
          b += adjustments.highlightsMagenta * highlightWeight * 0.3;
          b += adjustments.highlightsYellow * highlightWeight * -0.5;
        }
      }
      
      // 5. Black & White
      if (bwEnabled && shouldApplyEffect('blackWhite')) {
        // Convert RGB to HSL to determine color range
        const max = Math.max(r, g, b);
        const min = Math.min(r, g, b);
        const l = (max + min) / 2;
        let h = 0;
        let s = 0;
        
        if (max !== min) {
          const d = max - min;
          s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
          
          if (max === r) {
            h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
          } else if (max === g) {
            h = ((b - r) / d + 2) / 6;
          } else {
            h = ((r - g) / d + 4) / 6;
          }
        }
        
        h = h * 360; // Convert to degrees
        
        // Determine which color range this pixel belongs to
        let colorWeight = 0;
        
        if (h >= 345 || h < 15) {
          // Reds
          colorWeight = adjustments.bwRed / 100;
        } else if (h >= 15 && h < 45) {
          // Oranges/Yellows
          colorWeight = adjustments.bwYellow / 100;
        } else if (h >= 45 && h < 75) {
          // Yellows
          colorWeight = adjustments.bwYellow / 100;
        } else if (h >= 75 && h < 155) {
          // Greens
          colorWeight = adjustments.bwGreen / 100;
        } else if (h >= 155 && h < 185) {
          // Cyans
          colorWeight = adjustments.bwCyan / 100;
        } else if (h >= 185 && h < 255) {
          // Blues
          colorWeight = adjustments.bwBlue / 100;
        } else if (h >= 255 && h < 345) {
          // Magentas
          colorWeight = adjustments.bwMagenta / 100;
        }
        
        // Calculate grayscale with color-specific weighting
        let gray = (0.299 * r + 0.587 * g + 0.114 * b) * colorWeight;
        
        // Clamp gray value
        gray = Math.max(0, Math.min(255, gray));
        
        r = g = b = gray;
        
        // Apply tint
        if (adjustments.bwTint !== 0) {
          const tintAmount = adjustments.bwTint * 0.8;
          if (adjustments.bwTint > 0) {
            // Warm tint (sepia)
            r += tintAmount;
            g += tintAmount * 0.7;
            b += tintAmount * 0.3;
          } else {
            // Cool tint (blue)
            r += tintAmount * 0.3;
            g += tintAmount * 0.5;
            b -= tintAmount;
          }
        }
      }
      
      // 6. Vibrance (smart saturation)
      if (adjustments.vibrance !== 0) {
        const avg = (r + g + b) / 3;
        const maxRGB = Math.max(r, g, b);
        const currentSat = maxRGB > 0 ? (maxRGB - avg) / maxRGB : 0;
        
        // Apply vibrance more to less saturated colors
        const vibranceFactor = (1 - currentSat) * (adjustments.vibrance / 100);
        
        r = avg + (r - avg) * (1 + vibranceFactor);
        g = avg + (g - avg) * (1 + vibranceFactor);
        b = avg + (b - avg) * (1 + vibranceFactor);
      }
      
      // 7. Saturation (uniform)
      if (adjustments.saturationVibrance !== 0) {
        const avg = (r + g + b) / 3;
        const satFactor = 1 + (adjustments.saturationVibrance / 100);
        
        r = avg + (r - avg) * satFactor;
        g = avg + (g - avg) * satFactor;
        b = avg + (b - avg) * satFactor;
      }
      
      // 8. Brightness
      if (adjustments.brightness !== 0) {
        const brightFactor = adjustments.brightness * 2.55;
        r += brightFactor;
        g += brightFactor;
        b += brightFactor;
      }
      
      // 9. Contrast
      if (adjustments.contrast !== 0) {
        const contrastFactor = (100 + adjustments.contrast) / 100;
        r = ((r / 255 - 0.5) * contrastFactor + 0.5) * 255;
        g = ((g / 255 - 0.5) * contrastFactor + 0.5) * 255;
        b = ((b / 255 - 0.5) * contrastFactor + 0.5) * 255;
      }
      
      // 10. Selective Color
      if (adjustments.scCyan !== 0 || adjustments.scMagenta !== 0 || adjustments.scYellow !== 0 || adjustments.scBlack !== 0) {
        // Convert RGB to HSL to determine color range
        const max = Math.max(r, g, b);
        const min = Math.min(r, g, b);
        const l = (max + min) / 2;
        let h = 0;
        
        if (max !== min) {
          const d = max - min;
          
          if (max === r) {
            h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
          } else if (max === g) {
            h = ((b - r) / d + 2) / 6;
          } else {
            h = ((r - g) / d + 4) / 6;
          }
        }
        
        h = h * 360;
        const lNorm = l / 255;
        
        // Determine if pixel is in selected color range
        let inRange = false;
        const range = adjustments.selectiveColorRange;
        
        if (range === 'reds' && (h >= 345 || h < 15)) inRange = true;
        else if (range === 'yellows' && h >= 45 && h < 75) inRange = true;
        else if (range === 'greens' && h >= 75 && h < 155) inRange = true;
        else if (range === 'cyans' && h >= 155 && h < 195) inRange = true;
        else if (range === 'blues' && h >= 195 && h < 255) inRange = true;
        else if (range === 'magentas' && h >= 255 && h < 345) inRange = true;
        else if (range === 'whites' && lNorm > 0.8) inRange = true;
        else if (range === 'neutrals' && lNorm >= 0.3 && lNorm <= 0.7) inRange = true;
        else if (range === 'blacks' && lNorm < 0.2) inRange = true;
        
        if (inRange) {
          // Apply CMYK adjustments
          const cyanAdj = adjustments.scCyan / 100;
          const magentaAdj = adjustments.scMagenta / 100;
          const yellowAdj = adjustments.scYellow / 100;
          const blackAdj = adjustments.scBlack / 100;
          
          r += (-cyanAdj * 50) + (magentaAdj * 30) + (yellowAdj * 50) - (blackAdj * 50);
          g += (cyanAdj * 30) + (-magentaAdj * 50) + (yellowAdj * 50) - (blackAdj * 50);
          b += (cyanAdj * 50) + (magentaAdj * 30) + (-yellowAdj * 50) - (blackAdj * 50);
        }
      }
      
      // 11. Photo Filter
      if (adjustments.photoFilterType !== 'none' && adjustments.filterDensity > 0) {
        const filterColors = {
          'warming85': [236, 138, 0],
          'warming81': [238, 206, 0],
          'cooling80': [0, 88, 238],
          'cooling82': [0, 206, 255],
          'red': [234, 28, 36],
          'orange': [247, 148, 29],
          'yellow': [255, 242, 0],
          'green': [57, 181, 74],
          'cyan': [0, 174, 239],
          'blue': [46, 49, 146],
          'violet': [146, 39, 143],
          'magenta': [236, 0, 140],
          'sepia': [162, 138, 101]
        };
        
        const filterColor = filterColors[adjustments.photoFilterType];
        if (filterColor) {
          const density = adjustments.filterDensity / 100;
          const origLum = 0.299 * r + 0.587 * g + 0.114 * b;
          
          // Blend with filter color
          r = r * (1 - density) + filterColor[0] * density;
          g = g * (1 - density) + filterColor[1] * density;
          b = b * (1 - density) + filterColor[2] * density;
          
          // Preserve luminosity if enabled
          if (adjustments.preserveLuminosity) {
            const newLum = 0.299 * r + 0.587 * g + 0.114 * b;
            const lumDiff = origLum - newLum;
            r += lumDiff;
            g += lumDiff;
            b += lumDiff;
          }
        }
      }
      
      // 12. Gradient Map
      if (adjustments.gradientMapPreset !== 'none' && adjustments.gradientOpacity > 0) {
        const gradients = {
          'duotone-blue': [[26, 26, 46], [22, 33, 62], [15, 52, 96], [83, 52, 131]],
          'duotone-red': [[44, 0, 62], [106, 5, 114], [171, 35, 70], [255, 107, 107]],
          'duotone-green': [[10, 61, 98], [30, 95, 116], [7, 153, 146], [56, 173, 169]],
          'sunset': [[44, 0, 62], [106, 5, 114], [255, 107, 107], [254, 202, 87]],
          'ocean': [[10, 61, 98], [30, 95, 116], [7, 153, 146], [72, 219, 251]],
          'forest': [[30, 58, 32], [45, 80, 22], [106, 176, 76], [186, 220, 88]],
          'fire': [[44, 0, 62], [106, 5, 114], [255, 99, 72], [254, 202, 87]],
          'purple-haze': [[44, 0, 62], [106, 5, 114], [165, 94, 234], [224, 86, 253]],
          'vintage': [[61, 53, 34], [107, 91, 58], [160, 140, 92], [212, 175, 55]],
          'cyberpunk': [[10, 14, 39], [30, 58, 138], [236, 72, 153], [251, 191, 36]]
        };
        
        const gradient = gradients[adjustments.gradientMapPreset];
        if (gradient) {
          const lum = 0.299 * r + 0.587 * g + 0.114 * b;
          const lumNorm = lum / 255;
          
          // Find position in gradient
          const pos = lumNorm * (gradient.length - 1);
          const idx = Math.floor(pos);
          const frac = pos - idx;
          
          const color1 = gradient[Math.min(idx, gradient.length - 1)];
          const color2 = gradient[Math.min(idx + 1, gradient.length - 1)];
          
          // Interpolate between gradient colors
          const gradR = color1[0] + (color2[0] - color1[0]) * frac;
          const gradG = color1[1] + (color2[1] - color1[1]) * frac;
          const gradB = color1[2] + (color2[2] - color1[2]) * frac;
          
          // Blend with original
          const opacity = adjustments.gradientOpacity / 100;
          r = r * (1 - opacity) + gradR * opacity;
          g = g * (1 - opacity) + gradG * opacity;
          b = b * (1 - opacity) + gradB * opacity;
        }
      }
      
      // 13. Channel Mixer
      if (adjustments.mixerRed !== 100 || adjustments.mixerGreen !== 0 || adjustments.mixerBlue !== 0 || adjustments.mixerConstant !== 0) {
        const origR = r;
        const origG = g;
        const origB = b;
        
        const mixR = adjustments.mixerRed / 100;
        const mixG = adjustments.mixerGreen / 100;
        const mixB = adjustments.mixerBlue / 100;
        const mixC = adjustments.mixerConstant * 2.55;
        
        if (adjustments.mixerOutputChannel === 'red') {
          r = origR * mixR + origG * mixG + origB * mixB + mixC;
        } else if (adjustments.mixerOutputChannel === 'green') {
          g = origR * mixR + origG * mixG + origB * mixB + mixC;
        } else if (adjustments.mixerOutputChannel === 'blue') {
          b = origR * mixR + origG * mixG + origB * mixB + mixC;
        }
      }
      
      // 14. Color Lookup (LUT)
      if (adjustments.lutPreset !== 'none' && adjustments.lutIntensity > 0) {
        const luts = {
          'cinematic': (r, g, b) => {
            r = r * 0.9 + 20;
            g = g * 0.95 + 10;
            b = b * 1.1 - 10;
            return [r, g, b];
          },
          'warm-vintage': (r, g, b) => {
            r = Math.min(255, r * 1.15 + 30);
            g = g * 1.05 + 15;
            b = b * 0.85 - 20;
            return [r, g, b];
          },
          'cool-blue': (r, g, b) => {
            r = r * 0.85 - 15;
            g = g * 0.95;
            b = Math.min(255, b * 1.2 + 25);
            return [r, g, b];
          },
          'high-contrast': (r, g, b) => {
            r = r < 128 ? r * 0.7 : r * 1.3;
            g = g < 128 ? g * 0.7 : g * 1.3;
            b = b < 128 ? b * 0.7 : b * 1.3;
            return [r, g, b];
          },
          'faded': (r, g, b) => {
            r = r * 0.8 + 40;
            g = g * 0.8 + 40;
            b = b * 0.8 + 40;
            return [r, g, b];
          },
          'golden-hour': (r, g, b) => {
            r = Math.min(255, r * 1.2 + 40);
            g = Math.min(255, g * 1.1 + 20);
            b = b * 0.8;
            return [r, g, b];
          },
          'moonlight': (r, g, b) => {
            r = r * 0.7;
            g = g * 0.85 + 10;
            b = Math.min(255, b * 1.3 + 30);
            return [r, g, b];
          },
          'dramatic': (r, g, b) => {
            const lum = 0.299 * r + 0.587 * g + 0.114 * b;
            const factor = lum < 128 ? 0.6 : 1.4;
            r *= factor;
            g *= factor;
            b *= factor;
            return [r, g, b];
          },
          'soft-pastel': (r, g, b) => {
            r = r * 0.9 + 50;
            g = g * 0.9 + 50;
            b = b * 0.9 + 50;
            return [r, g, b];
          },
          'noir': (r, g, b) => {
            const gray = 0.299 * r + 0.587 * g + 0.114 * b;
            const contrast = (gray - 128) * 1.5 + 128;
            r = g = b = contrast;
            return [r, g, b];
          }
        };
        
        const lutFunc = luts[adjustments.lutPreset];
        if (lutFunc) {
          const [lutR, lutG, lutB] = lutFunc(r, g, b);
          const intensity = adjustments.lutIntensity / 100;
          r = r * (1 - intensity) + lutR * intensity;
          g = g * (1 - intensity) + lutG * intensity;
          b = b * (1 - intensity) + lutB * intensity;
        }
      }
      
      // 15. Invert
      if (adjustments.invertEnabled) {
        r = 255 - r;
        g = 255 - g;
        b = 255 - b;
      }
      
      // 16. Threshold
      if (adjustments.thresholdEnabled) {
        const lum = 0.299 * r + 0.587 * g + 0.114 * b;
        const value = lum >= adjustments.thresholdLevel ? 255 : 0;
        r = g = b = value;
      }
      
      // 17. Posterize
      if (adjustments.posterizeEnabled) {
        const levels = adjustments.posterizeLevels;
        const step = 255 / (levels - 1);
        r = Math.round(r / step) * step;
        g = Math.round(g / step) * step;
        b = Math.round(b / step) * step;
      }
      
      // Clamp values
      data[i] = Math.max(0, Math.min(255, r));
      data[i + 1] = Math.max(0, Math.min(255, g));
      data[i + 2] = Math.max(0, Math.min(255, b));
    }
    
    tempCtx.putImageData(imageData, 0, 0);
    previewImage.src = tempCanvas.toDataURL();
    
    // Apply CSS filters for remaining adjustments
    const cssFilters = [];
    
    if (adjustments.saturation !== 0 && shouldApplyEffect('hueSaturation')) {
      cssFilters.push(`saturate(${100 + adjustments.saturation}%)`);
    }
    
    if (adjustments.hue !== 0 && shouldApplyEffect('hueSaturation')) {
      cssFilters.push(`hue-rotate(${adjustments.hue}deg)`);
    }
    
    if (adjustments.lightness !== 0 && shouldApplyEffect('hueSaturation')) {
      cssFilters.push(`brightness(${100 + adjustments.lightness}%)`);
    }
    
    if (adjustments.temperature !== 0 && shouldApplyEffect('whiteBalance')) {
      const tempValue = Math.abs(adjustments.temperature) / 100;
      if (adjustments.temperature > 0) {
        cssFilters.push(`sepia(${tempValue * 0.3})`);
      } else {
        cssFilters.push(`hue-rotate(${adjustments.temperature * 0.5}deg)`);
      }
    }
    
    if (adjustments.tint !== 0 && shouldApplyEffect('whiteBalance')) {
      cssFilters.push(`hue-rotate(${adjustments.tint * 0.3}deg)`);
    }
    
    // Blur
    if (adjustments.blurAmount > 0) {
      cssFilters.push(`blur(${adjustments.blurAmount}px)`);
    }
    
    previewImage.style.filter = cssFilters.join(' ');
    
    // Apply transform for flip and rotate
    const transforms = [];
    
    if (adjustments.flipHorizontal) {
      transforms.push('scaleX(-1)');
    }
    
    if (adjustments.flipVertical) {
      transforms.push('scaleY(-1)');
    }
    
    if (adjustments.rotateAngle !== 0) {
      transforms.push(`rotate(${adjustments.rotateAngle}deg)`);
    }
    
    previewImage.style.transform = transforms.join(' ');
  };
  
  const reader = new FileReader();
  reader.onload = (e) => {
    img.src = e.target.result;
  };
  reader.readAsDataURL(selectedFile);
}

// Update brightness/contrast comparison bars
function updateComparisonBars() {
  const afterBarFill = document.getElementById('afterBarFill');
  if (!afterBarFill) return;
  
  const brightness = 50 + (adjustments.brightness / 2);
  const contrast = Math.abs(adjustments.contrast);
  
  afterBarFill.style.width = `${brightness}%`;
  
  if (adjustments.contrast > 0) {
    afterBarFill.style.background = `linear-gradient(to right, #000, #fff)`;
  } else if (adjustments.contrast < 0) {
    afterBarFill.style.background = `linear-gradient(to right, #555, #aaa)`;
  } else {
    afterBarFill.style.background = `linear-gradient(to right, #333, #999)`;
  }
}

// Brightness slider
if (brightnessSlider) {
  brightnessSlider.addEventListener('input', (e) => {
    adjustments.brightness = parseInt(e.target.value);
    document.getElementById('brightnessValue').textContent = adjustments.brightness;
    applyFilters();
    updateComparisonBars();
  });
}

// Contrast slider
if (contrastSlider) {
  contrastSlider.addEventListener('input', (e) => {
    adjustments.contrast = parseInt(e.target.value);
    document.getElementById('contrastValue').textContent = adjustments.contrast;
    applyFilters();
    updateComparisonBars();
  });
}

// Saturation slider
saturationSlider.addEventListener('input', (e) => {
  adjustments.saturation = parseInt(e.target.value);
  document.getElementById('saturationValue').textContent = adjustments.saturation;
  applyFilters();
  updateColorPreview();
});

// Hue slider
hueSlider.addEventListener('input', (e) => {
  adjustments.hue = parseInt(e.target.value);
  document.getElementById('hueValue').textContent = adjustments.hue + '°';
  applyFilters();
  updateColorPreview();
});

// Lightness slider
if (lightnessSlider) {
  lightnessSlider.addEventListener('input', (e) => {
    adjustments.lightness = parseInt(e.target.value);
    document.getElementById('lightnessValue').textContent = adjustments.lightness;
    applyFilters();
    updateColorPreview();
  });
}

// Temperature slider
if (temperatureSlider) {
  temperatureSlider.addEventListener('input', (e) => {
    adjustments.temperature = parseInt(e.target.value);
    document.getElementById('temperatureValue').textContent = adjustments.temperature;
    applyFilters();
  });
}

// Tint slider
if (tintSlider) {
  tintSlider.addEventListener('input', (e) => {
    adjustments.tint = parseInt(e.target.value);
    document.getElementById('tintValue').textContent = adjustments.tint;
    applyFilters();
  });
}

// Reset adjustments
resetAdjustmentsBtn.addEventListener('click', () => {
  adjustments = {
    brightness: 0,
    contrast: 0,
    saturation: 0,
    hue: 0,
    lightness: 0,
    temperature: 0,
    tint: 0
  };
  
  if (brightnessSlider) brightnessSlider.value = 0;
  if (contrastSlider) contrastSlider.value = 0;
  saturationSlider.value = 0;
  hueSlider.value = 0;
  if (lightnessSlider) lightnessSlider.value = 0;
  if (temperatureSlider) temperatureSlider.value = 0;
  if (tintSlider) tintSlider.value = 0;
  
  if (document.getElementById('brightnessValue')) document.getElementById('brightnessValue').textContent = '0';
  if (document.getElementById('contrastValue')) document.getElementById('contrastValue').textContent = '0';
  document.getElementById('saturationValue').textContent = '0';
  document.getElementById('hueValue').textContent = '0°';
  if (document.getElementById('lightnessValue')) document.getElementById('lightnessValue').textContent = '0';
  if (document.getElementById('temperatureValue')) document.getElementById('temperatureValue').textContent = '0';
  if (document.getElementById('tintValue')) document.getElementById('tintValue').textContent = '0';
  
  // Reset curves
  curvePoints = [
    { x: 0, y: 0 },
    { x: 255, y: 255 }
  ];
  if (curveCanvas) drawCurve();
  
  // Reset Black & White
  bwEnabled = false;
  if (bwToggle) bwToggle.checked = false;
  
  // Reset all B&W sliders to default
  adjustments.bwRed = 40;
  adjustments.bwYellow = 60;
  adjustments.bwGreen = 40;
  adjustments.bwCyan = 60;
  adjustments.bwBlue = 20;
  adjustments.bwMagenta = 80;
  adjustments.bwTint = 0;
  
  if (document.getElementById('bwRedSlider')) {
    document.getElementById('bwRedSlider').value = 40;
    document.getElementById('bwRedValue').textContent = '40';
  }
  if (document.getElementById('bwYellowSlider')) {
    document.getElementById('bwYellowSlider').value = 60;
    document.getElementById('bwYellowValue').textContent = '60';
  }
  if (document.getElementById('bwGreenSlider')) {
    document.getElementById('bwGreenSlider').value = 40;
    document.getElementById('bwGreenValue').textContent = '40';
  }
  if (document.getElementById('bwCyanSlider')) {
    document.getElementById('bwCyanSlider').value = 60;
    document.getElementById('bwCyanValue').textContent = '60';
  }
  if (document.getElementById('bwBlueSlider')) {
    document.getElementById('bwBlueSlider').value = 20;
    document.getElementById('bwBlueValue').textContent = '20';
  }
  if (document.getElementById('bwMagentaSlider')) {
    document.getElementById('bwMagentaSlider').value = 80;
    document.getElementById('bwMagentaValue').textContent = '80';
  }
  if (document.getElementById('bwTintSlider')) {
    document.getElementById('bwTintSlider').value = 0;
    document.getElementById('bwTintValue').textContent = '0';
  }
  
  // Reset blur, flip, rotate
  adjustments.blurAmount = 0;
  adjustments.flipHorizontal = false;
  adjustments.flipVertical = false;
  adjustments.rotateAngle = 0;
  
  if (document.getElementById('blurAmountSlider')) {
    document.getElementById('blurAmountSlider').value = 0;
    document.getElementById('blurAmountValue').textContent = '0';
  }
  
  if (document.getElementById('rotateAngleSlider')) {
    document.getElementById('rotateAngleSlider').value = 0;
    document.getElementById('rotateAngleValue').textContent = '0°';
  }
  
  // Reset image to original
  if (originalImageData) {
    previewImage.src = originalImageData;
  }
  previewImage.style.filter = '';
  previewImage.style.transform = '';
  updateColorPreview();
  updateComparisonBars();
});

// Curves functionality
const curveCanvas = document.getElementById('curveCanvas');
const curveCtx = curveCanvas ? curveCanvas.getContext('2d') : null;
const curveChannelSelect = document.getElementById('curveChannel');
const curveInput = document.getElementById('curveInput');
const curveOutput = document.getElementById('curveOutput');

let curvePoints = [
  { x: 0, y: 0 },
  { x: 255, y: 255 }
];
let selectedPoint = -1;
let isDraggingCurve = false;
let currentChannel = 'rgb';
let histogram = {
  red: new Array(256).fill(0),
  green: new Array(256).fill(0),
  blue: new Array(256).fill(0),
  luminance: new Array(256).fill(0)
};

// Levels values
let levelsValues = {
  channel: 'rgb',
  shadows: 0,
  midtones: 1.0,
  highlights: 255,
  outputBlack: 0,
  outputWhite: 255
};

// Calculate histogram from image
function calculateHistogram() {
  if (!previewImage.src || !previewImage.complete) return;
  
  const tempCanvas = document.createElement('canvas');
  const tempCtx = tempCanvas.getContext('2d');
  
  const img = new Image();
  img.crossOrigin = 'anonymous';
  
  img.onload = () => {
    // Resize for performance (max 500px)
    const maxSize = 500;
    let width = img.width;
    let height = img.height;
    
    if (width > maxSize || height > maxSize) {
      if (width > height) {
        height = (height / width) * maxSize;
        width = maxSize;
      } else {
        width = (width / height) * maxSize;
        height = maxSize;
      }
    }
    
    tempCanvas.width = width;
    tempCanvas.height = height;
    tempCtx.drawImage(img, 0, 0, width, height);
    
    const imageData = tempCtx.getImageData(0, 0, width, height);
    const data = imageData.data;
    
    // Reset histogram
    histogram.red = new Array(256).fill(0);
    histogram.green = new Array(256).fill(0);
    histogram.blue = new Array(256).fill(0);
    histogram.luminance = new Array(256).fill(0);
    
    // Calculate histogram
    for (let i = 0; i < data.length; i += 4) {
      const r = data[i];
      const g = data[i + 1];
      const b = data[i + 2];
      
      histogram.red[r]++;
      histogram.green[g]++;
      histogram.blue[b]++;
      
      // Calculate luminance (perceived brightness)
      const lum = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
      histogram.luminance[lum]++;
    }
    
    // Normalize histogram
    const totalPixels = (width * height);
    const maxRed = Math.max(...histogram.red);
    const maxGreen = Math.max(...histogram.green);
    const maxBlue = Math.max(...histogram.blue);
    const maxLum = Math.max(...histogram.luminance);
    
    for (let i = 0; i < 256; i++) {
      histogram.red[i] = histogram.red[i] / maxRed;
      histogram.green[i] = histogram.green[i] / maxGreen;
      histogram.blue[i] = histogram.blue[i] / maxBlue;
      histogram.luminance[i] = histogram.luminance[i] / maxLum;
    }
    
    // Redraw curve with histogram
    drawCurve();
  };
  
  img.src = previewImage.src;
}

// Draw histogram on curve canvas
function drawHistogram() {
  if (!curveCtx) return;
  
  const width = curveCanvas.width;
  const height = curveCanvas.height;
  
  // Choose which histogram to display
  let histData;
  let color;
  
  if (currentChannel === 'rgb') {
    histData = histogram.luminance;
    color = 'rgba(150, 150, 150, 0.3)';
  } else if (currentChannel === 'red') {
    histData = histogram.red;
    color = 'rgba(255, 68, 68, 0.3)';
  } else if (currentChannel === 'green') {
    histData = histogram.green;
    color = 'rgba(68, 255, 68, 0.3)';
  } else if (currentChannel === 'blue') {
    histData = histogram.blue;
    color = 'rgba(68, 68, 255, 0.3)';
  }
  
  // Draw histogram bars
  curveCtx.fillStyle = color;
  const barWidth = width / 256;
  
  for (let i = 0; i < 256; i++) {
    const barHeight = histData[i] * (height * 0.6); // Use 60% of height
    const x = (i / 255) * width;
    const y = height - barHeight;
    
    curveCtx.fillRect(x, y, barWidth, barHeight);
  }
}

// Draw curve canvas
function drawCurve() {
  if (!curveCtx) return;
  
  const width = curveCanvas.width;
  const height = curveCanvas.height;
  
  // Clear canvas
  curveCtx.fillStyle = '#1e1e1e';
  curveCtx.fillRect(0, 0, width, height);
  
  // Draw histogram first (behind everything)
  drawHistogram();
  
  // Draw grid
  curveCtx.strokeStyle = '#2d2d2d';
  curveCtx.lineWidth = 1;
  for (let i = 0; i <= 4; i++) {
    const pos = (width / 4) * i;
    curveCtx.beginPath();
    curveCtx.moveTo(pos, 0);
    curveCtx.lineTo(pos, height);
    curveCtx.stroke();
    curveCtx.beginPath();
    curveCtx.moveTo(0, pos);
    curveCtx.lineTo(width, pos);
    curveCtx.stroke();
  }
  
  // Draw diagonal reference line
  curveCtx.strokeStyle = '#3c3c3c';
  curveCtx.lineWidth = 1;
  curveCtx.beginPath();
  curveCtx.moveTo(0, height);
  curveCtx.lineTo(width, 0);
  curveCtx.stroke();
  
  // Draw curve
  curveCtx.strokeStyle = currentChannel === 'rgb' ? '#4a9eff' : 
                         currentChannel === 'red' ? '#ff4444' :
                         currentChannel === 'green' ? '#44ff44' : '#4444ff';
  curveCtx.lineWidth = 2;
  curveCtx.beginPath();
  
  const sortedPoints = [...curvePoints].sort((a, b) => a.x - b.x);
  
  for (let i = 0; i < sortedPoints.length; i++) {
    const point = sortedPoints[i];
    const x = (point.x / 255) * width;
    const y = height - (point.y / 255) * height;
    
    if (i === 0) {
      curveCtx.moveTo(x, y);
    } else {
      curveCtx.lineTo(x, y);
    }
  }
  curveCtx.stroke();
  
  // Draw control points
  sortedPoints.forEach((point, index) => {
    const x = (point.x / 255) * width;
    const y = height - (point.y / 255) * height;
    
    curveCtx.fillStyle = index === selectedPoint ? '#ffffff' : '#4a9eff';
    curveCtx.beginPath();
    curveCtx.arc(x, y, 5, 0, Math.PI * 2);
    curveCtx.fill();
    
    curveCtx.strokeStyle = '#1e1e1e';
    curveCtx.lineWidth = 2;
    curveCtx.stroke();
  });
}

// Get mouse position on canvas
function getCanvasMousePos(e) {
  const rect = curveCanvas.getBoundingClientRect();
  const scaleX = curveCanvas.width / rect.width;
  const scaleY = curveCanvas.height / rect.height;
  
  return {
    x: (e.clientX - rect.left) * scaleX,
    y: (e.clientY - rect.top) * scaleY
  };
}

// Canvas mouse events
if (curveCanvas) {
  curveCanvas.addEventListener('mousedown', (e) => {
    const pos = getCanvasMousePos(e);
    const width = curveCanvas.width;
    const height = curveCanvas.height;
    
    // Check if clicking on existing point
    selectedPoint = -1;
    for (let i = 0; i < curvePoints.length; i++) {
      const point = curvePoints[i];
      const x = (point.x / 255) * width;
      const y = height - (point.y / 255) * height;
      
      const distance = Math.sqrt(Math.pow(pos.x - x, 2) + Math.pow(pos.y - y, 2));
      if (distance < 10) {
        selectedPoint = i;
        isDraggingCurve = true;
        break;
      }
    }
    
    // Add new point if not clicking on existing one
    if (selectedPoint === -1 && curvePoints.length < 10) {
      const newX = Math.round((pos.x / width) * 255);
      const newY = Math.round(((height - pos.y) / height) * 255);
      
      curvePoints.push({ x: newX, y: newY });
      selectedPoint = curvePoints.length - 1;
      isDraggingCurve = true;
    }
    
    drawCurve();
  });
  
  curveCanvas.addEventListener('mousemove', (e) => {
    const pos = getCanvasMousePos(e);
    const width = curveCanvas.width;
    const height = curveCanvas.height;
    
    const inputVal = Math.round((pos.x / width) * 255);
    const outputVal = Math.round(((height - pos.y) / height) * 255);
    
    curveInput.textContent = Math.max(0, Math.min(255, inputVal));
    curveOutput.textContent = Math.max(0, Math.min(255, outputVal));
    
    if (isDraggingCurve && selectedPoint !== -1) {
      const point = curvePoints[selectedPoint];
      
      // Don't allow moving first and last points horizontally
      if (selectedPoint === 0 || selectedPoint === curvePoints.length - 1) {
        point.y = Math.max(0, Math.min(255, outputVal));
      } else {
        point.x = Math.max(0, Math.min(255, inputVal));
        point.y = Math.max(0, Math.min(255, outputVal));
      }
      
      drawCurve();
      applyCurveFilter();
    }
  });
  
  curveCanvas.addEventListener('mouseup', () => {
    isDraggingCurve = false;
    selectedPoint = -1;
  });
  
  curveCanvas.addEventListener('mouseleave', () => {
    isDraggingCurve = false;
    curveInput.textContent = '-';
    curveOutput.textContent = '-';
  });
  
  // Double click to remove point
  curveCanvas.addEventListener('dblclick', (e) => {
    const pos = getCanvasMousePos(e);
    const width = curveCanvas.width;
    const height = curveCanvas.height;
    
    for (let i = 1; i < curvePoints.length - 1; i++) {
      const point = curvePoints[i];
      const x = (point.x / 255) * width;
      const y = height - (point.y / 255) * height;
      
      const distance = Math.sqrt(Math.pow(pos.x - x, 2) + Math.pow(pos.y - y, 2));
      if (distance < 10) {
        curvePoints.splice(i, 1);
        drawCurve();
        applyCurveFilter();
        break;
      }
    }
  });
}

// Build curve lookup table
function buildCurveLUT() {
  const lut = new Array(256);
  const sortedPoints = [...curvePoints].sort((a, b) => a.x - b.x);
  
  for (let i = 0; i < 256; i++) {
    // Find the two points to interpolate between
    let x1 = 0, y1 = 0, x2 = 255, y2 = 255;
    
    for (let j = 0; j < sortedPoints.length - 1; j++) {
      if (i >= sortedPoints[j].x && i <= sortedPoints[j + 1].x) {
        x1 = sortedPoints[j].x;
        y1 = sortedPoints[j].y;
        x2 = sortedPoints[j + 1].x;
        y2 = sortedPoints[j + 1].y;
        break;
      }
    }
    
    // Linear interpolation
    if (x2 === x1) {
      lut[i] = y1;
    } else {
      const t = (i - x1) / (x2 - x1);
      lut[i] = Math.round(y1 + t * (y2 - y1));
    }
    
    // Clamp values
    lut[i] = Math.max(0, Math.min(255, lut[i]));
  }
  
  return lut;
}

// Apply curve filter to image
function applyCurveFilter() {
  if (!previewImage.src || !previewImage.complete) {
    applyFilters();
    return;
  }
  
  // Create a temporary canvas to process the image
  const tempCanvas = document.createElement('canvas');
  const tempCtx = tempCanvas.getContext('2d');
  
  // Load original image
  const img = new Image();
  img.crossOrigin = 'anonymous';
  
  img.onload = () => {
    tempCanvas.width = img.width;
    tempCanvas.height = img.height;
    
    // Draw original image
    tempCtx.drawImage(img, 0, 0);
    
    // Get image data
    const imageData = tempCtx.getImageData(0, 0, tempCanvas.width, tempCanvas.height);
    const data = imageData.data;
    
    // Build lookup table
    const lut = buildCurveLUT();
    
    // Apply curve to each pixel
    for (let i = 0; i < data.length; i += 4) {
      if (currentChannel === 'rgb') {
        data[i] = lut[data[i]];         // Red
        data[i + 1] = lut[data[i + 1]]; // Green
        data[i + 2] = lut[data[i + 2]]; // Blue
      } else if (currentChannel === 'red') {
        data[i] = lut[data[i]];
      } else if (currentChannel === 'green') {
        data[i + 1] = lut[data[i + 1]];
      } else if (currentChannel === 'blue') {
        data[i + 2] = lut[data[i + 2]];
      }
    }
    
    // Put modified image data back
    tempCtx.putImageData(imageData, 0, 0);
    
    // Update preview image with processed version
    previewImage.src = tempCanvas.toDataURL();
    
    // Recalculate histogram after curve adjustment
    setTimeout(() => {
      calculateHistogram();
    }, 100);
    
    // Apply other filters on top
    applyFilters();
  };
  
  img.onerror = () => {
    // If curve processing fails, just apply regular filters
    applyFilters();
  };
  
  // Get the original image source (before any filters)
  if (selectedFile) {
    const reader = new FileReader();
    reader.onload = (e) => {
      img.src = e.target.result;
    };
    reader.readAsDataURL(selectedFile);
  } else {
    img.src = previewImage.src;
  }
}

// Curve presets
const presetButtons = document.querySelectorAll('.preset-btn');
presetButtons.forEach(btn => {
  btn.addEventListener('click', () => {
    const preset = btn.getAttribute('data-preset');
    
    switch (preset) {
      case 'linear':
        curvePoints = [{ x: 0, y: 0 }, { x: 255, y: 255 }];
        break;
      case 'contrast':
        curvePoints = [
          { x: 0, y: 20 },
          { x: 128, y: 128 },
          { x: 255, y: 235 }
        ];
        break;
      case 'brighten':
        curvePoints = [
          { x: 0, y: 30 },
          { x: 255, y: 255 }
        ];
        break;
      case 'darken':
        curvePoints = [
          { x: 0, y: 0 },
          { x: 255, y: 225 }
        ];
        break;
      case 'scurve':
        curvePoints = [
          { x: 0, y: 0 },
          { x: 64, y: 45 },
          { x: 192, y: 210 },
          { x: 255, y: 255 }
        ];
        break;
    }
    
    drawCurve();
    applyCurveFilter();
  });
});

// Channel select
if (curveChannelSelect) {
  curveChannelSelect.addEventListener('change', (e) => {
    currentChannel = e.target.value;
    drawCurve(); // Redraw with new channel histogram
  });
}

// Initialize curve
if (curveCanvas) {
  drawCurve();
}

// Levels functionality
const levelsCanvas = document.getElementById('levelsCanvas');
const levelsCtx = levelsCanvas ? levelsCanvas.getContext('2d') : null;
const levelsChannelSelect = document.getElementById('levelsChannel');
const shadowsSlider = document.getElementById('shadowsSlider');
const shadowsInput = document.getElementById('shadowsInput');
const midtonesSlider = document.getElementById('midtonesSlider');
const midtonesInput = document.getElementById('midtonesInput');
const highlightsSlider = document.getElementById('highlightsSlider');
const highlightsInput = document.getElementById('highlightsInput');
const outputBlackSlider = document.getElementById('outputBlackSlider');
const outputWhiteSlider = document.getElementById('outputWhiteSlider');
const autoLevelsBtn = document.getElementById('autoLevelsBtn');

// Draw levels histogram
function drawLevelsHistogram() {
  if (!levelsCtx) return;
  
  const width = levelsCanvas.width;
  const height = levelsCanvas.height;
  
  // Clear canvas
  levelsCtx.fillStyle = '#1e1e1e';
  levelsCtx.fillRect(0, 0, width, height);
  
  // Choose histogram data
  let histData;
  let color;
  
  if (levelsValues.channel === 'rgb') {
    histData = histogram.luminance;
    color = 'rgba(200, 200, 200, 0.8)';
  } else if (levelsValues.channel === 'red') {
    histData = histogram.red;
    color = 'rgba(255, 68, 68, 0.8)';
  } else if (levelsValues.channel === 'green') {
    histData = histogram.green;
    color = 'rgba(68, 255, 68, 0.8)';
  } else if (levelsValues.channel === 'blue') {
    histData = histogram.blue;
    color = 'rgba(68, 68, 255, 0.8)';
  }
  
  // Draw histogram
  levelsCtx.fillStyle = color;
  const barWidth = width / 256;
  
  for (let i = 0; i < 256; i++) {
    const barHeight = histData[i] * (height - 10);
    const x = (i / 255) * width;
    const y = height - barHeight;
    
    levelsCtx.fillRect(x, y, barWidth, barHeight);
  }
  
  // Draw level markers
  const shadowX = (levelsValues.shadows / 255) * width;
  const highlightX = (levelsValues.highlights / 255) * width;
  
  // Shadow marker (black)
  levelsCtx.fillStyle = '#000000';
  levelsCtx.strokeStyle = '#4a9eff';
  levelsCtx.lineWidth = 2;
  levelsCtx.beginPath();
  levelsCtx.moveTo(shadowX, height);
  levelsCtx.lineTo(shadowX - 6, height - 10);
  levelsCtx.lineTo(shadowX + 6, height - 10);
  levelsCtx.closePath();
  levelsCtx.fill();
  levelsCtx.stroke();
  
  // Highlight marker (white)
  levelsCtx.fillStyle = '#ffffff';
  levelsCtx.beginPath();
  levelsCtx.moveTo(highlightX, height);
  levelsCtx.lineTo(highlightX - 6, height - 10);
  levelsCtx.lineTo(highlightX + 6, height - 10);
  levelsCtx.closePath();
  levelsCtx.fill();
  levelsCtx.stroke();
  
  // Midtone marker (gray)
  const midX = shadowX + (highlightX - shadowX) * 0.5;
  levelsCtx.fillStyle = '#888888';
  levelsCtx.beginPath();
  levelsCtx.moveTo(midX, height);
  levelsCtx.lineTo(midX - 5, height - 8);
  levelsCtx.lineTo(midX + 5, height - 8);
  levelsCtx.closePath();
  levelsCtx.fill();
  levelsCtx.stroke();
}

// Apply levels adjustment
function applyLevels() {
  if (!previewImage.src || !previewImage.complete || !selectedFile) {
    return;
  }
  
  const tempCanvas = document.createElement('canvas');
  const tempCtx = tempCanvas.getContext('2d');
  
  const img = new Image();
  img.crossOrigin = 'anonymous';
  
  img.onload = () => {
    tempCanvas.width = img.width;
    tempCanvas.height = img.height;
    tempCtx.drawImage(img, 0, 0);
    
    const imageData = tempCtx.getImageData(0, 0, tempCanvas.width, tempCanvas.height);
    const data = imageData.data;
    
    const { shadows, midtones, highlights, outputBlack, outputWhite } = levelsValues;
    
    // Build lookup table
    const lut = new Array(256);
    for (let i = 0; i < 256; i++) {
      // Input levels adjustment
      let value = (i - shadows) / (highlights - shadows);
      value = Math.max(0, Math.min(1, value));
      
      // Gamma (midtones) adjustment
      value = Math.pow(value, 1 / midtones);
      
      // Output levels adjustment
      value = outputBlack + value * (outputWhite - outputBlack);
      
      lut[i] = Math.max(0, Math.min(255, Math.round(value)));
    }
    
    // Apply levels
    for (let i = 0; i < data.length; i += 4) {
      if (levelsValues.channel === 'rgb') {
        data[i] = lut[data[i]];
        data[i + 1] = lut[data[i + 1]];
        data[i + 2] = lut[data[i + 2]];
      } else if (levelsValues.channel === 'red') {
        data[i] = lut[data[i]];
      } else if (levelsValues.channel === 'green') {
        data[i + 1] = lut[data[i + 1]];
      } else if (levelsValues.channel === 'blue') {
        data[i + 2] = lut[data[i + 2]];
      }
    }
    
    tempCtx.putImageData(imageData, 0, 0);
    previewImage.src = tempCanvas.toDataURL();
    
    // Recalculate histogram
    setTimeout(() => {
      calculateHistogram();
    }, 100);
    
    applyFilters();
  };
  
  const reader = new FileReader();
  reader.onload = (e) => {
    img.src = e.target.result;
  };
  reader.readAsDataURL(selectedFile);
}

// Levels event listeners
if (shadowsSlider && shadowsInput) {
  shadowsSlider.addEventListener('input', (e) => {
    levelsValues.shadows = parseInt(e.target.value);
    shadowsInput.value = levelsValues.shadows;
    drawLevelsHistogram();
    applyLevels();
  });
  
  shadowsInput.addEventListener('input', (e) => {
    levelsValues.shadows = parseInt(e.target.value);
    shadowsSlider.value = levelsValues.shadows;
    drawLevelsHistogram();
    applyLevels();
  });
}

if (midtonesSlider && midtonesInput) {
  midtonesSlider.addEventListener('input', (e) => {
    levelsValues.midtones = parseFloat(e.target.value);
    midtonesInput.value = levelsValues.midtones.toFixed(2);
    drawLevelsHistogram();
    applyLevels();
  });
  
  midtonesInput.addEventListener('input', (e) => {
    levelsValues.midtones = parseFloat(e.target.value);
    midtonesSlider.value = levelsValues.midtones;
    drawLevelsHistogram();
    applyLevels();
  });
}

if (highlightsSlider && highlightsInput) {
  highlightsSlider.addEventListener('input', (e) => {
    levelsValues.highlights = parseInt(e.target.value);
    highlightsInput.value = levelsValues.highlights;
    drawLevelsHistogram();
    applyLevels();
  });
  
  highlightsInput.addEventListener('input', (e) => {
    levelsValues.highlights = parseInt(e.target.value);
    highlightsSlider.value = levelsValues.highlights;
    drawLevelsHistogram();
    applyLevels();
  });
}

if (outputBlackSlider) {
  outputBlackSlider.addEventListener('input', (e) => {
    levelsValues.outputBlack = parseInt(e.target.value);
    document.getElementById('outputBlackValue').textContent = levelsValues.outputBlack;
    applyLevels();
  });
}

if (outputWhiteSlider) {
  outputWhiteSlider.addEventListener('input', (e) => {
    levelsValues.outputWhite = parseInt(e.target.value);
    document.getElementById('outputWhiteValue').textContent = levelsValues.outputWhite;
    applyLevels();
  });
}

if (levelsChannelSelect) {
  levelsChannelSelect.addEventListener('change', (e) => {
    levelsValues.channel = e.target.value;
    drawLevelsHistogram();
  });
}

// Auto Levels
if (autoLevelsBtn) {
  autoLevelsBtn.addEventListener('click', () => {
    const histData = levelsValues.channel === 'rgb' ? histogram.luminance :
                     levelsValues.channel === 'red' ? histogram.red :
                     levelsValues.channel === 'green' ? histogram.green :
                     histogram.blue;
    
    // Find first and last non-zero values
    let firstNonZero = 0;
    let lastNonZero = 255;
    
    for (let i = 0; i < 256; i++) {
      if (histData[i] > 0.01) {
        firstNonZero = i;
        break;
      }
    }
    
    for (let i = 255; i >= 0; i--) {
      if (histData[i] > 0.01) {
        lastNonZero = i;
        break;
      }
    }
    
    // Apply auto levels
    levelsValues.shadows = firstNonZero;
    levelsValues.highlights = lastNonZero;
    levelsValues.midtones = 1.0;
    
    shadowsSlider.value = firstNonZero;
    shadowsInput.value = firstNonZero;
    highlightsSlider.value = lastNonZero;
    highlightsInput.value = lastNonZero;
    midtonesSlider.value = 1.0;
    midtonesInput.value = '1.00';
    
    drawLevelsHistogram();
    applyLevels();
    
    showMessage('✓ Auto Levels applied!', 'success');
  });
}

// Initialize levels histogram
if (levelsCanvas) {
  drawLevelsHistogram();
}

// Collapsible panels
document.addEventListener('DOMContentLoaded', () => {
  const panelHeaders = document.querySelectorAll('.panel-header');
  
  // Collapse all panels on load
  panelHeaders.forEach(header => {
    const panelId = header.getAttribute('data-panel');
    const content = document.getElementById(panelId);
    
    if (content) {
      header.classList.add('collapsed');
      content.classList.add('collapsed');
    }
    
    // Add click handler
    header.addEventListener('click', () => {
      if (content) {
        header.classList.toggle('collapsed');
        content.classList.toggle('collapsed');
      }
    });
  });
});

// Zoom functions
function updateZoom() {
  const transform = `scale(${currentZoom})`;
  previewImage.style.transform = transform;
  zoomLevel.textContent = `${Math.round(currentZoom * 100)}%`;
}

function zoomIn() {
  if (currentZoom < 10) {
    currentZoom = Math.min(10, currentZoom + 0.01);
    updateZoom();
  }
}

function zoomOut() {
  if (currentZoom > 0.1) {
    currentZoom = Math.max(0.1, currentZoom - 0.01);
    updateZoom();
  }
}

function zoomReset() {
  const img = new Image();
  img.onload = () => {
    fitImageToCanvas(img.width, img.height);
  };
  img.src = previewImage.src;
}

// Zoom buttons
zoomInBtn.addEventListener('click', zoomIn);
zoomOutBtn.addEventListener('click', zoomOut);
zoomResetBtn.addEventListener('click', zoomReset);

// Mouse wheel zoom
imageContainer.addEventListener('wheel', (e) => {
  e.preventDefault();
  
  const zoomSpeed = 0.05;
  
  if (e.deltaY < 0) {
    if (currentZoom < 10) {
      currentZoom = Math.min(10, currentZoom + zoomSpeed);
      updateZoom();
    }
  } else {
    if (currentZoom > 0.1) {
      currentZoom = Math.max(0.1, currentZoom - zoomSpeed);
      updateZoom();
    }
  }
});

// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
  if (!previewImage.src) return;
  
  if (e.key === '+' || e.key === '=') {
    e.preventDefault();
    zoomIn();
  } else if (e.key === '-' || e.key === '_') {
    e.preventDefault();
    zoomOut();
  } else if (e.key === '0') {
    e.preventDefault();
    zoomReset();
  }
});

// Pan functionality
imageContainer.addEventListener('mousedown', (e) => {
  if (currentZoom <= 1) return;
  
  isPanning = true;
  canvasContent.classList.add('panning');
  startX = e.pageX - imageContainer.offsetLeft;
  startY = e.pageY - imageContainer.offsetTop;
  scrollLeft = imageContainer.scrollLeft;
  scrollTop = imageContainer.scrollTop;
});

imageContainer.addEventListener('mouseleave', () => {
  isPanning = false;
  canvasContent.classList.remove('panning');
});

imageContainer.addEventListener('mouseup', () => {
  isPanning = false;
  canvasContent.classList.remove('panning');
});

imageContainer.addEventListener('mousemove', (e) => {
  if (!isPanning) return;
  e.preventDefault();
  
  const x = e.pageX - imageContainer.offsetLeft;
  const y = e.pageY - imageContainer.offsetTop;
  const walkX = (x - startX) * 2;
  const walkY = (y - startY) * 2;
  
  imageContainer.scrollLeft = scrollLeft - walkX;
  imageContainer.scrollTop = scrollTop - walkY;
});

// Upload file
headerUploadBtn.addEventListener('click', async () => {
  if (!selectedFile) return;
  
  const formData = new FormData();
  formData.append('image', selectedFile);
  
  headerUploadBtn.disabled = true;
  const originalHTML = headerUploadBtn.innerHTML;
  headerUploadBtn.innerHTML = `
    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
    </svg>
    Đang upload...
  `;
  
  updateStatus('Đang upload...', false, true);
  
  try {
    const response = await fetch('/upload', {
      method: 'POST',
      body: formData,
    });
    
    const data = await response.json();
    
    if (data.success) {
      showMessage('✓ Upload thành công!', 'success');
      updateStatus('Upload thành công', true);
      previewImage.src = data.path;
    } else {
      showMessage(data.error || 'Upload thất bại', 'error');
      updateStatus('Upload thất bại', false);
    }
  } catch (error) {
    showMessage('Có lỗi xảy ra: ' + error.message, 'error');
    updateStatus('Lỗi kết nối', false);
  } finally {
    headerUploadBtn.disabled = false;
    headerUploadBtn.innerHTML = originalHTML;
  }
});

// Xóa và reset
headerClearBtn.addEventListener('click', () => {
  // Clear session from localStorage
  if (typeof clearSession === 'function') {
    clearSession();
  }
  
  selectedFile = null;
  originalImageData = null;
  fileInput.value = '';
  imageContainer.style.display = 'none';
  previewImage.src = '';
  previewImage.style.filter = '';
  previewImage.style.transform = '';
  canvasPlaceholder.style.display = 'block';
  propertiesSection.style.display = 'none';
  adjustmentsSection.style.display = 'none';
  
  const effectsSection = document.getElementById('effectsSection');
  if (effectsSection) effectsSection.style.display = 'none';
  
  const presetsSection = document.getElementById('presetsSection');
  if (presetsSection) presetsSection.style.display = 'none';
  headerUploadBtn.disabled = true;
  headerClearBtn.style.display = 'none';
  
  // Disable download button
  const downloadBtn = document.getElementById('downloadBtn');
  if (downloadBtn) {
    downloadBtn.disabled = true;
  }
  
  // Disable export project button
  const exportProjectBtn = document.getElementById('exportProjectBtn');
  if (exportProjectBtn) {
    exportProjectBtn.disabled = true;
  }
  
  // Disable remove background button
  const removeBackgroundBtn = document.getElementById('removeBackgroundBtn');
  if (removeBackgroundBtn) {
    removeBackgroundBtn.disabled = true;
  }
  
  canvasInfo.textContent = '';
  
  // Reset zoom
  currentZoom = 1;
  zoomLevel.textContent = '100%';
  
  // Reset adjustments
  adjustments = {
    brightness: 0,
    contrast: 0,
    saturation: 0,
    hue: 0,
    lightness: 0,
    temperature: 0,
    tint: 0,
    blurAmount: 0,
    flipHorizontal: false,
    flipVertical: false,
    rotateAngle: 0
  };
  
  if (brightnessSlider) brightnessSlider.value = 0;
  if (contrastSlider) contrastSlider.value = 0;
  saturationSlider.value = 0;
  hueSlider.value = 0;
  if (lightnessSlider) lightnessSlider.value = 0;
  if (temperatureSlider) temperatureSlider.value = 0;
  if (tintSlider) tintSlider.value = 0;
  
  // Reset curves
  curvePoints = [
    { x: 0, y: 0 },
    { x: 255, y: 255 }
  ];
  if (curveCanvas) drawCurve();
  
  // Reset thông tin
  document.getElementById('fileName').textContent = '-';
  document.getElementById('fileSize').textContent = '-';
  document.getElementById('fileType').textContent = '-';
  document.getElementById('imageDimensions').textContent = '-';
  
  updateStatus('Sẵn sàng', true);
});

// Cập nhật status indicator
function updateStatus(text, _success = true, uploading = false) {
  if (!statusIndicator) return;
  
  const statusText = statusIndicator.querySelector('.status-text');
  if (!statusText) return;
  
  statusText.textContent = text;
  
  if (uploading) {
    statusIndicator.classList.add('uploading');
  } else {
    statusIndicator.classList.remove('uploading');
  }
}

// Note: showMessage is now handled by sweetalert-wrapper.js

// Color Balance, Black & White, Exposure, Vibrance functionality
const bwToggle = document.getElementById('bwToggle');
let bwEnabled = false;

// Color Balance sliders
const colorBalanceSliders = {
  shadowsCyan: document.getElementById('shadowsCyanSlider'),
  shadowsMagenta: document.getElementById('shadowsMagentaSlider'),
  shadowsYellow: document.getElementById('shadowsYellowSlider'),
  midtonesCyan: document.getElementById('midtonesCyanSlider'),
  midtonesMagenta: document.getElementById('midtonesMagentaSlider'),
  midtonesYellow: document.getElementById('midtonesYellowSlider'),
  highlightsCyan: document.getElementById('highlightsCyanSlider'),
  highlightsMagenta: document.getElementById('highlightsMagentaSlider'),
  highlightsYellow: document.getElementById('highlightsYellowSlider')
};

// Setup Color Balance
Object.keys(colorBalanceSliders).forEach(key => {
  const slider = colorBalanceSliders[key];
  if (slider) {
    slider.addEventListener('input', (e) => {
      adjustments[key] = parseInt(e.target.value);
      document.getElementById(key + 'Value').textContent = adjustments[key];
      applyFilters();
    });
  }
});

// Black & White sliders
const bwSliders = ['bwRed', 'bwYellow', 'bwGreen', 'bwCyan', 'bwBlue', 'bwMagenta', 'bwTint'];
bwSliders.forEach(key => {
  const slider = document.getElementById(key + 'Slider');
  if (slider) {
    slider.addEventListener('input', (e) => {
      const value = parseInt(e.target.value);
      adjustments[key] = value;
      const valueElement = document.getElementById(key + 'Value');
      if (valueElement) {
        valueElement.textContent = value;
      }
      if (bwEnabled) {
        applyFilters();
      }
    });
  }
});

if (bwToggle) {
  bwToggle.addEventListener('change', (e) => {
    bwEnabled = e.target.checked;
    if (bwEnabled) {
      showMessage('✓ Black & White enabled', 'success');
    }
    applyFilters();
  });
}

// Exposure sliders
const exposureSlider = document.getElementById('exposureSlider');
const offsetSlider = document.getElementById('offsetSlider');
const gammaCorrectionSlider = document.getElementById('gammaCorrectionSlider');

if (exposureSlider) {
  exposureSlider.addEventListener('input', (e) => {
    adjustments.exposure = parseFloat(e.target.value);
    document.getElementById('exposureValue').textContent = adjustments.exposure.toFixed(1);
    applyFilters();
  });
}

if (offsetSlider) {
  offsetSlider.addEventListener('input', (e) => {
    adjustments.offset = parseInt(e.target.value);
    document.getElementById('offsetValue').textContent = adjustments.offset;
    applyFilters();
  });
}

if (gammaCorrectionSlider) {
  gammaCorrectionSlider.addEventListener('input', (e) => {
    adjustments.gammaCorrection = parseFloat(e.target.value);
    document.getElementById('gammaCorrectionValue').textContent = adjustments.gammaCorrection.toFixed(2);
    applyFilters();
  });
}

// Vibrance sliders
const vibranceSlider = document.getElementById('vibranceSlider');
const saturationVibranceSlider = document.getElementById('saturationVibranceSlider');

if (vibranceSlider) {
  vibranceSlider.addEventListener('input', (e) => {
    adjustments.vibrance = parseInt(e.target.value);
    document.getElementById('vibranceValue').textContent = adjustments.vibrance;
    applyFilters();
  });
}

if (saturationVibranceSlider) {
  saturationVibranceSlider.addEventListener('input', (e) => {
    adjustments.saturationVibrance = parseInt(e.target.value);
    document.getElementById('saturationVibranceValue').textContent = adjustments.saturationVibrance;
    applyFilters();
  });
}

// Selective Color
const selectiveColorRange = document.getElementById('selectiveColorRange');
const scSliders = ['scCyan', 'scMagenta', 'scYellow', 'scBlack'];

if (selectiveColorRange) {
  selectiveColorRange.addEventListener('change', (e) => {
    adjustments.selectiveColorRange = e.target.value;
  });
}

scSliders.forEach(key => {
  const slider = document.getElementById(key + 'Slider');
  if (slider) {
    slider.addEventListener('input', (e) => {
      adjustments[key] = parseInt(e.target.value);
      document.getElementById(key + 'Value').textContent = adjustments[key];
      applyFilters();
    });
  }
});

// Photo Filter
const photoFilterType = document.getElementById('photoFilterType');
const filterDensitySlider = document.getElementById('filterDensitySlider');
const preserveLuminosity = document.getElementById('preserveLuminosity');
const filterPreview = document.getElementById('filterPreview');

const filterColors = {
  'warming85': 'rgb(236, 138, 0)',
  'warming81': 'rgb(238, 206, 0)',
  'cooling80': 'rgb(0, 88, 238)',
  'cooling82': 'rgb(0, 206, 255)',
  'red': 'rgb(234, 28, 36)',
  'orange': 'rgb(247, 148, 29)',
  'yellow': 'rgb(255, 242, 0)',
  'green': 'rgb(57, 181, 74)',
  'cyan': 'rgb(0, 174, 239)',
  'blue': 'rgb(46, 49, 146)',
  'violet': 'rgb(146, 39, 143)',
  'magenta': 'rgb(236, 0, 140)',
  'sepia': 'rgb(162, 138, 101)'
};

if (photoFilterType) {
  photoFilterType.addEventListener('change', (e) => {
    adjustments.photoFilterType = e.target.value;
    if (filterPreview && filterColors[e.target.value]) {
      filterPreview.style.background = filterColors[e.target.value];
    } else {
      filterPreview.style.background = 'transparent';
    }
    applyFilters();
  });
}

if (filterDensitySlider) {
  filterDensitySlider.addEventListener('input', (e) => {
    adjustments.filterDensity = parseInt(e.target.value);
    document.getElementById('filterDensityValue').textContent = adjustments.filterDensity;
    applyFilters();
  });
}

if (preserveLuminosity) {
  preserveLuminosity.addEventListener('change', (e) => {
    adjustments.preserveLuminosity = e.target.checked;
    applyFilters();
  });
}

// Gradient Map
const gradientMapPreset = document.getElementById('gradientMapPreset');
const gradientOpacitySlider = document.getElementById('gradientOpacitySlider');
const gradientPreview = document.getElementById('gradientPreview');

const gradientPresets = {
  'duotone-blue': 'linear-gradient(to right, #1a1a2e, #16213e, #0f3460, #533483)',
  'duotone-red': 'linear-gradient(to right, #2c003e, #6a0572, #ab2346, #ff6b6b)',
  'duotone-green': 'linear-gradient(to right, #0a3d62, #1e5f74, #079992, #38ada9)',
  'sunset': 'linear-gradient(to right, #2c003e, #6a0572, #ff6b6b, #feca57)',
  'ocean': 'linear-gradient(to right, #0a3d62, #1e5f74, #079992, #48dbfb)',
  'forest': 'linear-gradient(to right, #1e3a20, #2d5016, #6ab04c, #badc58)',
  'fire': 'linear-gradient(to right, #2c003e, #6a0572, #ff6348, #feca57)',
  'purple-haze': 'linear-gradient(to right, #2c003e, #6a0572, #a55eea, #e056fd)',
  'vintage': 'linear-gradient(to right, #3d3522, #6b5b3a, #a08c5c, #d4af37)',
  'cyberpunk': 'linear-gradient(to right, #0a0e27, #1e3a8a, #ec4899, #fbbf24)'
};

if (gradientMapPreset) {
  gradientMapPreset.addEventListener('change', (e) => {
    adjustments.gradientMapPreset = e.target.value;
    if (gradientPreview && gradientPresets[e.target.value]) {
      gradientPreview.style.background = gradientPresets[e.target.value];
    } else {
      gradientPreview.style.background = 'transparent';
    }
    applyFilters();
  });
}

if (gradientOpacitySlider) {
  gradientOpacitySlider.addEventListener('input', (e) => {
    adjustments.gradientOpacity = parseInt(e.target.value);
    document.getElementById('gradientOpacityValue').textContent = adjustments.gradientOpacity;
    applyFilters();
  });
}

// Channel Mixer
const mixerOutputChannel = document.getElementById('mixerOutputChannel');
const mixerSliders = ['mixerRed', 'mixerGreen', 'mixerBlue', 'mixerConstant'];
const mixerMonochromeBtn = document.getElementById('mixerMonochromeBtn');

if (mixerOutputChannel) {
  mixerOutputChannel.addEventListener('change', (e) => {
    adjustments.mixerOutputChannel = e.target.value;
    // Reset to default for selected channel
    if (e.target.value === 'red') {
      adjustments.mixerRed = 100;
      adjustments.mixerGreen = 0;
      adjustments.mixerBlue = 0;
    } else if (e.target.value === 'green') {
      adjustments.mixerRed = 0;
      adjustments.mixerGreen = 100;
      adjustments.mixerBlue = 0;
    } else {
      adjustments.mixerRed = 0;
      adjustments.mixerGreen = 0;
      adjustments.mixerBlue = 100;
    }
    adjustments.mixerConstant = 0;
    
    document.getElementById('mixerRedSlider').value = adjustments.mixerRed;
    document.getElementById('mixerGreenSlider').value = adjustments.mixerGreen;
    document.getElementById('mixerBlueSlider').value = adjustments.mixerBlue;
    document.getElementById('mixerConstantSlider').value = 0;
    
    document.getElementById('mixerRedValue').textContent = adjustments.mixerRed;
    document.getElementById('mixerGreenValue').textContent = adjustments.mixerGreen;
    document.getElementById('mixerBlueValue').textContent = adjustments.mixerBlue;
    document.getElementById('mixerConstantValue').textContent = 0;
    
    applyFilters();
  });
}

mixerSliders.forEach(key => {
  const slider = document.getElementById(key + 'Slider');
  if (slider) {
    slider.addEventListener('input', (e) => {
      adjustments[key] = parseInt(e.target.value);
      document.getElementById(key + 'Value').textContent = adjustments[key];
      applyFilters();
    });
  }
});

if (mixerMonochromeBtn) {
  mixerMonochromeBtn.addEventListener('click', () => {
    adjustments.mixerRed = 40;
    adjustments.mixerGreen = 40;
    adjustments.mixerBlue = 20;
    adjustments.mixerConstant = 0;
    
    document.getElementById('mixerRedSlider').value = 40;
    document.getElementById('mixerGreenSlider').value = 40;
    document.getElementById('mixerBlueSlider').value = 20;
    document.getElementById('mixerConstantSlider').value = 0;
    
    document.getElementById('mixerRedValue').textContent = 40;
    document.getElementById('mixerGreenValue').textContent = 40;
    document.getElementById('mixerBlueValue').textContent = 20;
    document.getElementById('mixerConstantValue').textContent = 0;
    
    applyFilters();
    showMessage('✓ Monochrome preset applied!', 'success');
  });
}

// Color Lookup (LUT)
const lutPreset = document.getElementById('lutPreset');
const lutIntensitySlider = document.getElementById('lutIntensitySlider');

if (lutPreset) {
  lutPreset.addEventListener('change', (e) => {
    adjustments.lutPreset = e.target.value;
    applyFilters();
  });
}

if (lutIntensitySlider) {
  lutIntensitySlider.addEventListener('input', (e) => {
    adjustments.lutIntensity = parseInt(e.target.value);
    document.getElementById('lutIntensityValue').textContent = adjustments.lutIntensity;
    applyFilters();
  });
}

// Invert
const invertToggle = document.getElementById('invertToggle');
if (invertToggle) {
  invertToggle.addEventListener('change', (e) => {
    adjustments.invertEnabled = e.target.checked;
    if (adjustments.invertEnabled) {
      showMessage('✓ Invert enabled', 'success');
    }
    applyFilters();
  });
}

// Threshold
const thresholdToggle = document.getElementById('thresholdToggle');
const thresholdLevelSlider = document.getElementById('thresholdLevelSlider');

if (thresholdToggle) {
  thresholdToggle.addEventListener('change', (e) => {
    adjustments.thresholdEnabled = e.target.checked;
    if (adjustments.thresholdEnabled) {
      showMessage('✓ Threshold enabled', 'success');
    }
    applyFilters();
  });
}

if (thresholdLevelSlider) {
  thresholdLevelSlider.addEventListener('input', (e) => {
    adjustments.thresholdLevel = parseInt(e.target.value);
    document.getElementById('thresholdLevelValue').textContent = adjustments.thresholdLevel;
    if (adjustments.thresholdEnabled) {
      applyFilters();
    }
  });
}

// Posterize
const posterizeToggle = document.getElementById('posterizeToggle');
const posterizeLevelsSlider = document.getElementById('posterizeLevelsSlider');

if (posterizeToggle) {
  posterizeToggle.addEventListener('change', (e) => {
    adjustments.posterizeEnabled = e.target.checked;
    if (adjustments.posterizeEnabled) {
      showMessage('✓ Posterize enabled', 'success');
    }
    applyFilters();
  });
}

if (posterizeLevelsSlider) {
  posterizeLevelsSlider.addEventListener('input', (e) => {
    adjustments.posterizeLevels = parseInt(e.target.value);
    document.getElementById('posterizeLevelsValue').textContent = adjustments.posterizeLevels;
    if (adjustments.posterizeEnabled) {
      applyFilters();
    }
  });
}

// History System
const undoBtn = document.getElementById('undoBtn');
const redoBtn = document.getElementById('redoBtn');
const historyBtn = document.getElementById('historyBtn');
const historyPanel = document.getElementById('historyPanel');
const historyCloseBtn = document.getElementById('historyCloseBtn');
const historyContent = document.getElementById('historyContent');

// Save state to history
function saveToHistory(action, details = '') {
  if (isApplyingHistory) return;
  
  const state = {
    action: action,
    details: details,
    timestamp: new Date().toLocaleTimeString(),
    adjustments: JSON.parse(JSON.stringify(adjustments)),
    bwEnabled: bwEnabled,
    curvePoints: JSON.parse(JSON.stringify(curvePoints)),
    levelsValues: JSON.parse(JSON.stringify(levelsValues)),
    currentChannel: currentChannel,
    imageData: previewImage.src,
    cssFilter: previewImage.style.filter
  };
  
  // Remove any states after current index
  historyStack = historyStack.slice(0, historyIndex + 1);
  
  // Add new state
  historyStack.push(state);
  
  // Limit to MAX_HISTORY
  if (historyStack.length > MAX_HISTORY) {
    historyStack.shift();
  } else {
    historyIndex++;
  }
  
  updateHistoryUI();
  updateUndoRedoButtons();
}

// Undo
function undo() {
  if (historyIndex > 0) {
    historyIndex--;
    applyHistoryState(historyStack[historyIndex]);
    updateHistoryUI();
    updateUndoRedoButtons();
    showMessage('↶ Undo', 'success');
  }
}

// Redo
function redo() {
  if (historyIndex < historyStack.length - 1) {
    historyIndex++;
    applyHistoryState(historyStack[historyIndex]);
    updateHistoryUI();
    updateUndoRedoButtons();
    showMessage('↷ Redo', 'success');
  }
}

// Apply history state
function applyHistoryState(state) {
  isApplyingHistory = true;
  
  // Restore adjustments
  Object.assign(adjustments, state.adjustments);
  bwEnabled = state.bwEnabled;
  curvePoints = JSON.parse(JSON.stringify(state.curvePoints));
  levelsValues = JSON.parse(JSON.stringify(state.levelsValues));
  currentChannel = state.currentChannel || 'rgb';
  
  // Restore image and CSS filter
  previewImage.src = state.imageData;
  previewImage.style.filter = state.cssFilter || '';
  
  // Update all UI controls
  updateAllControls();
  
  // Force recalculate histogram
  setTimeout(() => {
    if (previewImage.complete) {
      calculateHistogram();
      if (levelsCanvas) drawLevelsHistogram();
    }
  }, 100);
  
  isApplyingHistory = false;
}

// Update all UI controls to match current state
function updateAllControls() {
  // Update all sliders and inputs
  Object.keys(adjustments).forEach(key => {
    const slider = document.getElementById(key + 'Slider');
    const input = document.getElementById(key + 'Input');
    const value = document.getElementById(key + 'Value');
    
    if (slider) {
      slider.value = adjustments[key];
    }
    if (input) {
      input.value = adjustments[key];
    }
    if (value) {
      // Format value display
      if (key === 'hue') {
        value.textContent = adjustments[key] + '°';
      } else if (key === 'gammaCorrection' || key === 'midtones') {
        value.textContent = parseFloat(adjustments[key]).toFixed(2);
      } else if (key === 'exposure') {
        value.textContent = parseFloat(adjustments[key]).toFixed(1);
      } else {
        value.textContent = adjustments[key];
      }
    }
  });
  
  // Update special value displays
  if (document.getElementById('outputBlackValue')) {
    document.getElementById('outputBlackValue').textContent = levelsValues.outputBlack;
  }
  if (document.getElementById('outputWhiteValue')) {
    document.getElementById('outputWhiteValue').textContent = levelsValues.outputWhite;
  }
  
  // Update toggles
  if (bwToggle) bwToggle.checked = bwEnabled;
  if (document.getElementById('invertToggle')) {
    document.getElementById('invertToggle').checked = adjustments.invertEnabled;
  }
  if (document.getElementById('thresholdToggle')) {
    document.getElementById('thresholdToggle').checked = adjustments.thresholdEnabled;
  }
  if (document.getElementById('posterizeToggle')) {
    document.getElementById('posterizeToggle').checked = adjustments.posterizeEnabled;
  }
  if (document.getElementById('preserveLuminosity')) {
    document.getElementById('preserveLuminosity').checked = adjustments.preserveLuminosity;
  }
  
  // Update selects
  if (document.getElementById('selectiveColorRange')) {
    document.getElementById('selectiveColorRange').value = adjustments.selectiveColorRange;
  }
  if (document.getElementById('photoFilterType')) {
    document.getElementById('photoFilterType').value = adjustments.photoFilterType;
  }
  if (document.getElementById('gradientMapPreset')) {
    document.getElementById('gradientMapPreset').value = adjustments.gradientMapPreset;
  }
  if (document.getElementById('mixerOutputChannel')) {
    document.getElementById('mixerOutputChannel').value = adjustments.mixerOutputChannel;
  }
  if (document.getElementById('lutPreset')) {
    document.getElementById('lutPreset').value = adjustments.lutPreset;
  }
  if (document.getElementById('curveChannel')) {
    document.getElementById('curveChannel').value = currentChannel;
  }
  if (document.getElementById('levelsChannel')) {
    document.getElementById('levelsChannel').value = levelsValues.channel;
  }
  
  // Update levels sliders
  if (document.getElementById('shadowsSlider')) {
    document.getElementById('shadowsSlider').value = levelsValues.shadows;
    document.getElementById('shadowsInput').value = levelsValues.shadows;
  }
  if (document.getElementById('midtonesSlider')) {
    document.getElementById('midtonesSlider').value = levelsValues.midtones;
    document.getElementById('midtonesInput').value = levelsValues.midtones.toFixed(2);
  }
  if (document.getElementById('highlightsSlider')) {
    document.getElementById('highlightsSlider').value = levelsValues.highlights;
    document.getElementById('highlightsInput').value = levelsValues.highlights;
  }
  if (document.getElementById('outputBlackSlider')) {
    document.getElementById('outputBlackSlider').value = levelsValues.outputBlack;
  }
  if (document.getElementById('outputWhiteSlider')) {
    document.getElementById('outputWhiteSlider').value = levelsValues.outputWhite;
  }
  
  // Update color preview
  updateColorPreview();
  updateComparisonBars();
  
  // Redraw curves and levels
  if (curveCanvas) drawCurve();
  if (levelsCanvas) drawLevelsHistogram();
  
  // Update filter preview
  const filterPreview = document.getElementById('filterPreview');
  if (filterPreview && adjustments.photoFilterType !== 'none') {
    const filterColors = {
      'warming85': 'rgb(236, 138, 0)',
      'warming81': 'rgb(238, 206, 0)',
      'cooling80': 'rgb(0, 88, 238)',
      'cooling82': 'rgb(0, 206, 255)',
      'red': 'rgb(234, 28, 36)',
      'orange': 'rgb(247, 148, 29)',
      'yellow': 'rgb(255, 242, 0)',
      'green': 'rgb(57, 181, 74)',
      'cyan': 'rgb(0, 174, 239)',
      'blue': 'rgb(46, 49, 146)',
      'violet': 'rgb(146, 39, 143)',
      'magenta': 'rgb(236, 0, 140)',
      'sepia': 'rgb(162, 138, 101)'
    };
    filterPreview.style.background = filterColors[adjustments.photoFilterType] || 'transparent';
  }
  
  // Update gradient preview
  const gradientPreview = document.getElementById('gradientPreview');
  if (gradientPreview && adjustments.gradientMapPreset !== 'none') {
    const gradientPresets = {
      'duotone-blue': 'linear-gradient(to right, #1a1a2e, #16213e, #0f3460, #533483)',
      'duotone-red': 'linear-gradient(to right, #2c003e, #6a0572, #ab2346, #ff6b6b)',
      'duotone-green': 'linear-gradient(to right, #0a3d62, #1e5f74, #079992, #38ada9)',
      'sunset': 'linear-gradient(to right, #2c003e, #6a0572, #ff6b6b, #feca57)',
      'ocean': 'linear-gradient(to right, #0a3d62, #1e5f74, #079992, #48dbfb)',
      'forest': 'linear-gradient(to right, #1e3a20, #2d5016, #6ab04c, #badc58)',
      'fire': 'linear-gradient(to right, #2c003e, #6a0572, #ff6348, #feca57)',
      'purple-haze': 'linear-gradient(to right, #2c003e, #6a0572, #a55eea, #e056fd)',
      'vintage': 'linear-gradient(to right, #3d3522, #6b5b3a, #a08c5c, #d4af37)',
      'cyberpunk': 'linear-gradient(to right, #0a0e27, #1e3a8a, #ec4899, #fbbf24)'
    };
    gradientPreview.style.background = gradientPresets[adjustments.gradientMapPreset] || 'transparent';
  }
}

// Update undo/redo buttons
function updateUndoRedoButtons() {
  if (undoBtn) {
    undoBtn.disabled = historyIndex <= 0;
  }
  if (redoBtn) {
    redoBtn.disabled = historyIndex >= historyStack.length - 1;
  }
}

// Update history UI
function updateHistoryUI() {
  if (!historyContent) return;
  
  if (historyStack.length === 0) {
    historyContent.innerHTML = '<div class="history-empty">No history yet</div>';
    return;
  }
  
  let html = '';
  historyStack.forEach((state, index) => {
    const isActive = index === historyIndex;
    html += `
      <div class="history-item ${isActive ? 'active' : ''}" data-index="${index}">
        <div class="history-action">${state.action}</div>
        ${state.details ? `<div class="history-details">${state.details}</div>` : ''}
        <div class="history-time">${state.timestamp}</div>
      </div>
    `;
  });
  
  historyContent.innerHTML = html;
  
  // Add click handlers
  document.querySelectorAll('.history-item').forEach(item => {
    item.addEventListener('click', () => {
      const index = parseInt(item.getAttribute('data-index'));
      historyIndex = index;
      applyHistoryState(historyStack[index]);
      updateHistoryUI();
      updateUndoRedoButtons();
    });
  });
  
  // Scroll to active item
  const activeItem = historyContent.querySelector('.history-item.active');
  if (activeItem) {
    activeItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
  }
}

// Event listeners
// Note: Undo/Redo and History panel are now handled by history-integration.js

// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
  // Ctrl+Z for Undo
  if (e.ctrlKey && e.key === 'z' && !e.shiftKey) {
    e.preventDefault();
    undo();
  }
  // Ctrl+Y or Ctrl+Shift+Z for Redo
  else if ((e.ctrlKey && e.key === 'y') || (e.ctrlKey && e.shiftKey && e.key === 'z')) {
    e.preventDefault();
    redo();
  }
});

// Save initial state when image is loaded
const originalHandleFile = handleFile;
handleFile = function(file) {
  originalHandleFile(file);
  
  // Save initial state after image loads
  setTimeout(() => {
    historyStack = [];
    historyIndex = -1;
    saveToHistory('Image Loaded', file.name);
  }, 500);
};

// Get last changed adjustment for history
let lastAdjustments = {};

function getLastChangedAdjustment() {
  for (let key in adjustments) {
    if (adjustments[key] !== lastAdjustments[key]) {
      lastAdjustments = JSON.parse(JSON.stringify(adjustments));
      
      // Map adjustment keys to readable names
      const actionNames = {
        brightness: 'Brightness',
        contrast: 'Contrast',
        saturation: 'Saturation',
        hue: 'Hue',
        lightness: 'Lightness',
        exposure: 'Exposure',
        offset: 'Offset',
        gammaCorrection: 'Gamma Correction',
        vibrance: 'Vibrance',
        scCyan: 'Selective Color',
        filterDensity: 'Photo Filter',
        gradientOpacity: 'Gradient Map',
        mixerRed: 'Channel Mixer',
        lutIntensity: 'Color Lookup',
        thresholdLevel: 'Threshold',
        posterizeLevels: 'Posterize'
      };
      
      const action = actionNames[key] || key;
      const value = adjustments[key];
      
      return {
        action: action,
        details: `Value: ${value}`
      };
    }
  }
  return null;
}

// Initialize last adjustments
lastAdjustments = JSON.parse(JSON.stringify(adjustments));

// Panel Reset Buttons
document.querySelectorAll('.panel-reset-btn').forEach(btn => {
  btn.addEventListener('click', () => {
    const resetType = btn.getAttribute('data-reset');
    resetPanel(resetType);
  });
});

function resetPanel(panelType) {
  isApplyingHistory = true;
  
  switch(panelType) {
    case 'hueSaturation':
      adjustments.hue = 0;
      adjustments.saturation = 0;
      adjustments.lightness = 0;
      
      if (hueSlider) hueSlider.value = 0;
      if (saturationSlider) saturationSlider.value = 0;
      if (lightnessSlider) lightnessSlider.value = 0;
      
      document.getElementById('hueValue').textContent = '0°';
      document.getElementById('saturationValue').textContent = '0';
      if (document.getElementById('lightnessValue')) {
        document.getElementById('lightnessValue').textContent = '0';
      }
      
      updateColorPreview();
      showMessage('✓ Hue/Saturation reset', 'success');
      break;
      
    case 'brightnessContrast':
      adjustments.brightness = 0;
      adjustments.contrast = 0;
      
      if (brightnessSlider) brightnessSlider.value = 0;
      if (contrastSlider) contrastSlider.value = 0;
      
      if (document.getElementById('brightnessValue')) {
        document.getElementById('brightnessValue').textContent = '0';
      }
      if (document.getElementById('contrastValue')) {
        document.getElementById('contrastValue').textContent = '0';
      }
      
      updateComparisonBars();
      showMessage('✓ Brightness/Contrast reset', 'success');
      break;
      
    case 'curves':
      curvePoints = [
        { x: 0, y: 0 },
        { x: 255, y: 255 }
      ];
      if (curveCanvas) drawCurve();
      showMessage('✓ Curves reset', 'success');
      break;
      
    case 'levels':
      levelsValues.shadows = 0;
      levelsValues.midtones = 1.0;
      levelsValues.highlights = 255;
      levelsValues.outputBlack = 0;
      levelsValues.outputWhite = 255;
      
      if (shadowsSlider) {
        shadowsSlider.value = 0;
        shadowsInput.value = 0;
      }
      if (midtonesSlider) {
        midtonesSlider.value = 1.0;
        midtonesInput.value = '1.00';
      }
      if (highlightsSlider) {
        highlightsSlider.value = 255;
        highlightsInput.value = 255;
      }
      if (outputBlackSlider) outputBlackSlider.value = 0;
      if (outputWhiteSlider) outputWhiteSlider.value = 255;
      
      document.getElementById('outputBlackValue').textContent = '0';
      document.getElementById('outputWhiteValue').textContent = '255';
      
      if (levelsCanvas) drawLevelsHistogram();
      showMessage('✓ Levels reset', 'success');
      break;
      
    case 'colorBalance':
      adjustments.shadowsCyan = 0;
      adjustments.shadowsMagenta = 0;
      adjustments.shadowsYellow = 0;
      adjustments.midtonesCyan = 0;
      adjustments.midtonesMagenta = 0;
      adjustments.midtonesYellow = 0;
      adjustments.highlightsCyan = 0;
      adjustments.highlightsMagenta = 0;
      adjustments.highlightsYellow = 0;
      
      ['shadowsCyan', 'shadowsMagenta', 'shadowsYellow',
       'midtonesCyan', 'midtonesMagenta', 'midtonesYellow',
       'highlightsCyan', 'highlightsMagenta', 'highlightsYellow'].forEach(key => {
        const slider = document.getElementById(key + 'Slider');
        const value = document.getElementById(key + 'Value');
        if (slider) slider.value = 0;
        if (value) value.textContent = '0';
      });
      
      showMessage('✓ Color Balance reset', 'success');
      break;
      
    case 'blackWhite':
      bwEnabled = false;
      if (bwToggle) bwToggle.checked = false;
      
      adjustments.bwRed = 40;
      adjustments.bwYellow = 60;
      adjustments.bwGreen = 40;
      adjustments.bwCyan = 60;
      adjustments.bwBlue = 20;
      adjustments.bwMagenta = 80;
      adjustments.bwTint = 0;
      
      const bwDefaults = {
        bwRed: 40, bwYellow: 60, bwGreen: 40,
        bwCyan: 60, bwBlue: 20, bwMagenta: 80, bwTint: 0
      };
      
      Object.keys(bwDefaults).forEach(key => {
        const slider = document.getElementById(key + 'Slider');
        const value = document.getElementById(key + 'Value');
        if (slider) slider.value = bwDefaults[key];
        if (value) value.textContent = bwDefaults[key];
      });
      
      showMessage('✓ Black & White reset', 'success');
      break;
      
    case 'exposure':
      adjustments.exposure = 0;
      adjustments.offset = 0;
      adjustments.gammaCorrection = 1.0;
      
      if (exposureSlider) exposureSlider.value = 0;
      if (offsetSlider) offsetSlider.value = 0;
      if (gammaCorrectionSlider) gammaCorrectionSlider.value = 1.0;
      
      if (document.getElementById('exposureValue')) {
        document.getElementById('exposureValue').textContent = '0';
      }
      if (document.getElementById('offsetValue')) {
        document.getElementById('offsetValue').textContent = '0';
      }
      if (document.getElementById('gammaCorrectionValue')) {
        document.getElementById('gammaCorrectionValue').textContent = '1.00';
      }
      
      showMessage('✓ Exposure reset', 'success');
      break;
      
    case 'vibrance':
      adjustments.vibrance = 0;
      adjustments.saturationVibrance = 0;
      
      if (vibranceSlider) vibranceSlider.value = 0;
      if (saturationVibranceSlider) saturationVibranceSlider.value = 0;
      
      if (document.getElementById('vibranceValue')) {
        document.getElementById('vibranceValue').textContent = '0';
      }
      if (document.getElementById('saturationVibranceValue')) {
        document.getElementById('saturationVibranceValue').textContent = '0';
      }
      
      showMessage('✓ Vibrance reset', 'success');
      break;
      
    case 'selectiveColor':
      adjustments.scCyan = 0;
      adjustments.scMagenta = 0;
      adjustments.scYellow = 0;
      adjustments.scBlack = 0;
      
      ['scCyan', 'scMagenta', 'scYellow', 'scBlack'].forEach(key => {
        const slider = document.getElementById(key + 'Slider');
        const value = document.getElementById(key + 'Value');
        if (slider) slider.value = 0;
        if (value) value.textContent = '0';
      });
      
      showMessage('✓ Selective Color reset', 'success');
      break;
      
    case 'photoFilter':
      adjustments.photoFilterType = 'none';
      adjustments.filterDensity = 25;
      
      if (photoFilterType) photoFilterType.value = 'none';
      if (filterDensitySlider) filterDensitySlider.value = 25;
      if (document.getElementById('filterDensityValue')) {
        document.getElementById('filterDensityValue').textContent = '25';
      }
      if (filterPreview) filterPreview.style.background = 'transparent';
      
      showMessage('✓ Photo Filter reset', 'success');
      break;
      
    case 'gradientMap':
      adjustments.gradientMapPreset = 'none';
      adjustments.gradientOpacity = 100;
      
      if (gradientMapPreset) gradientMapPreset.value = 'none';
      if (gradientOpacitySlider) gradientOpacitySlider.value = 100;
      if (document.getElementById('gradientOpacityValue')) {
        document.getElementById('gradientOpacityValue').textContent = '100';
      }
      if (gradientPreview) gradientPreview.style.background = 'transparent';
      
      showMessage('✓ Gradient Map reset', 'success');
      break;
      
    case 'channelMixer':
      adjustments.mixerRed = 100;
      adjustments.mixerGreen = 0;
      adjustments.mixerBlue = 0;
      adjustments.mixerConstant = 0;
      
      ['mixerRed', 'mixerGreen', 'mixerBlue', 'mixerConstant'].forEach(key => {
        const slider = document.getElementById(key + 'Slider');
        const value = document.getElementById(key + 'Value');
        const defaultVal = key === 'mixerRed' ? 100 : 0;
        if (slider) slider.value = defaultVal;
        if (value) value.textContent = defaultVal;
      });
      
      showMessage('✓ Channel Mixer reset', 'success');
      break;
      
    case 'colorLookup':
      adjustments.lutPreset = 'none';
      adjustments.lutIntensity = 100;
      
      if (lutPreset) lutPreset.value = 'none';
      if (lutIntensitySlider) lutIntensitySlider.value = 100;
      if (document.getElementById('lutIntensityValue')) {
        document.getElementById('lutIntensityValue').textContent = '100';
      }
      
      showMessage('✓ Color Lookup reset', 'success');
      break;
      
    case 'invert':
      adjustments.invertEnabled = false;
      if (invertToggle) invertToggle.checked = false;
      showMessage('✓ Invert reset', 'success');
      break;
      
    case 'threshold':
      adjustments.thresholdEnabled = false;
      adjustments.thresholdLevel = 128;
      
      if (thresholdToggle) thresholdToggle.checked = false;
      if (thresholdLevelSlider) thresholdLevelSlider.value = 128;
      if (document.getElementById('thresholdLevelValue')) {
        document.getElementById('thresholdLevelValue').textContent = '128';
      }
      
      showMessage('✓ Threshold reset', 'success');
      break;
      
    case 'posterize':
      adjustments.posterizeEnabled = false;
      adjustments.posterizeLevels = 4;
      
      if (posterizeToggle) posterizeToggle.checked = false;
      if (posterizeLevelsSlider) posterizeLevelsSlider.value = 4;
      if (document.getElementById('posterizeLevelsValue')) {
        document.getElementById('posterizeLevelsValue').textContent = '4';
      }
      
      showMessage('✓ Posterize reset', 'success');
      break;
      
    case 'whiteBalance':
      adjustments.temperature = 0;
      adjustments.tint = 0;
      
      if (temperatureSlider) temperatureSlider.value = 0;
      if (tintSlider) tintSlider.value = 0;
      
      if (document.getElementById('temperatureValue')) {
        document.getElementById('temperatureValue').textContent = '0';
      }
      if (document.getElementById('tintValue')) {
        document.getElementById('tintValue').textContent = '0';
      }
      
      showMessage('✓ White Balance reset', 'success');
      break;
  }
  
  isApplyingHistory = false;
  
  // Reapply all filters
  applyFilters();
  
  // Save to history
  saveToHistory(`Reset ${panelType}`, 'Panel reset');
}

// Auto-add reset buttons to all panels that don't have one
document.addEventListener('DOMContentLoaded', () => {
  const panelResetHTML = `
    <button class="panel-reset-btn" data-reset="PANEL_NAME">
      <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
      </svg>
      Reset PANEL_LABEL
    </button>
  `;
  
  const panelMappings = [
    { id: 'blackWhite', label: 'Black & White' },
    { id: 'exposure', label: 'Exposure' },
    { id: 'vibrance', label: 'Vibrance' },
    { id: 'selectiveColor', label: 'Selective Color' },
    { id: 'photoFilter', label: 'Photo Filter' },
    { id: 'gradientMap', label: 'Gradient Map' },
    { id: 'channelMixer', label: 'Channel Mixer' },
    { id: 'colorLookup', label: 'Color Lookup' },
    { id: 'invert', label: 'Invert' },
    { id: 'threshold', label: 'Threshold' },
    { id: 'posterize', label: 'Posterize' },
    { id: 'whiteBalance', label: 'White Balance' }
  ];
  
  panelMappings.forEach(panel => {
    const panelContent = document.getElementById(panel.id);
    if (panelContent && !panelContent.querySelector('.panel-reset-btn')) {
      const resetBtn = panelResetHTML
        .replace('PANEL_NAME', panel.id)
        .replace('PANEL_LABEL', panel.label);
      panelContent.insertAdjacentHTML('beforeend', resetBtn);
    }
  });
  
  // Re-attach event listeners for newly added buttons
  document.querySelectorAll('.panel-reset-btn').forEach(btn => {
    if (!btn.hasAttribute('data-listener-attached')) {
      btn.setAttribute('data-listener-attached', 'true');
      btn.addEventListener('click', () => {
        const resetType = btn.getAttribute('data-reset');
        resetPanel(resetType);
      });
    }
  });
});

// Double-click on control-value to edit
document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('.control-value').forEach(valueElement => {
    valueElement.style.cursor = 'pointer';
    valueElement.title = 'Double-click to edit';
    
    valueElement.addEventListener('dblclick', () => {
      const currentValue = valueElement.textContent.replace(/[°%]/g, '').trim();
      const valueId = valueElement.id;
      const key = valueId.replace('Value', '');
      
      // Create input element
      const input = document.createElement('input');
      input.type = 'number';
      input.value = currentValue;
      input.className = 'control-value-input';
      
      // Determine min, max, step based on the control
      let min = -100, max = 100, step = 1;
      
      if (key === 'hue') {
        min = 0;
        max = 360;
      } else if (key === 'gammaCorrection' || key === 'midtones') {
        min = 0.01;
        max = 9.99;
        step = 0.01;
      } else if (key === 'exposure') {
        min = -5;
        max = 5;
        step = 0.1;
      } else if (key.includes('threshold')) {
        min = 0;
        max = 255;
      } else if (key.includes('posterize')) {
        min = 2;
        max = 32;
      } else if (key.includes('output')) {
        min = 0;
        max = 255;
      } else if (key.includes('shadows') || key.includes('highlights')) {
        min = 0;
        max = 255;
      } else if (key.includes('bw')) {
        min = -200;
        max = 300;
      } else if (key.includes('mixer')) {
        min = -200;
        max = 200;
      } else if (key.includes('sc')) {
        min = -100;
        max = 100;
      } else if (key.includes('Density') || key.includes('Opacity') || key.includes('Intensity')) {
        min = 0;
        max = 100;
      }
      
      input.min = min;
      input.max = max;
      input.step = step;
      
      // Style the input
      input.style.width = '100%';
      input.style.textAlign = 'right';
      input.style.background = '#1e1e1e';
      input.style.border = '1px solid #4a9eff';
      input.style.color = '#4a9eff';
      input.style.padding = '2px 4px';
      input.style.borderRadius = '3px';
      input.style.fontSize = '12px';
      input.style.fontWeight = '600';
      
      // Replace span with input
      const parent = valueElement.parentNode;
      parent.replaceChild(input, valueElement);
      input.focus();
      input.select();
      
      // Handle input completion
      const finishEdit = () => {
        let newValue = parseFloat(input.value);
        
        // Clamp value
        newValue = Math.max(min, Math.min(max, newValue));
        
        // Update the adjustment
        if (adjustments.hasOwnProperty(key)) {
          adjustments[key] = newValue;
        } else if (levelsValues.hasOwnProperty(key)) {
          levelsValues[key] = newValue;
        }
        
        // Update the slider
        const slider = document.getElementById(key + 'Slider');
        if (slider) {
          slider.value = newValue;
        }
        
        // Update the input field if exists
        const inputField = document.getElementById(key + 'Input');
        if (inputField) {
          inputField.value = newValue;
        }
        
        // Format display value
        let displayValue = newValue;
        if (key === 'hue') {
          displayValue = newValue + '°';
        } else if (key === 'gammaCorrection' || key === 'midtones') {
          displayValue = newValue.toFixed(2);
        } else if (key === 'exposure') {
          displayValue = newValue.toFixed(1);
        }
        
        // Restore span
        valueElement.textContent = displayValue;
        parent.replaceChild(valueElement, input);
        
        // Apply filters
        if (key.includes('bw') && bwEnabled) {
          applyFilters();
        } else if (key.includes('threshold') && adjustments.thresholdEnabled) {
          applyFilters();
        } else if (key.includes('posterize') && adjustments.posterizeEnabled) {
          applyFilters();
        } else if (key.includes('shadows') || key.includes('midtones') || key.includes('highlights') || key.includes('output')) {
          if (levelsCanvas) drawLevelsHistogram();
          applyLevels();
        } else {
          applyFilters();
        }
        
        // Update other UI elements
        if (key === 'hue' || key === 'saturation' || key === 'lightness') {
          updateColorPreview();
        }
        if (key === 'brightness' || key === 'contrast') {
          updateComparisonBars();
        }
      };
      
      // Enter key to confirm
      input.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
          finishEdit();
        } else if (e.key === 'Escape') {
          // Cancel edit
          parent.replaceChild(valueElement, input);
        }
      });
      
      // Blur to confirm
      input.addEventListener('blur', finishEdit);
    });
  });
});

// Color Picker Functionality
let colorPickerPopup = null;
let currentColorPickerHue = 0;
let currentColorPickerSV = { s: 1, v: 1 };

// Make color values editable
document.addEventListener('DOMContentLoaded', () => {
  const colorValues = ['rgbValue', 'hslValue', 'hexValue'];
  
  colorValues.forEach(id => {
    const element = document.getElementById(id);
    if (element) {
      element.style.cursor = 'pointer';
      element.title = 'Double-click to edit';
      
      element.addEventListener('dblclick', () => {
        const currentText = element.textContent;
        const input = document.createElement('input');
        input.type = 'text';
        input.value = currentText;
        input.className = 'color-value-input';
        
        const parent = element.parentNode;
        parent.replaceChild(input, element);
        input.focus();
        input.select();
        
        const finishEdit = () => {
          const newValue = input.value.trim();
          
          // Parse and apply color
          if (id === 'hexValue') {
            applyColorFromHex(newValue);
          } else if (id === 'rgbValue') {
            applyColorFromRgb(newValue);
          } else if (id === 'hslValue') {
            applyColorFromHsl(newValue);
          }
          
          parent.replaceChild(element, input);
        };
        
        input.addEventListener('keydown', (e) => {
          if (e.key === 'Enter') finishEdit();
          else if (e.key === 'Escape') parent.replaceChild(element, input);
        });
        
        input.addEventListener('blur', finishEdit);
      });
    }
  });
  
  // Color swatch click to open picker
  const colorSwatch = document.getElementById('colorSwatch');
  if (colorSwatch) {
    colorSwatch.style.cursor = 'pointer';
    colorSwatch.title = 'Click to open color picker';
    
    colorSwatch.addEventListener('click', (e) => {
      openColorPicker(e);
    });
  }
});

function applyColorFromHex(hex) {
  hex = hex.replace('#', '');
  if (hex.length === 3) {
    hex = hex.split('').map(c => c + c).join('');
  }
  
  if (!/^[0-9A-Fa-f]{6}$/.test(hex)) {
    showMessage('Invalid HEX color format', 'error');
    return;
  }
  
  const r = parseInt(hex.substr(0, 2), 16);
  const g = parseInt(hex.substr(2, 2), 16);
  const b = parseInt(hex.substr(4, 2), 16);
  
  applyColorFromRgbValues(r, g, b);
}

function applyColorFromRgb(rgb) {
  const match = rgb.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
  if (!match) {
    showMessage('Invalid RGB color format', 'error');
    return;
  }
  
  const r = parseInt(match[1]);
  const g = parseInt(match[2]);
  const b = parseInt(match[3]);
  
  applyColorFromRgbValues(r, g, b);
}

function applyColorFromHsl(hsl) {
  const match = hsl.match(/hsl\((\d+)°?,\s*(\d+)%,\s*(\d+)%\)/);
  if (!match) {
    showMessage('Invalid HSL color format', 'error');
    return;
  }
  
  const h = parseInt(match[1]);
  const s = parseInt(match[2]);
  const l = parseInt(match[3]);
  
  adjustments.hue = h;
  adjustments.saturation = s - 100;
  adjustments.lightness = l - 50;
  
  if (hueSlider) hueSlider.value = h;
  if (saturationSlider) saturationSlider.value = s - 100;
  if (lightnessSlider) lightnessSlider.value = l - 50;
  
  updateColorPreview();
  applyFilters();
}

function applyColorFromRgbValues(r, g, b) {
  // Convert RGB to HSL
  r /= 255;
  g /= 255;
  b /= 255;
  
  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  let h, s, l = (max + min) / 2;
  
  if (max === min) {
    h = s = 0;
  } else {
    const d = max - min;
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
    
    switch (max) {
      case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
      case g: h = ((b - r) / d + 2) / 6; break;
      case b: h = ((r - g) / d + 4) / 6; break;
    }
  }
  
  h = Math.round(h * 360);
  s = Math.round(s * 100);
  l = Math.round(l * 100);
  
  adjustments.hue = h;
  adjustments.saturation = s - 100;
  adjustments.lightness = l - 50;
  
  if (hueSlider) hueSlider.value = h;
  if (saturationSlider) saturationSlider.value = s - 100;
  if (lightnessSlider) lightnessSlider.value = l - 50;
  
  updateColorPreview();
  applyFilters();
}

function openColorPicker(event) {
  // Close existing picker
  if (colorPickerPopup && document.body.contains(colorPickerPopup)) {
    document.body.removeChild(colorPickerPopup);
    colorPickerPopup = null;
  }
  
  // Create popup
  colorPickerPopup = document.createElement('div');
  colorPickerPopup.className = 'color-picker-popup';
  
  // Temporarily add to DOM to get dimensions
  colorPickerPopup.style.visibility = 'hidden';
  
  // Position near the swatch
  const rect = event.target.getBoundingClientRect();
  const popupWidth = 280; // min-width from CSS
  const popupHeight = 500; // approximate height
  
  let left = rect.right + 10;
  let top = rect.top;
  
  // Check if popup goes off right edge
  if (left + popupWidth > window.innerWidth) {
    // Position to the left of swatch instead
    left = rect.left - popupWidth - 10;
  }
  
  // If still off screen, position from right edge
  if (left < 0) {
    left = window.innerWidth - popupWidth - 20;
  }
  
  // Check if popup goes off bottom edge
  if (top + popupHeight > window.innerHeight) {
    top = window.innerHeight - popupHeight - 20;
  }
  
  // Check if popup goes off top edge
  if (top < 20) {
    top = 20;
  }
  
  // Remove temporarily added popup
  if (document.body.contains(colorPickerPopup)) {
    document.body.removeChild(colorPickerPopup);
  }
  
  colorPickerPopup.style.left = left + 'px';
  colorPickerPopup.style.top = top + 'px';
  colorPickerPopup.style.visibility = 'visible';
  
  // Get current color
  const h = adjustments.hue || 0;
  const s = (100 + (adjustments.saturation || 0)) / 100;
  const l = (50 + (adjustments.lightness || 0)) / 100;
  
  currentColorPickerHue = h;
  currentColorPickerSV = { s: s, v: l };
  
  // Build popup HTML
  colorPickerPopup.innerHTML = `
    <div class="color-picker-header">
      <div class="color-picker-title">Color Picker</div>
      <button class="color-picker-close">×</button>
    </div>
    
    <div class="color-picker-canvas-container">
      <canvas class="color-picker-canvas" width="240" height="240"></canvas>
      <div class="color-picker-cursor"></div>
    </div>
    
    <div class="color-picker-hue-slider">
      <div class="color-picker-hue-cursor"></div>
    </div>
    
    <div class="color-picker-preview">
      <div class="color-picker-preview-box" id="pickerPreview"></div>
    </div>
    
    <div class="color-picker-inputs">
      <div class="color-picker-input-group">
        <span class="color-picker-input-label">HEX</span>
        <input type="text" class="color-picker-input" id="pickerHex" value="#FF0000">
      </div>
      <div class="color-picker-input-group">
        <span class="color-picker-input-label">RGB</span>
        <input type="text" class="color-picker-input" id="pickerRgb" value="255, 0, 0">
      </div>
      <div class="color-picker-input-group">
        <span class="color-picker-input-label">HSL</span>
        <input type="text" class="color-picker-input" id="pickerHsl" value="0, 100%, 50%">
      </div>
    </div>
    
    <div class="color-picker-buttons">
      <button class="color-picker-btn color-picker-btn-cancel">Cancel</button>
      <button class="color-picker-btn color-picker-btn-apply">Apply</button>
    </div>
  `;
  
  document.body.appendChild(colorPickerPopup);
  
  // Initialize canvas
  const canvas = colorPickerPopup.querySelector('.color-picker-canvas');
  const ctx = canvas.getContext('2d');
  drawColorPickerCanvas(ctx, currentColorPickerHue);
  
  // Event listeners
  const closeBtn = colorPickerPopup.querySelector('.color-picker-close');
  const cancelBtn = colorPickerPopup.querySelector('.color-picker-btn-cancel');
  const applyBtn = colorPickerPopup.querySelector('.color-picker-btn-apply');
  const cursor = colorPickerPopup.querySelector('.color-picker-cursor');
  const hueSliderEl = colorPickerPopup.querySelector('.color-picker-hue-slider');
  const hueCursor = colorPickerPopup.querySelector('.color-picker-hue-cursor');
  
  const closePickerSafely = () => {
    if (colorPickerPopup && document.body.contains(colorPickerPopup)) {
      document.body.removeChild(colorPickerPopup);
      colorPickerPopup = null;
    }
  };
  
  closeBtn.addEventListener('click', closePickerSafely);
  cancelBtn.addEventListener('click', closePickerSafely);
  
  applyBtn.addEventListener('click', () => {
    const hex = document.getElementById('pickerHex').value;
    applyColorFromHex(hex);
    closePickerSafely();
    showMessage('✓ Color applied', 'success');
  });
  
  // Canvas interaction
  canvas.addEventListener('mousedown', (e) => {
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    currentColorPickerSV.s = x / canvas.width;
    currentColorPickerSV.v = 1 - (y / canvas.height);
    
    updateColorPickerPreview();
    cursor.style.left = x + 'px';
    cursor.style.top = y + 'px';
  });
  
  // Hue slider interaction
  hueSliderEl.addEventListener('click', (e) => {
    const rect = hueSliderEl.getBoundingClientRect();
    const x = e.clientX - rect.left;
    currentColorPickerHue = (x / rect.width) * 360;
    
    drawColorPickerCanvas(ctx, currentColorPickerHue);
    updateColorPickerPreview();
    hueCursor.style.left = x + 'px';
  });
  
  // Initial preview
  updateColorPickerPreview();
  hueCursor.style.left = (currentColorPickerHue / 360 * hueSliderEl.offsetWidth) + 'px';
}

function drawColorPickerCanvas(ctx, hue) {
  const width = ctx.canvas.width;
  const height = ctx.canvas.height;
  
  // Draw saturation gradient (left to right)
  const satGradient = ctx.createLinearGradient(0, 0, width, 0);
  satGradient.addColorStop(0, '#ffffff');
  satGradient.addColorStop(1, `hsl(${hue}, 100%, 50%)`);
  ctx.fillStyle = satGradient;
  ctx.fillRect(0, 0, width, height);
  
  // Draw value gradient (top to bottom)
  const valGradient = ctx.createLinearGradient(0, 0, 0, height);
  valGradient.addColorStop(0, 'rgba(0, 0, 0, 0)');
  valGradient.addColorStop(1, 'rgba(0, 0, 0, 1)');
  ctx.fillStyle = valGradient;
  ctx.fillRect(0, 0, width, height);
}

function updateColorPickerPreview() {
  const h = currentColorPickerHue;
  const s = currentColorPickerSV.s * 100;
  const v = currentColorPickerSV.v * 100;
  
  const color = `hsl(${h}, ${s}%, ${v}%)`;
  
  const preview = document.getElementById('pickerPreview');
  if (preview) preview.style.background = color;
  
  // Convert to RGB and HEX
  const [r, g, b] = hslToRgb(h, s, v);
  const hex = rgbToHex(r, g, b);
  
  const hexInput = document.getElementById('pickerHex');
  const rgbInput = document.getElementById('pickerRgb');
  const hslInput = document.getElementById('pickerHsl');
  
  if (hexInput) hexInput.value = hex;
  if (rgbInput) rgbInput.value = `${r}, ${g}, ${b}`;
  if (hslInput) hslInput.value = `${Math.round(h)}, ${Math.round(s)}%, ${Math.round(v)}%`;
}

// Close picker when clicking outside
document.addEventListener('click', (e) => {
  if (colorPickerPopup && 
      document.body.contains(colorPickerPopup) && 
      !colorPickerPopup.contains(e.target) && 
      !e.target.closest('#colorSwatch')) {
    document.body.removeChild(colorPickerPopup);
    colorPickerPopup = null;
  }
});

// Panel Tabs Functionality
document.addEventListener('DOMContentLoaded', () => {
  const panelTabs = document.getElementById('panelTabs');
  const tabs = document.querySelectorAll('.panel-tab');
  const tabContents = document.querySelectorAll('.tab-content');
  
  // Show tabs when image is loaded
  const originalHandleFileForTabs = handleFile;
  if (typeof handleFile !== 'undefined') {
    handleFile = function(file) {
      originalHandleFileForTabs(file);
      if (panelTabs) {
        panelTabs.style.display = 'flex';
      }
    };
  }
  
  // Tab switching
  tabs.forEach(tab => {
    tab.addEventListener('click', () => {
      const targetTab = tab.getAttribute('data-tab');
      
      // Remove active class from all tabs
      tabs.forEach(t => t.classList.remove('active'));
      tabContents.forEach(tc => tc.classList.remove('active'));
      
      // Add active class to clicked tab
      tab.classList.add('active');
      
      // Show corresponding content
      const targetContent = document.getElementById('tab' + targetTab.charAt(0).toUpperCase() + targetTab.slice(1));
      if (targetContent) {
        targetContent.classList.add('active');
      }
    });
  });
});

// Features Panel Functionality
document.addEventListener('DOMContentLoaded', () => {
  const featuresPanel = document.getElementById('featuresPanel');
  const featuresToggle = document.getElementById('featuresToggle');
  const resizeHandle = document.getElementById('resizeHandle');
  
  // Toggle collapse
  if (featuresToggle) {
    featuresToggle.addEventListener('click', () => {
      featuresPanel.classList.toggle('collapsed');
      featuresToggle.classList.toggle('collapsed');
    });
  }
  
  // Resize functionality
  let isResizing = false;
  let startY = 0;
  let startHeight = 0;
  
  if (resizeHandle) {
    resizeHandle.addEventListener('mousedown', (e) => {
      isResizing = true;
      startY = e.clientY;
      startHeight = featuresPanel.offsetHeight;
      document.body.style.cursor = 'ns-resize';
      document.body.style.userSelect = 'none';
    });
  }
  
  document.addEventListener('mousemove', (e) => {
    if (!isResizing) return;
    
    const deltaY = startY - e.clientY;
    const newHeight = Math.max(150, Math.min(500, startHeight + deltaY));
    featuresPanel.style.height = newHeight + 'px';
  });
  
  document.addEventListener('mouseup', () => {
    if (isResizing) {
      isResizing = false;
      document.body.style.cursor = '';
      document.body.style.userSelect = '';
    }
  });
  
  // Feature items click handlers
  const featureItems = document.querySelectorAll('.feature-item');
  featureItems.forEach(item => {
    item.addEventListener('click', () => {
      const feature = item.getAttribute('data-feature');
      handleFeatureClick(feature);
    });
  });
});

// Background Removal State
let tolerance = 30;

function handleFeatureClick(feature) {
  switch(feature) {
    case 'removeBackground':
      startBackgroundRemoval();
      break;
  }
}

// Remove background using remove.bg API
async function removeBackgroundWithAPI() {
  if (!selectedFile) return;
  
  showMessage('⏳ Đang tách nền bằng AI (remove.bg)...', 'success');
  updateStatus('Đang xử lý...', false);
  
  const formData = new FormData();
  formData.append('image', selectedFile);
  
  try {
    const response = await fetch('/remove-background', {
      method: 'POST',
      body: formData
    });
    
    const result = await response.json();
    
    if (result.success) {
      // Load the new image
      const newImageUrl = result.path + '?t=' + Date.now();
      previewImage.src = newImageUrl;
      
      // Update selected file info
      const fileName = result.filename;
      document.getElementById('fileName').textContent = fileName;
      
      showMessage('✅ Đã tách nền thành công bằng AI! Nền đã được làm trong suốt.', 'success');
      updateStatus('Hoàn tất', true);
      saveToHistory('Remove Background (AI)', 'Using remove.bg API');
    } else {
      throw new Error(result.error || 'Lỗi không xác định');
    }
  } catch (error) {
    console.error('Error removing background:', error);
    showMessage('❌ Lỗi khi tách nền: ' + error.message, 'error');
    updateStatus('Lỗi', false);
  }
}

function startBackgroundRemoval() {
  if (!previewImage.src || !selectedFile) {
    showMessage('Vui lòng upload ảnh trước', 'error');
    return;
  }
  
  // Use remove.bg API
  removeBackgroundWithAPI();
}



// Download button functionality
const downloadBtn = document.getElementById('downloadBtn');

if (downloadBtn) {
  downloadBtn.addEventListener('click', () => {
    downloadEditedImage();
  });
}

// Function to download the edited image
function downloadEditedImage() {
  if (!previewImage.src || !selectedFile) {
    showMessage('Không có ảnh để tải xuống', 'error');
    return;
  }
  
  try {
    // Create a temporary canvas to capture the edited image
    const tempCanvas = document.createElement('canvas');
    const tempCtx = tempCanvas.getContext('2d');
    
    const img = new Image();
    img.crossOrigin = 'anonymous';
    
    img.onload = () => {
      tempCanvas.width = img.naturalWidth;
      tempCanvas.height = img.naturalHeight;
      
      // Draw the image with all filters applied
      tempCtx.filter = previewImage.style.filter || 'none';
      tempCtx.drawImage(img, 0, 0);
      
      // Convert canvas to blob
      tempCanvas.toBlob((blob) => {
        if (!blob) {
          showMessage('Lỗi khi tạo file tải xuống', 'error');
          return;
        }
        
        // Create download link
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        
        // Generate filename
        const originalName = selectedFile.name;
        const nameWithoutExt = originalName.substring(0, originalName.lastIndexOf('.')) || originalName;
        const ext = originalName.substring(originalName.lastIndexOf('.')) || '.png';
        const timestamp = new Date().getTime();
        const newFileName = `${nameWithoutExt}_edited_${timestamp}${ext}`;
        
        link.href = url;
        link.download = newFileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        // Clean up
        URL.revokeObjectURL(url);
        
        showMessage('✓ Đã tải xuống ảnh thành công!', 'success');
        saveToHistory('Download Image', `Downloaded as ${newFileName}`);
      }, 'image/png');
    };
    
    img.onerror = () => {
      showMessage('Lỗi khi tải ảnh', 'error');
    };
    
    img.src = previewImage.src;
    
  } catch (error) {
    console.error('Error downloading image:', error);
    showMessage('Lỗi khi tải xuống: ' + error.message, 'error');
  }
}



// Remove Background Button (Using Remove.bg API)
const removeBackgroundBtn = document.getElementById('removeBackgroundBtn');

if (removeBackgroundBtn) {
  removeBackgroundBtn.addEventListener('click', () => {
    removeBackgroundWithAPI();
  });
}

// Remove background using Remove.bg API
async function removeBackgroundWithAPI() {
  if (!selectedFile) {
    showMessage('Vui lòng upload ảnh trước', 'error');
    return;
  }
  
  try {
    showMessage('🤖 Đang tách nền bằng Remove.bg API...', 'success');
    updateStatus('Đang gửi yêu cầu...', false);
    removeBackgroundBtn.disabled = true;
    
    // Create FormData
    const formData = new FormData();
    formData.append('image', selectedFile);
    
    // Call server endpoint
    const response = await fetch('/remove-background', {
      method: 'POST',
      body: formData
    });
    
    const result = await response.json();
    
    if (!response.ok || !result.success) {
      throw new Error(result.error || result.details || 'Lỗi khi tách nền');
    }
    
    // Load the result image
    const resultUrl = result.path;
    previewImage.src = resultUrl;
    
    // Fetch the image as blob to update selectedFile
    const imgResponse = await fetch(resultUrl);
    const blob = await imgResponse.blob();
    
    // Update selected file
    const fileName = result.filename;
    selectedFile = new File([blob], fileName, { type: 'image/png' });
    
    // Update file info
    document.getElementById('fileName').textContent = fileName;
    document.getElementById('fileSize').textContent = formatFileSize(blob.size);
    document.getElementById('fileType').textContent = 'image/png';
    
    showMessage('✅ Đã tách nền thành công bằng Remove.bg API!', 'success');
    updateStatus('Hoàn tất', true);
    saveToHistory('Remove Background (Remove.bg API)', 'AI-powered background removal');
    
    // Recalculate histogram
    setTimeout(() => {
      calculateHistogram();
    }, 100);
    
  } catch (error) {
    console.error('Error removing background:', error);
    showMessage('❌ Lỗi khi tách nền: ' + error.message, 'error');
    updateStatus('Lỗi', false);
  } finally {
    removeBackgroundBtn.disabled = false;
  }
}

// Enable remove background button when image is loaded
function enableRemoveBackgroundButton() {
  if (removeBackgroundBtn && previewImage.src && selectedFile) {
    removeBackgroundBtn.disabled = false;
  }
}

// Sharpen functionality
const sharpenAmountSlider = document.getElementById('sharpenAmountSlider');
const sharpenRadiusSlider = document.getElementById('sharpenRadiusSlider');
const sharpenThresholdSlider = document.getElementById('sharpenThresholdSlider');

// Sharpen event listeners
if (sharpenAmountSlider) {
  sharpenAmountSlider.addEventListener('input', (e) => {
    adjustments.sharpenAmount = parseInt(e.target.value);
    document.getElementById('sharpenAmountValue').textContent = adjustments.sharpenAmount;
    applySharpenFilter();
  });
}

if (sharpenRadiusSlider) {
  sharpenRadiusSlider.addEventListener('input', (e) => {
    adjustments.sharpenRadius = parseFloat(e.target.value);
    document.getElementById('sharpenRadiusValue').textContent = adjustments.sharpenRadius;
    if (adjustments.sharpenAmount > 0) {
      applySharpenFilter();
    }
  });
}

if (sharpenThresholdSlider) {
  sharpenThresholdSlider.addEventListener('input', (e) => {
    adjustments.sharpenThreshold = parseInt(e.target.value);
    document.getElementById('sharpenThresholdValue').textContent = adjustments.sharpenThreshold;
    if (adjustments.sharpenAmount > 0) {
      applySharpenFilter();
    }
  });
}

// Sharpen presets
document.querySelectorAll('[data-sharpen-preset]').forEach(btn => {
  btn.addEventListener('click', () => {
    const preset = btn.getAttribute('data-sharpen-preset');
    
    switch (preset) {
      case 'subtle':
        adjustments.sharpenAmount = 50;
        adjustments.sharpenRadius = 1;
        adjustments.sharpenThreshold = 5;
        break;
      case 'moderate':
        adjustments.sharpenAmount = 100;
        adjustments.sharpenRadius = 1.5;
        adjustments.sharpenThreshold = 10;
        break;
      case 'strong':
        adjustments.sharpenAmount = 150;
        adjustments.sharpenRadius = 2;
        adjustments.sharpenThreshold = 15;
        break;
      case 'extreme':
        adjustments.sharpenAmount = 200;
        adjustments.sharpenRadius = 2.5;
        adjustments.sharpenThreshold = 20;
        break;
    }
    
    // Update UI
    sharpenAmountSlider.value = adjustments.sharpenAmount;
    sharpenRadiusSlider.value = adjustments.sharpenRadius;
    sharpenThresholdSlider.value = adjustments.sharpenThreshold;
    
    document.getElementById('sharpenAmountValue').textContent = adjustments.sharpenAmount;
    document.getElementById('sharpenRadiusValue').textContent = adjustments.sharpenRadius;
    document.getElementById('sharpenThresholdValue').textContent = adjustments.sharpenThreshold;
    
    applySharpenFilter();
    showMessage(`✓ ${preset.charAt(0).toUpperCase() + preset.slice(1)} sharpen applied!`, 'success');
  });
});

// Apply sharpen filter using Unsharp Mask algorithm
function applySharpenFilter() {
  if (!previewImage.src || !previewImage.complete || !selectedFile) {
    return;
  }
  
  if (adjustments.sharpenAmount === 0) {
    applyFilters();
    return;
  }
  
  const tempCanvas = document.createElement('canvas');
  const tempCtx = tempCanvas.getContext('2d');
  
  const img = new Image();
  img.crossOrigin = 'anonymous';
  
  img.onload = () => {
    tempCanvas.width = img.width;
    tempCanvas.height = img.height;
    tempCtx.drawImage(img, 0, 0);
    
    const imageData = tempCtx.getImageData(0, 0, tempCanvas.width, tempCanvas.height);
    const data = imageData.data;
    const width = tempCanvas.width;
    const height = tempCanvas.height;
    
    // Create a copy for blur calculation
    const blurredData = new Uint8ClampedArray(data);
    
    // Apply Gaussian blur (simple box blur for performance)
    const radius = Math.round(adjustments.sharpenRadius);
    const kernelSize = radius * 2 + 1;
    
    // Horizontal blur pass
    for (let y = 0; y < height; y++) {
      for (let x = 0; x < width; x++) {
        let r = 0, g = 0, b = 0, count = 0;
        
        for (let kx = -radius; kx <= radius; kx++) {
          const px = Math.min(Math.max(x + kx, 0), width - 1);
          const idx = (y * width + px) * 4;
          
          r += data[idx];
          g += data[idx + 1];
          b += data[idx + 2];
          count++;
        }
        
        const idx = (y * width + x) * 4;
        blurredData[idx] = r / count;
        blurredData[idx + 1] = g / count;
        blurredData[idx + 2] = b / count;
      }
    }
    
    // Vertical blur pass
    const tempBlur = new Uint8ClampedArray(blurredData);
    for (let y = 0; y < height; y++) {
      for (let x = 0; x < width; x++) {
        let r = 0, g = 0, b = 0, count = 0;
        
        for (let ky = -radius; ky <= radius; ky++) {
          const py = Math.min(Math.max(y + ky, 0), height - 1);
          const idx = (py * width + x) * 4;
          
          r += tempBlur[idx];
          g += tempBlur[idx + 1];
          b += tempBlur[idx + 2];
          count++;
        }
        
        const idx = (y * width + x) * 4;
        blurredData[idx] = r / count;
        blurredData[idx + 1] = g / count;
        blurredData[idx + 2] = b / count;
      }
    }
    
    // Apply unsharp mask: sharpened = original + amount * (original - blurred)
    const amount = adjustments.sharpenAmount / 100;
    const threshold = adjustments.sharpenThreshold;
    
    for (let i = 0; i < data.length; i += 4) {
      const origR = data[i];
      const origG = data[i + 1];
      const origB = data[i + 2];
      
      const blurR = blurredData[i];
      const blurG = blurredData[i + 1];
      const blurB = blurredData[i + 2];
      
      // Calculate difference
      const diffR = origR - blurR;
      const diffG = origG - blurG;
      const diffB = origB - blurB;
      
      // Apply threshold - only sharpen if difference is above threshold
      const diff = Math.abs(diffR) + Math.abs(diffG) + Math.abs(diffB);
      
      if (diff > threshold) {
        data[i] = Math.max(0, Math.min(255, origR + diffR * amount));
        data[i + 1] = Math.max(0, Math.min(255, origG + diffG * amount));
        data[i + 2] = Math.max(0, Math.min(255, origB + diffB * amount));
      }
    }
    
    tempCtx.putImageData(imageData, 0, 0);
    previewImage.src = tempCanvas.toDataURL();
    
    // Apply other filters on top
    applyFilters();
    
    // Save to history
    if (!isApplyingHistory) {
      saveToHistory('Sharpen', `Amount: ${adjustments.sharpenAmount}, Radius: ${adjustments.sharpenRadius}`);
    }
  };
  
  const reader = new FileReader();
  reader.onload = (e) => {
    img.src = e.target.result;
  };
  reader.readAsDataURL(selectedFile);
}

// Reset sharpen button
document.querySelectorAll('[data-reset="sharpen"]').forEach(btn => {
  btn.addEventListener('click', () => {
    adjustments.sharpenAmount = 0;
    adjustments.sharpenRadius = 1;
    adjustments.sharpenThreshold = 0;
    
    if (sharpenAmountSlider) sharpenAmountSlider.value = 0;
    if (sharpenRadiusSlider) sharpenRadiusSlider.value = 1;
    if (sharpenThresholdSlider) sharpenThresholdSlider.value = 0;
    
    document.getElementById('sharpenAmountValue').textContent = '0';
    document.getElementById('sharpenRadiusValue').textContent = '1';
    document.getElementById('sharpenThresholdValue').textContent = '0';
    
    // Reset to original image
    if (selectedFile) {
      const reader = new FileReader();
      reader.onload = (e) => {
        previewImage.src = e.target.result;
        applyFilters();
      };
      reader.readAsDataURL(selectedFile);
    }
    
    showMessage('✓ Sharpen reset', 'success');
  });
});

// ============================================
// BLUR EVENT LISTENERS
// ============================================
const blurAmountSlider = document.getElementById('blurAmountSlider');

if (blurAmountSlider) {
  blurAmountSlider.addEventListener('input', (e) => {
    adjustments.blurAmount = parseFloat(e.target.value);
    document.getElementById('blurAmountValue').textContent = adjustments.blurAmount;
    applyFilters();
  });
}

// Reset blur button
document.querySelectorAll('[data-reset="blur"]').forEach(btn => {
  btn.addEventListener('click', () => {
    adjustments.blurAmount = 0;
    
    if (blurAmountSlider) blurAmountSlider.value = 0;
    document.getElementById('blurAmountValue').textContent = '0';
    
    applyFilters();
    showMessage('✓ Blur reset', 'success');
  });
});

// ============================================
// FLIP EVENT LISTENERS
// ============================================
const flipHorizontalBtn = document.getElementById('flipHorizontalBtn');
const flipVerticalBtn = document.getElementById('flipVerticalBtn');

if (flipHorizontalBtn) {
  flipHorizontalBtn.addEventListener('click', () => {
    adjustments.flipHorizontal = !adjustments.flipHorizontal;
    applyFilters();
    saveToHistory('Flip Horizontal', adjustments.flipHorizontal ? 'Enabled' : 'Disabled');
    showMessage(`✓ Flip horizontal ${adjustments.flipHorizontal ? 'enabled' : 'disabled'}`, 'success');
  });
}

if (flipVerticalBtn) {
  flipVerticalBtn.addEventListener('click', () => {
    adjustments.flipVertical = !adjustments.flipVertical;
    applyFilters();
    saveToHistory('Flip Vertical', adjustments.flipVertical ? 'Enabled' : 'Disabled');
    showMessage(`✓ Flip vertical ${adjustments.flipVertical ? 'enabled' : 'disabled'}`, 'success');
  });
}

// ============================================
// ROTATE EVENT LISTENERS
// ============================================
const rotateAngleSlider = document.getElementById('rotateAngleSlider');
const rotate90Btn = document.getElementById('rotate90Btn');
const rotate180Btn = document.getElementById('rotate180Btn');
const rotate270Btn = document.getElementById('rotate270Btn');
const rotate0Btn = document.getElementById('rotate0Btn');

if (rotateAngleSlider) {
  rotateAngleSlider.addEventListener('input', (e) => {
    adjustments.rotateAngle = parseInt(e.target.value);
    document.getElementById('rotateAngleValue').textContent = adjustments.rotateAngle + '°';
    applyFilters();
  });
}

// Quick rotate buttons
if (rotate90Btn) {
  rotate90Btn.addEventListener('click', () => {
    adjustments.rotateAngle = 90;
    rotateAngleSlider.value = 90;
    document.getElementById('rotateAngleValue').textContent = '90°';
    applyFilters();
    saveToHistory('Rotate', '90°');
    showMessage('✓ Rotated 90°', 'success');
  });
}

if (rotate180Btn) {
  rotate180Btn.addEventListener('click', () => {
    adjustments.rotateAngle = 180;
    rotateAngleSlider.value = 180;
    document.getElementById('rotateAngleValue').textContent = '180°';
    applyFilters();
    saveToHistory('Rotate', '180°');
    showMessage('✓ Rotated 180°', 'success');
  });
}

if (rotate270Btn) {
  rotate270Btn.addEventListener('click', () => {
    adjustments.rotateAngle = 270;
    rotateAngleSlider.value = 270;
    document.getElementById('rotateAngleValue').textContent = '270°';
    applyFilters();
    saveToHistory('Rotate', '270°');
    showMessage('✓ Rotated 270°', 'success');
  });
}

if (rotate0Btn) {
  rotate0Btn.addEventListener('click', () => {
    adjustments.rotateAngle = 0;
    rotateAngleSlider.value = 0;
    document.getElementById('rotateAngleValue').textContent = '0°';
    applyFilters();
    showMessage('✓ Rotation reset', 'success');
  });
}

// Reset rotate button
document.querySelectorAll('[data-reset="rotate"]').forEach(btn => {
  btn.addEventListener('click', () => {
    adjustments.rotateAngle = 0;
    
    if (rotateAngleSlider) rotateAngleSlider.value = 0;
    document.getElementById('rotateAngleValue').textContent = '0°';
    
    applyFilters();
    showMessage('✓ Rotation reset', 'success');
  });
});

// Panel tabs functionality
const panelTabs = document.querySelectorAll('.panel-tab');
const tabContents = document.querySelectorAll('.tab-content');

panelTabs.forEach(tab => {
  tab.addEventListener('click', () => {
    const targetTab = tab.getAttribute('data-tab');
    
    // Remove active class from all tabs and contents
    panelTabs.forEach(t => t.classList.remove('active'));
    tabContents.forEach(c => c.classList.remove('active'));
    
    // Add active class to clicked tab and corresponding content
    tab.classList.add('active');
    const targetContent = document.getElementById('tab' + targetTab.charAt(0).toUpperCase() + targetTab.slice(1));
    if (targetContent) {
      targetContent.classList.add('active');
    }
  });
});

// Download and Remove Background buttons are already defined earlier in the file

// Reset panel buttons
document.querySelectorAll('[data-reset]').forEach(btn => {
  btn.addEventListener('click', () => {
    const panel = btn.getAttribute('data-reset');
    
    switch (panel) {
      case 'hueSaturation':
        adjustments.hue = 0;
        adjustments.saturation = 0;
        adjustments.lightness = 0;
        hueSlider.value = 0;
        saturationSlider.value = 0;
        if (lightnessSlider) lightnessSlider.value = 0;
        document.getElementById('hueValue').textContent = '0°';
        document.getElementById('saturationValue').textContent = '0';
        if (document.getElementById('lightnessValue')) {
          document.getElementById('lightnessValue').textContent = '0';
        }
        updateColorPreview();
        break;
        
      case 'brightnessContrast':
        adjustments.brightness = 0;
        adjustments.contrast = 0;
        if (brightnessSlider) brightnessSlider.value = 0;
        if (contrastSlider) contrastSlider.value = 0;
        if (document.getElementById('brightnessValue')) {
          document.getElementById('brightnessValue').textContent = '0';
        }
        if (document.getElementById('contrastValue')) {
          document.getElementById('contrastValue').textContent = '0';
        }
        updateComparisonBars();
        break;
        
      case 'curves':
        curvePoints = [{ x: 0, y: 0 }, { x: 255, y: 255 }];
        if (curveCanvas) drawCurve();
        applyCurveFilter();
        break;
        
      case 'levels':
        levelsValues = {
          channel: 'rgb',
          shadows: 0,
          midtones: 1.0,
          highlights: 255,
          outputBlack: 0,
          outputWhite: 255
        };
        if (shadowsSlider) {
          shadowsSlider.value = 0;
          shadowsInput.value = 0;
        }
        if (midtonesSlider) {
          midtonesSlider.value = 1.0;
          midtonesInput.value = '1.00';
        }
        if (highlightsSlider) {
          highlightsSlider.value = 255;
          highlightsInput.value = 255;
        }
        if (outputBlackSlider) outputBlackSlider.value = 0;
        if (outputWhiteSlider) outputWhiteSlider.value = 255;
        if (document.getElementById('outputBlackValue')) {
          document.getElementById('outputBlackValue').textContent = '0';
        }
        if (document.getElementById('outputWhiteValue')) {
          document.getElementById('outputWhiteValue').textContent = '255';
        }
        if (levelsCanvas) drawLevelsHistogram();
        applyLevels();
        break;
        
      case 'colorBalance':
        adjustments.shadowsCyan = 0;
        adjustments.shadowsMagenta = 0;
        adjustments.shadowsYellow = 0;
        adjustments.midtonesCyan = 0;
        adjustments.midtonesMagenta = 0;
        adjustments.midtonesYellow = 0;
        adjustments.highlightsCyan = 0;
        adjustments.highlightsMagenta = 0;
        adjustments.highlightsYellow = 0;
        
        Object.keys(colorBalanceSliders).forEach(key => {
          const slider = colorBalanceSliders[key];
          if (slider) {
            slider.value = 0;
            document.getElementById(key + 'Value').textContent = '0';
          }
        });
        break;
        
      case 'vibrance':
        adjustments.vibrance = 0;
        adjustments.saturationVibrance = 0;
        if (vibranceSlider) vibranceSlider.value = 0;
        if (saturationVibranceSlider) saturationVibranceSlider.value = 0;
        if (document.getElementById('vibranceValue')) {
          document.getElementById('vibranceValue').textContent = '0';
        }
        if (document.getElementById('saturationVibranceValue')) {
          document.getElementById('saturationVibranceValue').textContent = '0';
        }
        break;
        
      case 'whiteBalance':
        adjustments.temperature = 0;
        adjustments.tint = 0;
        if (temperatureSlider) temperatureSlider.value = 0;
        if (tintSlider) tintSlider.value = 0;
        if (document.getElementById('temperatureValue')) {
          document.getElementById('temperatureValue').textContent = '0';
        }
        if (document.getElementById('tintValue')) {
          document.getElementById('tintValue').textContent = '0';
        }
        break;
    }
    
    applyFilters();
    showMessage(`✓ ${panel} reset`, 'success');
  });
});

console.log('Image Upload Studio initialized successfully!');

// AI Sharpen functionality
const aiSharpenBtn = document.getElementById('aiSharpenBtn');
if (aiSharpenBtn) {
  aiSharpenBtn.addEventListener('click', async () => {
    if (!selectedFile) return;
    
    // Show AI Sharpen modal
    showAISharpenModal();
  });
}

// Show AI Sharpen modal with options
function showAISharpenModal() {
  // Create modal
  const modal = document.createElement('div');
  modal.className = 'ai-sharpen-modal';
  modal.innerHTML = `
    <div class="ai-sharpen-content">
      <div class="ai-sharpen-header">
        <h3>🤖 AI Sharpen - Làm nét ảnh thông minh</h3>
        <button class="ai-sharpen-close" onclick="this.closest('.ai-sharpen-modal').remove()">×</button>
      </div>
      
      <div class="ai-sharpen-body">
        <div class="ai-sharpen-info">
          <p>AI sẽ tự động phát hiện các vùng quan trọng và làm nét một cách thông minh, giữ nguyên chi tiết và giảm nhiễu.</p>
        </div>
        
        <div class="ai-sharpen-options">
          <div class="option-group">
            <label class="option-label">Cường độ làm nét:</label>
            <div class="option-buttons">
              <button class="option-btn active" data-strength="subtle">Nhẹ</button>
              <button class="option-btn" data-strength="moderate">Vừa</button>
              <button class="option-btn" data-strength="strong">Mạnh</button>
              <button class="option-btn" data-strength="extreme">Cực mạnh</button>
            </div>
          </div>
          
          <div class="option-group">
            <label class="option-checkbox">
              <input type="checkbox" id="aiPreserveDetails" checked>
              <span>Bảo toàn chi tiết quan trọng</span>
            </label>
          </div>
          
          <div class="option-group">
            <label class="option-checkbox">
              <input type="checkbox" id="aiReduceNoise" checked>
              <span>Giảm nhiễu trước khi làm nét</span>
            </label>
          </div>
          
          <div class="option-group">
            <label class="option-checkbox">
              <input type="checkbox" id="aiAdaptiveSharpen" checked>
              <span>Làm nét thích ứng (AI phát hiện cạnh)</span>
            </label>
          </div>
        </div>
        
        <div class="ai-sharpen-progress" style="display: none;">
          <div class="progress-bar">
            <div class="progress-fill" id="aiSharpenProgress"></div>
          </div>
          <div class="progress-text" id="aiSharpenProgressText">Đang xử lý...</div>
        </div>
      </div>
      
      <div class="ai-sharpen-footer">
        <button class="ai-btn ai-btn-cancel" onclick="this.closest('.ai-sharpen-modal').remove()">Hủy</button>
        <button class="ai-btn ai-btn-apply" id="applyAISharpen">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
          </svg>
          Áp dụng AI Sharpen
        </button>
      </div>
    </div>
  `;
  
  document.body.appendChild(modal);
  
  // Handle strength selection
  const strengthBtns = modal.querySelectorAll('[data-strength]');
  let selectedStrength = 'subtle';
  
  strengthBtns.forEach(btn => {
    btn.addEventListener('click', () => {
      strengthBtns.forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      selectedStrength = btn.getAttribute('data-strength');
    });
  });
  
  // Handle apply button
  const applyBtn = modal.querySelector('#applyAISharpen');
  applyBtn.addEventListener('click', async () => {
    const preserveDetails = modal.querySelector('#aiPreserveDetails').checked;
    const reduceNoise = modal.querySelector('#aiReduceNoise').checked;
    const adaptiveSharpen = modal.querySelector('#aiAdaptiveSharpen').checked;
    
    await applyAISharpen({
      strength: selectedStrength,
      preserveDetails,
      reduceNoise,
      adaptiveSharpen
    }, modal);
  });
}

// Apply AI Sharpen to image
async function applyAISharpen(options, modal) {
  if (!selectedFile) return;
  
  const progressBar = modal.querySelector('#aiSharpenProgress');
  const progressText = modal.querySelector('#aiSharpenProgressText');
  const progressContainer = modal.querySelector('.ai-sharpen-progress');
  const applyBtn = modal.querySelector('#applyAISharpen');
  
  // Show progress
  progressContainer.style.display = 'block';
  applyBtn.disabled = true;
  
  try {
    // Initialize AI Sharpener
    const sharpener = new AISharpener();
    
    // Progress callback
    const progressCallback = (stage, current, total) => {
      const percent = (current / total) * 100;
      progressBar.style.width = percent + '%';
      
      const stageNames = {
        'analyzing': '🔍 Đang phân tích ảnh...',
        'processing': '⚙️ Đang xử lý...',
        'finalizing': '✨ Đang hoàn thiện...',
        'complete': '✅ Hoàn thành!'
      };
      
      progressText.textContent = stageNames[stage] || 'Đang xử lý...';
    };
    
    // Apply AI sharpening
    const blob = await sharpener.sharpen(selectedFile, {
      ...options,
      progress: progressCallback
    });
    
    // Update preview image
    const url = URL.createObjectURL(blob);
    previewImage.src = url;
    
    // Update selected file
    const file = new File([blob], 'ai-sharpened-' + selectedFile.name, { type: 'image/png' });
    selectedFile = file;
    
    // Update file info
    displayFileInfo(file);
    
    // Close modal
    setTimeout(() => {
      modal.remove();
      showMessage('✓ AI Sharpen áp dụng thành công!', 'success');
      updateStatus('AI Sharpen hoàn thành', true);
      
      // Save to history
      saveToHistory('AI Sharpen', `Strength: ${options.strength}`);
      
      // Recalculate histogram
      setTimeout(() => {
        calculateHistogram();
      }, 100);
    }, 500);
    
  } catch (error) {
    console.error('AI Sharpen error:', error);
    progressText.textContent = '❌ Lỗi: ' + error.message;
    progressBar.style.width = '0%';
    progressBar.style.background = '#f44336';
    applyBtn.disabled = false;
    
    showMessage('❌ Lỗi khi áp dụng AI Sharpen: ' + error.message, 'error');
  }
}

// Add CSS for AI Sharpen modal
const aiSharpenStyles = document.createElement('style');
aiSharpenStyles.textContent = `
  .ai-sharpen-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
    animation: fadeIn 0.3s ease;
  }
  
  @keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
  }
  
  .ai-sharpen-content {
    background: #2d2d2d;
    border-radius: 12px;
    width: 90%;
    max-width: 500px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.6);
    animation: slideUp 0.3s ease;
  }
  
  @keyframes slideUp {
    from {
      transform: translateY(20px);
      opacity: 0;
    }
    to {
      transform: translateY(0);
      opacity: 1;
    }
  }
  
  .ai-sharpen-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #3c3c3c;
  }
  
  .ai-sharpen-header h3 {
    margin: 0;
    font-size: 18px;
    color: #ffffff;
    font-weight: 600;
  }
  
  .ai-sharpen-close {
    background: none;
    border: none;
    color: #888888;
    font-size: 32px;
    cursor: pointer;
    padding: 0;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    transition: all 0.2s;
  }
  
  .ai-sharpen-close:hover {
    background: #3c3c3c;
    color: #ffffff;
  }
  
  .ai-sharpen-body {
    padding: 20px;
  }
  
  .ai-sharpen-info {
    background: #1e1e1e;
    border: 1px solid #3c3c3c;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 20px;
  }
  
  .ai-sharpen-info p {
    margin: 0;
    color: #cccccc;
    font-size: 13px;
    line-height: 1.6;
  }
  
  .ai-sharpen-options {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  
  .option-group {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  
  .option-label {
    font-size: 13px;
    color: #888888;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }
  
  .option-buttons {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 8px;
  }
  
  .option-btn {
    background: #3c3c3c;
    border: 2px solid #4a4a4a;
    color: #cccccc;
    padding: 10px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 12px;
    font-weight: 600;
    transition: all 0.2s;
  }
  
  .option-btn:hover {
    background: #4a4a4a;
    border-color: #5a5a5a;
  }
  
  .option-btn.active {
    background: #4a9eff;
    border-color: #4a9eff;
    color: #ffffff;
  }
  
  .option-checkbox {
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
    font-size: 13px;
    color: #cccccc;
    padding: 10px;
    background: #1e1e1e;
    border-radius: 6px;
    transition: all 0.2s;
  }
  
  .option-checkbox:hover {
    background: #252525;
  }
  
  .option-checkbox input[type="checkbox"] {
    width: 18px;
    height: 18px;
    cursor: pointer;
  }
  
  .ai-sharpen-progress {
    margin-top: 20px;
  }
  
  .progress-bar {
    width: 100%;
    height: 8px;
    background: #1e1e1e;
    border-radius: 4px;
    overflow: hidden;
    margin-bottom: 10px;
  }
  
  .progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #4a9eff, #5ab0ff);
    border-radius: 4px;
    transition: width 0.3s ease;
    width: 0%;
  }
  
  .progress-text {
    text-align: center;
    color: #4a9eff;
    font-size: 13px;
    font-weight: 600;
  }
  
  .ai-sharpen-footer {
    display: flex;
    gap: 10px;
    padding: 20px;
    border-top: 1px solid #3c3c3c;
  }
  
  .ai-btn {
    flex: 1;
    padding: 12px 20px;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
  }
  
  .ai-btn-cancel {
    background: #3c3c3c;
    color: #cccccc;
  }
  
  .ai-btn-cancel:hover {
    background: #4a4a4a;
  }
  
  .ai-btn-apply {
    background: #4a9eff;
    color: #ffffff;
  }
  
  .ai-btn-apply:hover:not(:disabled) {
    background: #5ab0ff;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(74, 158, 255, 0.4);
  }
  
  .ai-btn-apply:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
`;
document.head.appendChild(aiSharpenStyles);

console.log('AI Sharpen functionality initialized!');

// Helper functions to safely access variables for session/project managers
window.getAdjustments = () => adjustments;
window.getBwEnabled = () => typeof bwEnabled !== 'undefined' ? bwEnabled : false;
window.getCurvePoints = () => typeof curvePoints !== 'undefined' ? curvePoints : {};
window.getLevelsValues = () => typeof levelsValues !== 'undefined' ? levelsValues : {};
window.getCurrentZoom = () => typeof currentZoom !== 'undefined' ? currentZoom : 1;
window.getSelectedFile = () => selectedFile;
window.getPreviewImage = () => previewImage;

// Setters for restoration
window.setAdjustments = (val) => { Object.assign(adjustments, val); };
window.setBwEnabled = (val) => { if (typeof bwEnabled !== 'undefined') bwEnabled = val; };
window.setCurvePoints = (val) => { if (typeof curvePoints !== 'undefined') Object.assign(curvePoints, val); };
window.setLevelsValues = (val) => { if (typeof levelsValues !== 'undefined') Object.assign(levelsValues, val); };
window.setCurrentZoom = (val) => { if (typeof currentZoom !== 'undefined') currentZoom = val; };
window.setSelectedFile = (val) => { selectedFile = val; };

// Export utility functions
window.displayFileInfo = displayFileInfo;
window.handleFile = handleFile;
