import { AnonymousCounter } from '../types';

const ANONYMOUS_COUNTERS_KEY = 'anonymous_counters';

export const localStorageService = {
  // Anonymous counters
  getAnonymousCounters: (): AnonymousCounter[] => {
    try {
      const data = localStorage.getItem(ANONYMOUS_COUNTERS_KEY);
      return data ? JSON.parse(data) : [];
    } catch (error) {
      console.error('Error loading anonymous counters:', error);
      return [];
    }
  },

  saveAnonymousCounters: (counters: AnonymousCounter[]): void => {
    try {
      localStorage.setItem(ANONYMOUS_COUNTERS_KEY, JSON.stringify(counters));
    } catch (error) {
      console.error('Error saving anonymous counters:', error);
    }
  },

  addAnonymousCounter: (counter: AnonymousCounter): void => {
    const counters = localStorageService.getAnonymousCounters();
    counters.push(counter);
    localStorageService.saveAnonymousCounters(counters);
  },

  updateAnonymousCounter: (id: string, updates: Partial<AnonymousCounter>): void => {
    const counters = localStorageService.getAnonymousCounters();
    const index = counters.findIndex(c => c.id === id);
    if (index !== -1) {
      counters[index] = { ...counters[index], ...updates };
      localStorageService.saveAnonymousCounters(counters);
    }
  },

  deleteAnonymousCounter: (id: string): void => {
    const counters = localStorageService.getAnonymousCounters();
    const filtered = counters.filter(c => c.id !== id);
    localStorageService.saveAnonymousCounters(filtered);
  },

  // Auth
  setAuthToken: (token: string): void => {
    localStorage.setItem('token', token);
  },

  getAuthToken: (): string | null => {
    return localStorage.getItem('token');
  },

  removeAuthToken: (): void => {
    localStorage.removeItem('token');
  },

  setUser: (user: any): void => {
    localStorage.setItem('user', JSON.stringify(user));
  },

  getUser: (): any => {
    try {
      const data = localStorage.getItem('user');
      return data ? JSON.parse(data) : null;
    } catch (error) {
      console.error('Error loading user:', error);
      return null;
    }
  },

  removeUser: (): void => {
    localStorage.removeItem('user');
  },

  clearAuth: (): void => {
    localStorageService.removeAuthToken();
    localStorageService.removeUser();
  },

  // Utility
  generateId: (): string => {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
  },

  getTodayString: (): string => {
    return new Date().toISOString().split('T')[0];
  },
};
