import type { Task } from '../types/task';
import { normalizeTasks } from './taskNormalizer';

const STORAGE_KEY = 'Hua.Todo_tasks';
const SYNC_STATUS_KEY = 'Hua.Todo_sync_status';

export interface SyncStatus {
  lastSyncTime: number;
  isOnline: boolean;
  pendingChanges: number;
}

export class LocalStorageService {
  static saveTasks(tasks: Task[]): void {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(normalizeTasks(tasks)));
    } catch (error) {
      console.error('Failed to save tasks to localStorage:', error);
    }
  }

  static loadTasks(): Task[] {
    try {
      const data = localStorage.getItem(STORAGE_KEY);
      return data ? normalizeTasks(JSON.parse(data)) : [];
    } catch (error) {
      console.error('Failed to load tasks from localStorage:', error);
      return [];
    }
  }

  static clearTasks(): void {
    try {
      localStorage.removeItem(STORAGE_KEY);
    } catch (error) {
      console.error('Failed to clear tasks from localStorage:', error);
    }
  }

  static saveSyncStatus(status: SyncStatus): void {
    try {
      localStorage.setItem(SYNC_STATUS_KEY, JSON.stringify(status));
    } catch (error) {
      console.error('Failed to save sync status:', error);
    }
  }

  static loadSyncStatus(): SyncStatus {
    try {
      const data = localStorage.getItem(SYNC_STATUS_KEY);
      return data ? JSON.parse(data) : {
        lastSyncTime: 0,
        isOnline: true,
        pendingChanges: 0
      };
    } catch (error) {
      console.error('Failed to load sync status:', error);
      return {
        lastSyncTime: 0,
        isOnline: true,
        pendingChanges: 0
      };
    }
  }

  static isOnline(): boolean {
    return navigator.onLine;
  }
}

export default LocalStorageService;
