/**
 * Session Manager
 * Auto-save and restore editing session
 */

const SESSION_KEY = 'imageEditor_lastSession';
const SESSION_TIMEOUT = 24 * 60 * 60 * 1000; // 24 hours

/**
 * Save current session to localStorage
 */
function saveSession() {
  const getSelectedFile = window.getSelectedFile || (() => null);
  const getPreviewImage = window.getPreviewImage || (() => ({ src: '' }));
  
  const file = getSelectedFile();
  const img = getPreviewImage();
  
  if (!file || !img.src) {
    return;
  }

  try {
    const getAdjustments = window.getAdjustments || (() => ({}));
    const getBwEnabled = window.getBwEnabled || (() => false);
    const getCurvePoints = window.getCurvePoints || (() => ({}));
    const getLevelsValues = window.getLevelsValues || (() => ({}));
    const getCurrentZoom = window.getCurrentZoom || (() => 1);
    const getSelectedFile = window.getSelectedFile || (() => null);
    const getPreviewImage = window.getPreviewImage || (() => ({ src: '' }));
    
    const file = getSelectedFile();
    const img = getPreviewImage();
    
    const session = {
      timestamp: Date.now(),
      fileName: file.name,
      fileSize: file.size,
      fileType: file.type,
      imageData: img.src, // Base64 image data
      adjustments: JSON.parse(JSON.stringify(getAdjustments())),
      effectStates: JSON.parse(JSON.stringify(typeof effectStates !== 'undefined' ? effectStates : {})),
      bwEnabled: getBwEnabled(),
      curvePoints: JSON.parse(JSON.stringify(getCurvePoints())),
      levelsValues: JSON.parse(JSON.stringify(getLevelsValues())),
      zoom: getCurrentZoom(),
    };

    localStorage.setItem(SESSION_KEY, JSON.stringify(session));
    
    // Show clear session button
    const clearSessionBtn = document.getElementById('clearSessionBtn');
    if (clearSessionBtn) {
      clearSessionBtn.style.display = 'block';
    }
    
    // Update status indicator briefly
    const statusText = document.querySelector('.status-text');
    if (statusText) {
      const originalText = statusText.textContent;
      statusText.textContent = '💾 Đã lưu';
      setTimeout(() => {
        statusText.textContent = originalText;
      }, 2000);
    }
  } catch (error) {
    console.error('Failed to save session:', error);
    // If localStorage is full, try to clear old data
    if (error.name === 'QuotaExceededError') {
      console.warn('Storage quota exceeded, clearing old session');
      localStorage.removeItem(SESSION_KEY);
    }
  }
}

/**
 * Load last session from localStorage
 */
function loadSession() {
  try {
    const sessionData = localStorage.getItem(SESSION_KEY);
    if (!sessionData) {
      return null;
    }

    const session = JSON.parse(sessionData);
    
    // Check if session is not too old
    const age = Date.now() - session.timestamp;
    if (age > SESSION_TIMEOUT) {
      console.log('Session expired, clearing...');
      localStorage.removeItem(SESSION_KEY);
      return null;
    }

    return session;
  } catch (error) {
    console.error('Failed to load session:', error);
    return null;
  }
}

/**
 * Clear saved session
 */
function clearSession() {
  localStorage.removeItem(SESSION_KEY);
  console.log('✓ Session cleared');
  
  // Hide clear session button
  const clearSessionBtn = document.getElementById('clearSessionBtn');
  if (clearSessionBtn) {
    clearSessionBtn.style.display = 'none';
  }
}

// Flag to prevent duplicate restore notifications
let isRestoring = false;

/**
 * Restore session data to UI
 */
function restoreSession(session) {
  if (!session) return;
  
  // Prevent duplicate restore
  if (isRestoring) {
    console.log('Already restoring, skipping...');
    return;
  }
  
  isRestoring = true;
  console.log('Restoring session:', session.fileName);

  // Show loading message
  showLoading('Khôi phục phiên làm việc...');

  // Restore image
  previewImage.src = session.imageData;
  previewImage.onload = () => {
    // Show image container
    canvasPlaceholder.style.display = 'none';
    imageContainer.style.display = 'flex';
    
    // Restore adjustments
    if (window.setAdjustments) {
      window.setAdjustments(session.adjustments);
    }
    
    // Restore effect states
    if (session.effectStates && typeof effectStates !== 'undefined') {
      Object.assign(effectStates, session.effectStates);
      if (typeof updateEffectToggleButtons === 'function') {
        updateEffectToggleButtons();
      }
    }
    
    // Restore other values
    if (session.bwEnabled !== undefined && window.setBwEnabled) {
      window.setBwEnabled(session.bwEnabled);
    }
    if (session.curvePoints && window.setCurvePoints) {
      window.setCurvePoints(session.curvePoints);
    }
    if (session.levelsValues && window.setLevelsValues) {
      window.setLevelsValues(session.levelsValues);
    }
    
    // Restore zoom
    if (session.zoom && window.setCurrentZoom) {
      window.setCurrentZoom(session.zoom);
      if (typeof updateZoom === 'function') {
        updateZoom();
      }
    }
    
    // Update all UI controls
    if (typeof updateAllControls === 'function') {
      updateAllControls();
    }
    
    // Apply filters
    setTimeout(() => {
      if (typeof applyFilters === 'function') {
        applyFilters(false); // Don't save to history on restore
      }
      
      // Enable buttons
      if (typeof enableEditingButtons === 'function') {
        enableEditingButtons();
      }
      
      // Wait a bit more before showing success and resetting flag
      setTimeout(() => {
        closeLoading();        
        // Reset flag after notification shown
        setTimeout(() => {
          isRestoring = false;
        }, 500);
      }, 200);
    }, 100);
  };

  // Create a fake file object for compatibility
  const blob = dataURLtoBlob(session.imageData);
  const file = new File([blob], session.fileName, { type: session.fileType });
  if (window.setSelectedFile) {
    window.setSelectedFile(file);
  }
  
  // Display file info
  displayFileInfo(selectedFile);
  
  // Show properties section
  const propertiesSection = document.getElementById('propertiesSection');
  const adjustmentsSection = document.getElementById('adjustmentsSection');
  if (propertiesSection) propertiesSection.style.display = 'block';
  if (adjustmentsSection) adjustmentsSection.style.display = 'block';
  
  const effectsSection = document.getElementById('effectsSection');
  if (effectsSection) effectsSection.style.display = 'block';
  
  const presetsSection = document.getElementById('presetsSection');
  if (presetsSection) presetsSection.style.display = 'block';
  
  // Show tabs
  const panelTabs = document.getElementById('panelTabs');
  if (panelTabs) panelTabs.style.display = 'flex';
}

/**
 * Update all UI controls to match current adjustments
 */
function updateAllControls() {
  // Update all sliders and their value displays
  Object.keys(adjustments).forEach(key => {
    const slider = document.getElementById(key + 'Slider');
    const valueDisplay = document.getElementById(key + 'Value');
    
    if (slider) {
      slider.value = adjustments[key];
    }
    if (valueDisplay) {
      let displayValue = adjustments[key];
      if (key === 'hue') {
        displayValue += '°';
      }
      valueDisplay.textContent = displayValue;
    }
  });
  
  // Update color preview
  if (typeof updateColorPreview === 'function') {
    updateColorPreview();
  }
  
  // Update comparison bars
  if (typeof updateComparisonBars === 'function') {
    updateComparisonBars();
  }
  
  // Update curves
  if (typeof drawCurve === 'function') {
    drawCurve();
  }
  
  // Update levels
  if (typeof drawLevelsHistogram === 'function') {
    drawLevelsHistogram();
  }
}

/**
 * Update effect toggle buttons to match saved states
 */
function updateEffectToggleButtons() {
  if (typeof effectStates === 'undefined') return;
  
  Object.keys(effectStates).forEach(effectName => {
    const btn = document.querySelector(`.effect-toggle-btn[data-effect="${effectName}"]`);
    if (btn) {
      const isEnabled = effectStates[effectName];
      if (isEnabled) {
        btn.classList.add('active');
        btn.innerHTML = `
          <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
          </svg>
        `;
      } else {
        btn.classList.remove('active');
        btn.innerHTML = `
          <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
          </svg>
        `;
      }
    }
  });
}

/**
 * Enable editing buttons
 */
function enableEditingButtons() {
  const buttons = [
    'headerUploadBtn',
    'downloadBtn',
    'exportProjectBtn',
    'removeBackgroundBtn',
    'aiSharpenBtn',
    'undoBtn',
    'redoBtn'
  ];
  
  buttons.forEach(id => {
    const btn = document.getElementById(id);
    if (btn) {
      btn.disabled = false;
    }
  });
}

/**
 * Convert data URL to Blob
 */
function dataURLtoBlob(dataURL) {
  const arr = dataURL.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

/**
 * Show restore session prompt
 */
function showRestorePrompt(session) {
  const age = Date.now() - session.timestamp;
  const ageMinutes = Math.floor(age / 60000);
  const ageHours = Math.floor(ageMinutes / 60);
  
  let timeAgo = '';
  if (ageHours > 0) {
    timeAgo = `${ageHours} giờ trước`;
  } else if (ageMinutes > 0) {
    timeAgo = `${ageMinutes} phút trước`;
  } else {
    timeAgo = 'vừa xong';
  }
  
  const message = `
    <div style="text-align: left; padding: 10px;">
      <div style="font-weight: 600; margin-bottom: 8px;">🔄 Phát hiện phiên làm việc trước đó</div>
      <div style="font-size: 12px; color: #aaa; margin-bottom: 12px;">
        <div>📁 ${session.fileName}</div>
        <div>🕐 ${timeAgo}</div>
      </div>
      <div style="display: flex; gap: 8px; justify-content: flex-end;">
        <button id="restoreYes" style="padding: 6px 12px; background: #007acc; border: none; border-radius: 4px; color: white; cursor: pointer;">
          Khôi phục
        </button>
        <button id="restoreNo" style="padding: 6px 12px; background: #444; border: none; border-radius: 4px; color: white; cursor: pointer;">
          Bỏ qua
        </button>
      </div>
    </div>
  `;
  
  // Create custom notification
  const notification = document.createElement('div');
  notification.className = 'session-restore-notification';
  notification.innerHTML = message;
  notification.style.cssText = `
    position: fixed;
    top: 80px;
    right: 20px;
    background: #2d2d2d;
    border: 1px solid #444;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.3);
    z-index: 10000;
    min-width: 300px;
    animation: slideIn 0.3s ease;
  `;
  
  document.body.appendChild(notification);
  
  // Add animation
  const style = document.createElement('style');
  style.textContent = `
    @keyframes slideIn {
      from { transform: translateX(400px); opacity: 0; }
      to { transform: translateX(0); opacity: 1; }
    }
  `;
  document.head.appendChild(style);
  
  // Handle buttons
  document.getElementById('restoreYes').addEventListener('click', () => {
    notification.remove();
    restoreSession(session);
  });
  
  document.getElementById('restoreNo').addEventListener('click', () => {
    notification.remove();
    clearSession();
  });
  
  // Auto-dismiss after 15 seconds
  setTimeout(() => {
    if (notification.parentNode) {
      notification.remove();
      clearSession();
    }
  }, 15000);
}

/**
 * Setup auto-save
 */
function setupAutoSave() {
  // Save on every filter change (debounced)
  let saveTimeout;
  const debouncedSave = () => {
    // Don't save if currently restoring
    if (isRestoring) {
      return;
    }
    
    clearTimeout(saveTimeout);
    saveTimeout = setTimeout(() => {
      saveSession();
    }, 1000); // Save 1 second after last change
  };
  
  // Hook into applyFilters
  const originalApplyFilters = window.applyFilters;
  if (originalApplyFilters) {
    window.applyFilters = function(...args) {
      const result = originalApplyFilters.apply(this, args);
      
      // Only auto-save if not restoring
      if (!isRestoring) {
        debouncedSave();
      }
      
      return result;
    };
  }
  
  // Save before page unload
  window.addEventListener('beforeunload', () => {
    saveSession();
  });
  
  // Save periodically (every 30 seconds if there are changes)
  setInterval(() => {
    if (selectedFile && previewImage.src) {
      saveSession();
    }
  }, 30000);
}

/**
 * Initialize session manager
 */
function initSessionManager() {
  // Check for existing session
  const session = loadSession();
  
  if (session) {
    // Show restore prompt
    setTimeout(() => {
      showRestorePrompt(session);
    }, 500);
    
    // Show clear session button
    const clearSessionBtn = document.getElementById('clearSessionBtn');
    if (clearSessionBtn) {
      clearSessionBtn.style.display = 'block';
    }
  }
  
  // Setup clear session button
  const clearSessionBtn = document.getElementById('clearSessionBtn');
  if (clearSessionBtn) {
    clearSessionBtn.addEventListener('click', async () => {
      if (await confirmAsync('Bạn có chắc muốn xóa phiên làm việc đã lưu?')) {
        clearSession();
        clearSessionBtn.style.display = 'none';
        showSuccess('Đã xóa phiên làm việc');
      }
    });
  }
  
  // Setup auto-save
  setupAutoSave();
  
  console.log('✓ Session manager initialized');
}

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

// Export functions
window.saveSession = saveSession;
window.loadSession = loadSession;
window.clearSession = clearSession;
window.restoreSession = restoreSession;
window.enableEditingButtons = enableEditingButtons;
window.updateAllControls = updateAllControls;
window.updateEffectToggleButtons = updateEffectToggleButtons;
