/**
 * Batch Image Processor
 * Handle multiple images with batch processing
 */

let batchImages = [];
let currentBatchIndex = 0;
let batchMode = false;

/**
 * Initialize batch processor
 */
function initBatchProcessor() {
  const fileInput = document.getElementById('fileInput');
  
  // Allow multiple file selection
  if (fileInput) {
    fileInput.setAttribute('multiple', 'multiple');
    
    // Override the change handler to support batch
    const originalHandler = fileInput.onchange;
    fileInput.onchange = null;
    
    fileInput.addEventListener('change', (e) => {
      const files = Array.from(e.target.files);
      
      if (files.length > 1) {
        // Batch mode
        handleBatchFiles(files);
      } else if (files.length === 1) {
        // Single mode - use original handler
        if (typeof handleFile === 'function') {
          handleFile(files[0]);
        }
      }
    });
  }
  
  // Setup batch controls
  setupBatchControls();
  
  console.log('✓ Batch processor initialized');
}

/**
 * Handle multiple files
 */
function handleBatchFiles(files) {
  if (files.length === 0) return;
  
  batchMode = true;
  batchImages = [];
  currentBatchIndex = 0;
  
  showLoading(`Đang tải ${files.length} ảnh...`);
  
  // Load all images
  let loadedCount = 0;
  
  files.forEach((file, index) => {
    if (!file.type.startsWith('image/')) {
      console.warn('Skipping non-image file:', file.name);
      return;
    }
    
    const reader = new FileReader();
    
    reader.onload = (e) => {
      const img = new Image();
      img.onload = () => {
        batchImages.push({
          file: file,
          dataUrl: e.target.result,
          width: img.width,
          height: img.height,
          adjustments: null, // Will store individual adjustments
          processed: false
        });
        
        loadedCount++;
        
        if (loadedCount === files.length) {
          // All images loaded
          closeLoading();
          initBatchUI();
          loadBatchImage(0);
          showSuccess(`Đã tải ${batchImages.length} ảnh`);
        }
      };
      img.src = e.target.result;
    };
    
    reader.readAsDataURL(file);
  });
}

/**
 * Initialize batch UI
 */
function initBatchUI() {
  // Show batch gallery
  const batchGallery = document.getElementById('batchGallery');
  if (batchGallery) {
    batchGallery.style.display = 'flex';
    renderBatchThumbnails();
  }
  
  // Show batch controls
  const batchControls = document.getElementById('batchControls');
  if (batchControls) {
    batchControls.style.display = 'flex';
  }
  
  // Update counter
  updateBatchCounter();
}

/**
 * Render batch thumbnails
 */
function renderBatchThumbnails() {
  const container = document.getElementById('batchThumbnails');
  if (!container) return;
  
  container.innerHTML = '';
  
  batchImages.forEach((img, index) => {
    const thumb = document.createElement('div');
    thumb.className = 'batch-thumbnail';
    if (index === currentBatchIndex) {
      thumb.classList.add('active');
    }
    if (img.processed) {
      thumb.classList.add('processed');
    }
    
    thumb.innerHTML = `
      <img src="${img.dataUrl}" alt="${img.file.name}">
      <div class="batch-thumb-overlay">
        <span class="batch-thumb-name">${img.file.name}</span>
        ${img.processed ? '<span class="batch-thumb-check">✓</span>' : ''}
      </div>
      <button class="batch-thumb-remove" data-index="${index}" title="Xóa">×</button>
    `;
    
    thumb.addEventListener('click', (e) => {
      if (!e.target.classList.contains('batch-thumb-remove')) {
        loadBatchImage(index);
      }
    });
    
    // Context menu (right click)
    thumb.addEventListener('contextmenu', (e) => {
      e.preventDefault();
      showBatchContextMenu(e, index);
    });
    
    // Remove button
    const removeBtn = thumb.querySelector('.batch-thumb-remove');
    removeBtn.addEventListener('click', (e) => {
      e.stopPropagation();
      removeBatchImage(index);
    });
    
    container.appendChild(thumb);
  });
}

/**
 * Load batch image by index
 */
function loadBatchImage(index) {
  if (index < 0 || index >= batchImages.length) return;
  
  currentBatchIndex = index;
  const img = batchImages[index];
  
  // Load image to preview
  const previewImage = document.getElementById('previewImage');
  if (previewImage) {
    previewImage.src = img.dataUrl;
  }
  
  // Set selected file
  if (window.setSelectedFile) {
    window.setSelectedFile(img.file);
  }
  
  // Show image container
  const canvasPlaceholder = document.getElementById('canvasPlaceholder');
  const imageContainer = document.getElementById('imageContainer');
  if (canvasPlaceholder) canvasPlaceholder.style.display = 'none';
  if (imageContainer) imageContainer.style.display = 'flex';
  
  // Load saved adjustments if exists
  if (img.adjustments) {
    if (window.setAdjustments) {
      window.setAdjustments(img.adjustments);
    }
    if (typeof updateAllControls === 'function') {
      updateAllControls();
    }
    if (typeof applyFilters === 'function') {
      setTimeout(() => applyFilters(false), 100);
    }
  } else {
    // Reset adjustments for new image
    resetAdjustmentsQuiet();
  }
  
  // Update UI
  renderBatchThumbnails();
  updateBatchCounter();
  
  // Enable buttons
  enableEditingButtons();
  
  // Display file info
  if (typeof displayFileInfo === 'function') {
    displayFileInfo(img.file);
  }
}

/**
 * Save current adjustments to batch image
 */
function saveBatchAdjustments() {
  if (!batchMode || currentBatchIndex < 0) return;
  
  const getAdjustments = window.getAdjustments || (() => ({}));
  batchImages[currentBatchIndex].adjustments = JSON.parse(JSON.stringify(getAdjustments()));
  batchImages[currentBatchIndex].processed = true;
  
  renderBatchThumbnails();
}

/**
 * Remove image from batch
 */
function removeBatchImage(index) {
  if (index < 0 || index >= batchImages.length) return;
  
  batchImages.splice(index, 1);
  
  if (batchImages.length === 0) {
    // Exit batch mode
    exitBatchMode();
    return;
  }
  
  // Adjust current index
  if (currentBatchIndex >= batchImages.length) {
    currentBatchIndex = batchImages.length - 1;
  }
  
  loadBatchImage(currentBatchIndex);
}

/**
 * Navigate batch
 */
function batchPrevious() {
  saveBatchAdjustments();
  if (currentBatchIndex > 0) {
    loadBatchImage(currentBatchIndex - 1);
  }
}

function batchNext() {
  saveBatchAdjustments();
  if (currentBatchIndex < batchImages.length - 1) {
    loadBatchImage(currentBatchIndex + 1);
  }
}

/**
 * Show context menu for batch thumbnail
 */
function showBatchContextMenu(event, imageIndex) {
  // Remove existing context menu
  const existingMenu = document.querySelector('.batch-context-menu');
  if (existingMenu) {
    existingMenu.remove();
  }
  
  const img = batchImages[imageIndex];
  if (!img.adjustments) {
    showWarning('Ảnh này chưa có settings để áp dụng');
    return;
  }
  
  // Create context menu
  const menu = document.createElement('div');
  menu.className = 'batch-context-menu';
  
  // Initially position off-screen to measure
  menu.style.visibility = 'hidden';
  menu.style.left = '0px';
  menu.style.top = '0px';
  
  const menuItems = [
    {
      icon: '📋',
      label: 'Áp dụng cho tất cả ảnh',
      action: () => applySettingsToAll(imageIndex)
    },
    {
      icon: '🎯',
      label: 'Áp dụng cho ảnh chưa xử lý',
      action: () => applySettingsToUnprocessed(imageIndex)
    },
    {
      icon: '✨',
      label: 'Áp dụng cho ảnh đã chọn...',
      action: () => selectAndApplySettings(imageIndex)
    },
    {
      icon: '📄',
      label: 'Sao chép settings',
      action: () => copySettings(imageIndex)
    }
  ];
  
  menuItems.forEach(item => {
    const menuItem = document.createElement('div');
    menuItem.className = 'batch-context-menu-item';
    menuItem.innerHTML = `<span class="menu-icon">${item.icon}</span><span>${item.label}</span>`;
    menuItem.addEventListener('click', () => {
      item.action();
      menu.remove();
    });
    menu.appendChild(menuItem);
  });
  
  document.body.appendChild(menu);
  
  // Calculate position after adding to DOM (so we can measure it)
  const menuRect = menu.getBoundingClientRect();
  const viewportWidth = window.innerWidth;
  const viewportHeight = window.innerHeight;
  
  let left = event.clientX;
  let top = event.clientY;
  
  // Adjust horizontal position if menu goes off-screen
  if (left + menuRect.width > viewportWidth) {
    left = viewportWidth - menuRect.width - 10; // 10px margin
  }
  
  // Adjust vertical position if menu goes off-screen
  if (top + menuRect.height > viewportHeight) {
    top = viewportHeight - menuRect.height - 10; // 10px margin
  }
  
  // Ensure menu doesn't go off the left edge
  if (left < 10) {
    left = 10;
  }
  
  // Ensure menu doesn't go off the top edge
  if (top < 10) {
    top = 10;
  }
  
  // Apply final position
  menu.style.left = left + 'px';
  menu.style.top = top + 'px';
  menu.style.visibility = 'visible';
  
  // Close menu when clicking outside
  setTimeout(() => {
    document.addEventListener('click', function closeMenu() {
      menu.remove();
      document.removeEventListener('click', closeMenu);
    });
  }, 100);
}

/**
 * Apply settings from one image to all images
 */
async function applySettingsToAll(sourceIndex) {
  if (!batchMode || !batchImages[sourceIndex].adjustments) return;
  
  const confirmed = await confirmAsync(`Áp dụng settings của "${batchImages[sourceIndex].file.name}" cho tất cả ${batchImages.length} ảnh?`);
  if (!confirmed) return;
  
  const sourceAdj = JSON.parse(JSON.stringify(batchImages[sourceIndex].adjustments));
  
  let appliedCount = 0;
  batchImages.forEach((img, index) => {
    if (index !== sourceIndex) {
      img.adjustments = JSON.parse(JSON.stringify(sourceAdj));
      img.processed = true;
      appliedCount++;
    }
  });
  
  renderBatchThumbnails();
  showSuccess(`Đã áp dụng settings cho ${appliedCount} ảnh`);
}

/**
 * Apply settings to unprocessed images only
 */
async function applySettingsToUnprocessed(sourceIndex) {
  if (!batchMode || !batchImages[sourceIndex].adjustments) return;
  
  const unprocessedImages = batchImages.filter(img => !img.processed);
  
  if (unprocessedImages.length === 0) {
    showMessage('Tất cả ảnh đã được xử lý', 'info');
    return;
  }
  
  const confirmed = await confirmAsync(`Áp dụng settings cho ${unprocessedImages.length} ảnh chưa xử lý?`);
  if (!confirmed) return;
  
  const sourceAdj = JSON.parse(JSON.stringify(batchImages[sourceIndex].adjustments));
  
  let appliedCount = 0;
  batchImages.forEach((img, index) => {
    if (!img.processed && index !== sourceIndex) {
      img.adjustments = JSON.parse(JSON.stringify(sourceAdj));
      img.processed = true;
      appliedCount++;
    }
  });
  
  renderBatchThumbnails();
  showSuccess(`Đã áp dụng settings cho ${appliedCount} ảnh chưa xử lý`);
}

/**
 * Select specific images and apply settings
 */
function selectAndApplySettings(sourceIndex) {
  if (!batchMode || !batchImages[sourceIndex].adjustments) return;
  
  // Show selection dialog
  showImageSelectionDialog(sourceIndex);
}

/**
 * Show image selection dialog
 */
function showImageSelectionDialog(sourceIndex) {
  // Create modal
  const modal = document.createElement('div');
  modal.className = 'batch-selection-modal';
  modal.innerHTML = `
    <div class="batch-selection-content">
      <div class="batch-selection-header">
        <h3>Chọn ảnh để áp dụng settings</h3>
        <button class="batch-selection-close">×</button>
      </div>
      <div class="batch-selection-body">
        <div class="batch-selection-grid" id="batchSelectionGrid"></div>
      </div>
      <div class="batch-selection-footer">
        <button class="batch-btn" id="selectAllBtn">Chọn tất cả</button>
        <button class="batch-btn" id="deselectAllBtn">Bỏ chọn tất cả</button>
        <button class="batch-btn batch-btn-primary" id="applySelectedBtn">Áp dụng</button>
        <button class="batch-btn" id="cancelSelectionBtn">Hủy</button>
      </div>
    </div>
  `;
  
  document.body.appendChild(modal);
  
  // Render image grid
  const grid = document.getElementById('batchSelectionGrid');
  batchImages.forEach((img, index) => {
    if (index === sourceIndex) return; // Skip source image
    
    const item = document.createElement('div');
    item.className = 'batch-selection-item';
    item.innerHTML = `
      <input type="checkbox" id="select-${index}" ${!img.processed ? 'checked' : ''}>
      <label for="select-${index}">
        <img src="${img.dataUrl}" alt="${img.file.name}">
        <span class="selection-name">${img.file.name}</span>
        ${img.processed ? '<span class="selection-badge">Đã xử lý</span>' : ''}
      </label>
    `;
    grid.appendChild(item);
  });
  
  // Event handlers
  document.querySelector('.batch-selection-close').addEventListener('click', () => modal.remove());
  document.getElementById('cancelSelectionBtn').addEventListener('click', () => modal.remove());
  
  document.getElementById('selectAllBtn').addEventListener('click', () => {
    grid.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = true);
  });
  
  document.getElementById('deselectAllBtn').addEventListener('click', () => {
    grid.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = false);
  });
  
  document.getElementById('applySelectedBtn').addEventListener('click', () => {
    const selected = [];
    grid.querySelectorAll('input[type="checkbox"]:checked').forEach(cb => {
      const index = parseInt(cb.id.replace('select-', ''));
      selected.push(index);
    });
    
    if (selected.length === 0) {
      showWarning('Chưa chọn ảnh nào');
      return;
    }
    
    applySettingsToSelected(sourceIndex, selected);
    modal.remove();
  });
  
  // Close on outside click
  modal.addEventListener('click', (e) => {
    if (e.target === modal) {
      modal.remove();
    }
  });
}

/**
 * Apply settings to selected images
 */
function applySettingsToSelected(sourceIndex, targetIndices) {
  if (!batchMode || !batchImages[sourceIndex].adjustments) return;
  
  const sourceAdj = JSON.parse(JSON.stringify(batchImages[sourceIndex].adjustments));
  
  targetIndices.forEach(index => {
    batchImages[index].adjustments = JSON.parse(JSON.stringify(sourceAdj));
    batchImages[index].processed = true;
  });
  
  renderBatchThumbnails();
  showSuccess(`Đã áp dụng settings cho ${targetIndices.length} ảnh`);
}

/**
 * Copy settings to clipboard
 */
function copySettings(sourceIndex) {
  if (!batchMode || !batchImages[sourceIndex].adjustments) return;
  
  const settings = JSON.stringify(batchImages[sourceIndex].adjustments);
  
  // Copy to clipboard
  navigator.clipboard.writeText(settings).then(() => {
    showSuccess('Đã sao chép settings');
  }).catch(() => {
    showError('Không thể sao chép');
  });
}

/**
 * Apply current adjustments to all images
 */
async function applyToAllBatch() {
  if (!batchMode) return;
  
  const confirmed = await confirmAsync(`Áp dụng settings hiện tại cho tất cả ${batchImages.length} ảnh?`);
  if (!confirmed) return;
  
  const getAdjustments = window.getAdjustments || (() => ({}));
  const currentAdj = JSON.parse(JSON.stringify(getAdjustments()));
  
  batchImages.forEach(img => {
    img.adjustments = JSON.parse(JSON.stringify(currentAdj));
    img.processed = true;
  });
  
  renderBatchThumbnails();
  showSuccess('Đã áp dụng settings cho tất cả ảnh');
}

/**
 * Export all batch images
 */
async function exportAllBatch() {
  if (!batchMode || batchImages.length === 0) return;
  
  showLoading(`Đang xuất ${batchImages.length} ảnh...`);
  
  for (let i = 0; i < batchImages.length; i++) {
    const img = batchImages[i];
    
    // Load image
    await loadBatchImageAsync(i);
    
    // Apply adjustments if exists
    if (img.adjustments) {
      if (window.setAdjustments) {
        window.setAdjustments(img.adjustments);
      }
      if (typeof applyFilters === 'function') {
        await new Promise(resolve => {
          applyFilters(false);
          setTimeout(resolve, 500);
        });
      }
    }
    
    // Download
    await downloadCurrentImage(img.file.name);
    
    // Update progress
    showProgress('Đang xuất ảnh...', i + 1, batchImages.length);
  }
  
  closeLoading();
  showSuccess(`Đã xuất ${batchImages.length} ảnh`);
}

/**
 * Load batch image async
 */
function loadBatchImageAsync(index) {
  return new Promise(resolve => {
    loadBatchImage(index);
    setTimeout(resolve, 300);
  });
}

/**
 * Download current image
 */
function downloadCurrentImage(filename) {
  return new Promise(resolve => {
    const previewImage = document.getElementById('previewImage');
    if (!previewImage || !previewImage.src) {
      resolve();
      return;
    }
    
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    
    canvas.width = previewImage.naturalWidth;
    canvas.height = previewImage.naturalHeight;
    
    ctx.drawImage(previewImage, 0, 0);
    
    canvas.toBlob(blob => {
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      resolve();
    }, 'image/png');
  });
}

/**
 * Exit batch mode
 */
function exitBatchMode() {
  batchMode = false;
  batchImages = [];
  currentBatchIndex = 0;
  
  const batchGallery = document.getElementById('batchGallery');
  if (batchGallery) {
    batchGallery.style.display = 'none';
  }
  
  const batchControls = document.getElementById('batchControls');
  if (batchControls) {
    batchControls.style.display = 'none';
  }
  
  // Clear preview
  const previewImage = document.getElementById('previewImage');
  if (previewImage) {
    previewImage.src = '';
  }
  
  const canvasPlaceholder = document.getElementById('canvasPlaceholder');
  const imageContainer = document.getElementById('imageContainer');
  if (canvasPlaceholder) canvasPlaceholder.style.display = 'block';
  if (imageContainer) imageContainer.style.display = 'none';
}

/**
 * Update batch counter
 */
function updateBatchCounter() {
  const counter = document.getElementById('batchCounter');
  if (counter && batchMode) {
    counter.textContent = `${currentBatchIndex + 1} / ${batchImages.length}`;
  }
}

/**
 * Reset adjustments without applying
 */
function resetAdjustmentsQuiet() {
  const defaultAdj = {
    brightness: 0,
    contrast: 0,
    saturation: 0,
    hue: 0,
    lightness: 0,
    temperature: 0,
    tint: 0
  };
  
  if (window.setAdjustments) {
    window.setAdjustments(defaultAdj);
  }
  
  if (typeof updateAllControls === 'function') {
    updateAllControls();
  }
}

/**
 * Setup batch controls
 */
function setupBatchControls() {
  const prevBtn = document.getElementById('batchPrevBtn');
  const nextBtn = document.getElementById('batchNextBtn');
  const applyAllBtn = document.getElementById('batchApplyAllBtn');
  const exportAllBtn = document.getElementById('batchExportAllBtn');
  const exitBatchBtn = document.getElementById('batchExitBtn');
  
  if (prevBtn) prevBtn.addEventListener('click', batchPrevious);
  if (nextBtn) nextBtn.addEventListener('click', batchNext);
  if (applyAllBtn) applyAllBtn.addEventListener('click', applyToAllBatch);
  if (exportAllBtn) exportAllBtn.addEventListener('click', exportAllBatch);
  if (exitBatchBtn) exitBatchBtn.addEventListener('click', exitBatchMode);
  
  // Keyboard shortcuts
  document.addEventListener('keydown', (e) => {
    if (!batchMode) return;
    
    if (e.key === 'ArrowLeft') {
      e.preventDefault();
      batchPrevious();
    } else if (e.key === 'ArrowRight') {
      e.preventDefault();
      batchNext();
    }
  });
}

/**
 * Hook into applyFilters to auto-save batch adjustments
 */
function hookBatchAutoSave() {
  const originalApplyFilters = window.applyFilters;
  if (originalApplyFilters) {
    window.applyFilters = function(...args) {
      const result = originalApplyFilters.apply(this, args);
      
      // Auto-save in batch mode
      if (batchMode) {
        setTimeout(() => saveBatchAdjustments(), 500);
      }
      
      return result;
    };
  }
}

// Auto-initialize
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => {
    initBatchProcessor();
    hookBatchAutoSave();
  });
} else {
  initBatchProcessor();
  hookBatchAutoSave();
}

/**
 * Set batch images (for project restore)
 */
function setBatchImages(images) {
  batchMode = true;
  batchImages = images;
  currentBatchIndex = 0;
  
  initBatchUI();
  loadBatchImage(0);
}

// Export functions
window.batchMode = () => batchMode;
window.batchImages = batchImages;
window.exitBatchMode = exitBatchMode;
window.setBatchImages = setBatchImages;
window.handleBatchFiles = handleBatchFiles;
