const DEFAULT_VOLUME = 0.7;
const DEFAULT_DURATION = 1.0;
const DEFAULT_PITCH_LOCK_ENABLED = false;
const DEFAULT_PITCH_LOCK_FREQUENCY = 440;

const STORAGE_KEYS = {
  VOLUME: 'volume',
  DURATION: 'duration',
  PITCH_LOCK_ENABLED: 'pitchLockEnabled',
  PITCH_LOCK_FREQUENCY: 'pitchLockFrequency',
  EXPANDED_CATEGORIES: 'expandedCategories',
  SELECTED_PROCESSOR_CATEGORY: 'selectedProcessorCategory',
} as const;

export function loadVolume(): number {
  const stored = localStorage.getItem(STORAGE_KEYS.VOLUME);
  return stored ? parseFloat(stored) : DEFAULT_VOLUME;
}

export function saveVolume(volume: number): void {
  localStorage.setItem(STORAGE_KEYS.VOLUME, volume.toString());
}

export function loadDuration(): number {
  const stored = localStorage.getItem(STORAGE_KEYS.DURATION);
  return stored ? parseFloat(stored) : DEFAULT_DURATION;
}

export function saveDuration(duration: number): void {
  localStorage.setItem(STORAGE_KEYS.DURATION, duration.toString());
}

export function loadPitchLockEnabled(): boolean {
  const stored = localStorage.getItem(STORAGE_KEYS.PITCH_LOCK_ENABLED);
  return stored ? stored === 'true' : DEFAULT_PITCH_LOCK_ENABLED;
}

export function savePitchLockEnabled(enabled: boolean): void {
  localStorage.setItem(STORAGE_KEYS.PITCH_LOCK_ENABLED, enabled.toString());
}

export function loadPitchLockFrequency(): number {
  const stored = localStorage.getItem(STORAGE_KEYS.PITCH_LOCK_FREQUENCY);
  return stored ? parseFloat(stored) : DEFAULT_PITCH_LOCK_FREQUENCY;
}

export function savePitchLockFrequency(frequency: number): void {
  localStorage.setItem(STORAGE_KEYS.PITCH_LOCK_FREQUENCY, frequency.toString());
}

export function loadExpandedCategories(): Set<string> {
  const stored = localStorage.getItem(STORAGE_KEYS.EXPANDED_CATEGORIES);
  if (stored) {
    try {
      const parsed = JSON.parse(stored);
      return new Set(Array.isArray(parsed) ? parsed : []);
    } catch {
      return new Set();
    }
  }
  return new Set();
}

export function saveExpandedCategories(categories: Set<string>): void {
  localStorage.setItem(STORAGE_KEYS.EXPANDED_CATEGORIES, JSON.stringify(Array.from(categories)));
}

export function loadSelectedProcessorCategory(): string {
  const stored = localStorage.getItem(STORAGE_KEYS.SELECTED_PROCESSOR_CATEGORY);
  return stored || 'All';
}

export function saveSelectedProcessorCategory(category: string): void {
  localStorage.setItem(STORAGE_KEYS.SELECTED_PROCESSOR_CATEGORY, category);
}
