import { Injectable } from '@angular/core';

/**
 * Safe wrapper around window.localStorage — swallows quota/private-mode
 * errors instead of throwing, so callers don't each need their own try/catch.
 */
@Injectable({ providedIn: 'root' })
export class LocalStorageService {
  getItem(key: string): string | null {
    try {
      return typeof localStorage !== 'undefined' ? localStorage.getItem(key) : null;
    } catch {
      return null;
    }
  }

  setItem(key: string, value: string): void {
    try {
      if (typeof localStorage !== 'undefined') {
        localStorage.setItem(key, value);
      }
    } catch {
      // storage unavailable (private mode / quota) - value simply won't persist
    }
  }

  removeItem(key: string): void {
    try {
      if (typeof localStorage !== 'undefined') {
        localStorage.removeItem(key);
      }
    } catch {
      // ignore
    }
  }

  getJSON<T>(key: string): T | null {
    const raw = this.getItem(key);
    if (!raw) {
      return null;
    }
    try {
      return JSON.parse(raw) as T;
    } catch {
      this.removeItem(key);
      return null;
    }
  }

  setJSON<T>(key: string, value: T): void {
    this.setItem(key, JSON.stringify(value));
  }
}
