/**
 * Time Machine Integration
 * Connect Time Machine with the main app
 */

(function() {
  'use strict';

  // UI Elements
  const timeMachineBtn = document.getElementById('timeMachineBtn');
  const timeMachinePanel = document.getElementById('timeMachinePanel');
  const timeMachineCloseBtn = document.getElementById('timeMachineCloseBtn');
  const timelineBackBtn = document.getElementById('timelineBackBtn');
  const timelineForwardBtn = document.getElementById('timelineForwardBtn');
  const createBranchBtn = document.getElementById('createBranchBtn');
  const mergeBranchBtn = document.getElementById('mergeBranchBtn');

  // Toggle Time Machine panel
  if (timeMachineBtn) {
    timeMachineBtn.addEventListener('click', () => {
      timeMachinePanel.classList.toggle('active');
    });
  }

  // Close panel
  if (timeMachineCloseBtn) {
    timeMachineCloseBtn.addEventListener('click', () => {
      timeMachinePanel.classList.remove('active');
    });
  }

  // Navigation buttons
  if (timelineBackBtn) {
    timelineBackBtn.addEventListener('click', () => {
      window.timeMachine.goBack();
    });
  }

  if (timelineForwardBtn) {
    timelineForwardBtn.addEventListener('click', () => {
      window.timeMachine.goForward();
    });
  }

  // Create branch button
  if (createBranchBtn) {
    createBranchBtn.addEventListener('click', async () => {
      const currentCommit = window.timeMachine.getCurrentCommit();
      if (!currentCommit) {
        showMessage('No commit to branch from', 'error');
        return;
      }

      if (typeof Swal === 'undefined') {
        const name = prompt('Branch name:');
        if (name) {
          window.timeMachine.createBranch(name);
          showMessage(`✓ Created branch: ${name}`, 'success');
        }
        return;
      }

      const result = await Swal.fire({
        title: '🌿 Create Branch',
        input: 'text',
        inputLabel: 'Branch name',
        inputPlaceholder: 'experiment-1',
        showCancelButton: true,
        inputValidator: (value) => {
          if (!value) return 'Please enter a branch name';
          if (window.timeMachine.branches[value]) return 'Branch already exists';
        }
      });

      if (result.isConfirmed && result.value) {
        window.timeMachine.createBranch(result.value);
        showMessage(`✓ Created branch: ${result.value}`, 'success');
      }
    });
  }

  // Merge branch button
  if (mergeBranchBtn) {
    mergeBranchBtn.addEventListener('click', async () => {
      const branches = Object.keys(window.timeMachine.branches)
        .filter(b => b !== window.timeMachine.currentBranch);

      if (branches.length === 0) {
        showMessage('No other branches to merge', 'info');
        return;
      }

      if (typeof Swal === 'undefined') {
        const branch = prompt(`Merge from branch:\n${branches.join('\n')}`);
        if (branch && branches.includes(branch)) {
          await window.timeMachine.mergeBranch(branch);
          showMessage(`✓ Merged ${branch}`, 'success');
        }
        return;
      }

      const options = {};
      branches.forEach(b => {
        const branch = window.timeMachine.branches[b];
        options[b] = `${b} (${branch.commits.length} commits)`;
      });

      const result = await Swal.fire({
        title: '🔀 Merge Branch',
        input: 'select',
        inputOptions: options,
        inputPlaceholder: 'Select branch to merge',
        showCancelButton: true
      });

      if (result.isConfirmed && result.value) {
        await window.timeMachine.mergeBranch(result.value);
        showMessage(`✓ Merged ${result.value} into ${window.timeMachine.currentBranch}`, 'success');
      }
    });
  }

  // Keyboard shortcut: Alt+T to toggle Time Machine
  document.addEventListener('keydown', (e) => {
    if (e.altKey && e.key === 't') {
      e.preventDefault();
      timeMachinePanel.classList.toggle('active');
    }
  });

  // Hook into applyFilters to auto-commit
  const originalApplyFilters = window.applyFilters;
  if (originalApplyFilters) {
    window.applyFilters = function(saveHistory = true) {
      const result = originalApplyFilters.call(this, saveHistory);
      
      // Auto-commit to Time Machine
      if (saveHistory && !window.timeMachine.isApplying) {
        setTimeout(() => {
          const state = captureCurrentState();
          const action = getLastAction() || 'Adjustment';
          window.timeMachine.commit(action, state);
        }, 100);
      }
      
      return result;
    };
  }

  // Hook into handleFile to commit initial load
  const originalHandleFile = window.handleFile;
  if (originalHandleFile) {
    window.handleFile = function(file) {
      const result = originalHandleFile.call(this, file);
      
      // Commit initial load
      setTimeout(() => {
        const state = captureCurrentState();
        window.timeMachine.commit('Load Image', state);
      }, 500);
      
      return result;
    };
  }

  // Helper: Get last action from recent changes
  function getLastAction() {
    // Try to detect what changed
    if (window.lastVoiceCommand) {
      return `Voice: ${window.lastVoiceCommand}`;
    }
    
    if (window.lastPresetApplied) {
      return `Preset: ${window.lastPresetApplied}`;
    }
    
    // Check which adjustment changed
    const adjustmentNames = {
      brightness: 'Brightness',
      contrast: 'Contrast',
      saturation: 'Saturation',
      hue: 'Hue',
      temperature: 'Temperature',
      blur: 'Blur',
      sharpen: 'Sharpen'
    };
    
    for (const [key, name] of Object.entries(adjustmentNames)) {
      if (window.lastChangedAdjustment === key) {
        return name;
      }
    }
    
    return 'Adjustment';
  }

  // Helper: Capture current state
  function captureCurrentState() {
    return {
      imageData: window.previewImage?.src || null,
      adjustments: window.adjustments ? JSON.parse(JSON.stringify(window.adjustments)) : null,
      states: {
        bwEnabled: window.bwEnabled,
        curvePoints: window.curvePoints ? JSON.parse(JSON.stringify(window.curvePoints)) : null,
        levelsValues: window.levelsValues ? JSON.parse(JSON.stringify(window.levelsValues)) : null
      },
      cssFilter: window.previewImage?.style.filter || '',
      zoom: window.currentZoom || 1
    };
  }

  // Export helper
  window.captureCurrentState = captureCurrentState;

  console.log('[Time Machine Integration] Initialized ✓');
  console.log('[Time Machine Integration] Shortcut: Alt+T');

})();
