/**
 * Project Manager
 * Export and import .oedit project files
 */

const PROJECT_VERSION = '1.0';
const PROJECT_EXTENSION = '.oedit';

/**
 * Export current project as .oedit file
 */
function exportProject() {
  // Check if in batch mode
  const isBatchMode = typeof window.batchMode === 'function' ? window.batchMode() : false;
  
  if (isBatchMode) {
    exportBatchProject();
    return;
  }
  
  // Single image export
  const getSelectedFile = window.getSelectedFile || (() => null);
  const getPreviewImage = window.getPreviewImage || (() => ({ src: '' }));
  
  const file = getSelectedFile();
  const img = getPreviewImage();
  
  if (!file || !img.src) {
    showError('Không có ảnh để xuất');
    return;
  }

  try {
    const getAdjustments = window.getAdjustments || (() => ({}));
    const getBwEnabled = window.getBwEnabled || (() => false);
    const getCurvePoints = window.getCurvePoints || (() => ({}));
    const getLevelsValues = window.getLevelsValues || (() => ({}));
    const getCurrentZoom = window.getCurrentZoom || (() => 1);
    
    // Create project data
    const projectData = {
      version: PROJECT_VERSION,
      timestamp: Date.now(),
      mode: 'single',
      fileName: file.name,
      fileSize: file.size,
      fileType: file.type,
      imageData: img.src, // Base64 image
      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(),
      history: typeof historyManager !== 'undefined' && historyManager ? historyManager.exportHistory() : null,
    };

    // Convert to JSON string
    const jsonString = JSON.stringify(projectData);
    
    // Create blob
    const blob = new Blob([jsonString], { type: 'application/json' });
    
    // Generate filename
    const originalName = file.name.replace(/\.[^/.]+$/, ''); // Remove extension
    const projectFileName = `${originalName}${PROJECT_EXTENSION}`;
    
    // Create download link
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = projectFileName;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    showSuccess(`Đã xuất project: ${projectFileName}`);
    console.log('✓ Project exported:', projectFileName);
  } catch (error) {
    console.error('Failed to export project:', error);
    showError('Lỗi khi xuất project');
  }
}

/**
 * Export batch project with all images
 */
function exportBatchProject() {
  // Get batch images from window
  const batchImages = window.batchImages || [];
  
  if (batchImages.length === 0) {
    showError('Không có ảnh trong batch để xuất');
    return;
  }
  
  try {
    // Create batch project data
    const projectData = {
      version: PROJECT_VERSION,
      timestamp: Date.now(),
      mode: 'batch',
      imageCount: batchImages.length,
      images: batchImages.map(img => ({
        fileName: img.file.name,
        fileSize: img.file.size,
        fileType: img.file.type,
        imageData: img.dataUrl,
        width: img.width,
        height: img.height,
        adjustments: img.adjustments || null,
        processed: img.processed || false
      })),
      effectStates: JSON.parse(JSON.stringify(typeof effectStates !== 'undefined' ? effectStates : {})),
    };
    
    // Convert to JSON string
    const jsonString = JSON.stringify(projectData);
    
    // Create blob
    const blob = new Blob([jsonString], { type: 'application/json' });
    
    // Generate filename with timestamp
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
    const projectFileName = `batch-project-${timestamp}${PROJECT_EXTENSION}`;
    
    // Create download link
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = projectFileName;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    showSuccess(`Đã xuất batch project với ${batchImages.length} ảnh`);
    console.log('✓ Batch project exported:', projectFileName, batchImages.length, 'images');
  } catch (error) {
    console.error('Failed to export batch project:', error);
    showError('Lỗi khi xuất batch project');
  }
}

/**
 * Import .oedit project file
 */
function importProject(file) {
  if (!file) return;
  
  // Check file extension
  if (!file.name.endsWith(PROJECT_EXTENSION)) {
    showError(`File phải có đuôi ${PROJECT_EXTENSION}`);
    return;
  }
  
  showLoading('Đang mở project...');
  
  const reader = new FileReader();
  
  reader.onload = (e) => {
    try {
      const projectData = JSON.parse(e.target.result);
      
      // Validate project data
      if (!projectData.version) {
        throw new Error('Invalid project file');
      }
      
      // Check version compatibility
      if (projectData.version !== PROJECT_VERSION) {
        console.warn('Project version mismatch:', projectData.version, 'vs', PROJECT_VERSION);
        // Continue anyway, but warn user
      }
      
      // Check if batch or single mode
      if (projectData.mode === 'batch' && projectData.images) {
        // Restore batch project
        restoreBatchProject(projectData);
      } else if (projectData.imageData) {
        // Restore single project
        restoreProject(projectData);
      } else {
        throw new Error('Invalid project format');
      }
      
    } catch (error) {
      console.error('Failed to import project:', error);
      closeLoading();
      showError('Lỗi khi mở project. File có thể bị hỏng.');
    }
  };
  
  reader.onerror = () => {
    closeLoading();
    showError('Lỗi khi đọc file');
  };
  
  reader.readAsText(file);
}

/**
 * Restore batch project data
 */
function restoreBatchProject(projectData) {
  console.log('Restoring batch project:', projectData.imageCount, 'images');
  
  closeLoading();
  
  // Convert project images to batch format
  const batchImagesData = projectData.images.map(img => ({
    file: new File([dataURLtoBlob(img.imageData)], img.fileName, { type: img.fileType }),
    dataUrl: img.imageData,
    width: img.width,
    height: img.height,
    adjustments: img.adjustments,
    processed: img.processed
  }));
  
  // Call batch handler if available
  if (typeof window.handleBatchFiles === 'function') {
    // Set batch images directly
    if (typeof window.setBatchImages === 'function') {
      window.setBatchImages(batchImagesData);
    }
    
    showSuccess(`Đã mở batch project với ${projectData.imageCount} ảnh`);
  } else {
    showError('Batch mode không khả dụng');
  }
}

/**
 * Restore project data
 */
function restoreProject(projectData) {
  console.log('Restoring project:', projectData.fileName);
  
  // Restore image
  previewImage.src = projectData.imageData;
  
  previewImage.onload = () => {
    // Show image container
    canvasPlaceholder.style.display = 'none';
    imageContainer.style.display = 'flex';
    
    // Restore adjustments
    if (projectData.adjustments && window.setAdjustments) {
      window.setAdjustments(projectData.adjustments);
    }
    
    // Restore effect states
    if (projectData.effectStates && typeof effectStates !== 'undefined') {
      Object.assign(effectStates, projectData.effectStates);
      if (typeof updateEffectToggleButtons === 'function') {
        updateEffectToggleButtons();
      }
    }
    
    // Restore other values
    if (projectData.bwEnabled !== undefined && window.setBwEnabled) {
      window.setBwEnabled(projectData.bwEnabled);
    }
    if (projectData.curvePoints && window.setCurvePoints) {
      window.setCurvePoints(projectData.curvePoints);
    }
    if (projectData.levelsValues && window.setLevelsValues) {
      window.setLevelsValues(projectData.levelsValues);
    }
    
    // Restore zoom
    if (projectData.zoom && window.setCurrentZoom) {
      window.setCurrentZoom(projectData.zoom);
      if (typeof updateZoom === 'function') {
        updateZoom();
      }
    }
    
    // Restore history
    if (projectData.history && typeof historyManager !== 'undefined' && historyManager) {
      historyManager.importHistory(projectData.history);
    }
    
    // Update all UI controls
    if (typeof updateAllControls === 'function') {
      updateAllControls();
    }
    
    // Apply filters
    setTimeout(() => {
      applyFilters(false); // Don't save to history on restore
      closeLoading();
      showSuccess(`Đã mở project: ${projectData.fileName}`);
      
      // Enable buttons
      if (typeof enableEditingButtons === 'function') {
        enableEditingButtons();
      } else {
        // Fallback: enable buttons manually
        const buttons = ['headerUploadBtn', 'downloadBtn', 'removeBackgroundBtn', 'aiSharpenBtn', 'undoBtn', 'redoBtn'];
        buttons.forEach(id => {
          const btn = document.getElementById(id);
          if (btn) btn.disabled = false;
        });
      }
      
      // Show header clear button
      const headerClearBtn = document.getElementById('headerClearBtn');
      if (headerClearBtn) {
        headerClearBtn.style.display = 'block';
      }
    }, 100);
  };
  
  previewImage.onerror = () => {
    closeLoading();
    showError('Lỗi khi tải ảnh từ project');
  };
  
  // Create a fake file object for compatibility
  const blob = dataURLtoBlob(projectData.imageData);
  const file = new File([blob], projectData.fileName, { type: projectData.fileType });
  if (window.setSelectedFile) {
    window.setSelectedFile(file);
  }
  
  // Display file info
  if (typeof displayFileInfo === 'function') {
    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';
}

/**
 * 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 });
}

/**
 * Setup project file input
 */
function setupProjectManager() {
  // Create hidden file input for project files
  const projectInput = document.createElement('input');
  projectInput.type = 'file';
  projectInput.id = 'projectInput';
  projectInput.accept = PROJECT_EXTENSION;
  projectInput.style.display = 'none';
  document.body.appendChild(projectInput);
  
  // Handle project file selection
  projectInput.addEventListener('change', (e) => {
    const file = e.target.files[0];
    if (file) {
      importProject(file);
    }
    // Reset input
    projectInput.value = '';
  });
  
  // Setup export button
  const exportProjectBtn = document.getElementById('exportProjectBtn');
  if (exportProjectBtn) {
    exportProjectBtn.addEventListener('click', exportProject);
  }
  
  // Setup import button
  const importProjectBtn = document.getElementById('importProjectBtn');
  if (importProjectBtn) {
    importProjectBtn.addEventListener('click', () => {
      projectInput.click();
    });
  }
  
  // Handle drag and drop for .oedit files
  const canvasContent = document.getElementById('canvasContent');
  if (canvasContent) {
    canvasContent.addEventListener('drop', (e) => {
      e.preventDefault();
      const file = e.dataTransfer.files[0];
      if (file && file.name.endsWith(PROJECT_EXTENSION)) {
        importProject(file);
      }
    });
  }
  
  console.log('✓ Project manager initialized');
}

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

// Export functions
window.exportProject = exportProject;
window.importProject = importProject;
window.restoreProject = restoreProject;
