/**
 * History Integration
 * Integrates history manager with all app operations
 */

// Wait for history manager to be ready
function initHistoryIntegration() {
  if (!window.historyManager) {
    console.warn('[History Integration] Waiting for history manager...');
    setTimeout(initHistoryIntegration, 100);
    return;
  }

  console.log('[History Integration] Initializing...');

  // Hook into file upload
  hookFileUpload();
  
  // Hook into adjustments
  hookAdjustments();
  
  // Hook into special operations
  hookSpecialOperations();
  
  // Hook into UI buttons
  hookUIButtons();
  
  // Setup history panel
  setupHistoryPanel();

  console.log('[History Integration] All hooks installed ✓');
}

/**
 * Hook file upload to save initial state
 */
function hookFileUpload() {
  const originalHandleFile = window.handleFile;
  
  if (originalHandleFile) {
    window.handleFile = function(file) {
      originalHandleFile.call(this, file);
      
      // Save initial state after image loads
      setTimeout(() => {
        const state = captureCurrentState();
        historyManager.saveSnapshot('📁 Image Loaded: ' + file.name, state);
        console.log('[History] Initial state saved');
      }, 500);
    };
  }
}

/**
 * Hook all adjustment sliders
 */
function hookAdjustments() {
  // Create debounced save function
  const debouncedSave = debounce((action) => {
    const state = captureCurrentState();
    historyManager.saveSnapshot(action, state);
  }, 1000);

  // Hook all sliders
  const sliderIds = [
    'brightnessSlider', 'contrastSlider', 'saturationSlider', 'hueSlider',
    'lightnessSlider', 'temperatureSlider', 'tintSlider',
    'exposureSlider', 'offsetSlider', 'gammaCorrectionSlider',
    'vibranceSlider', 'saturationVibranceSlider',
    'sharpenAmountSlider', 'sharpenRadiusSlider', 'sharpenThresholdSlider'
  ];

  sliderIds.forEach(id => {
    const slider = document.getElementById(id);
    if (slider) {
      slider.addEventListener('change', () => {
        const label = slider.previousElementSibling?.querySelector('.control-label')?.textContent || id;
        debouncedSave('🎨 Adjusted: ' + label);
      });
    }
  });
}

/**
 * Hook special operations
 */
function hookSpecialOperations() {
  // Hook Remove Background
  const removeBackgroundBtn = document.getElementById('removeBackgroundBtn');
  if (removeBackgroundBtn) {
    removeBackgroundBtn.addEventListener('click', () => {
      setTimeout(() => {
        const state = captureCurrentState();
        historyManager.saveSnapshot('🎭 Remove Background', state);
      }, 2000);
    });
  }

  // Hook AI Sharpen
  const aiSharpenBtn = document.getElementById('aiSharpenBtn');
  if (aiSharpenBtn) {
    aiSharpenBtn.addEventListener('click', () => {
      setTimeout(() => {
        const state = captureCurrentState();
        historyManager.saveSnapshot('✨ AI Sharpen', state);
      }, 2000);
    });
  }

  // Hook Clear/Delete
  const headerClearBtn = document.getElementById('headerClearBtn');
  if (headerClearBtn) {
    const originalClick = headerClearBtn.onclick;
    headerClearBtn.onclick = function(e) {
      const state = captureCurrentState();
      historyManager.saveSnapshot('🗑️ Clear Image', state);
      if (originalClick) originalClick.call(this, e);
    };
  }
}

/**
 * Hook UI buttons
 */
function hookUIButtons() {
  const undoBtn = document.getElementById('undoBtn');
  const redoBtn = document.getElementById('redoBtn');

  if (undoBtn) {
    undoBtn.addEventListener('click', () => {
      historyManager.undo();
    });
  }

  if (redoBtn) {
    redoBtn.addEventListener('click', () => {
      historyManager.redo();
    });
  }
}

/**
 * Setup history panel
 */
function setupHistoryPanel() {
  const historyBtn = document.getElementById('historyBtn');
  const historyPanel = document.getElementById('historyPanel');
  const historyCloseBtn = document.getElementById('historyCloseBtn');

  if (historyBtn && historyPanel) {
    historyBtn.addEventListener('click', () => {
      historyPanel.style.display = historyPanel.style.display === 'none' ? 'flex' : 'none';
      historyManager.updateHistoryPanel();
    });
  }

  if (historyCloseBtn && historyPanel) {
    historyCloseBtn.addEventListener('click', () => {
      historyPanel.style.display = 'none';
    });
  }
}

/**
 * Debounce helper
 */
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

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

console.log('[History Integration] Module loaded ✓');
