import { Difficulty } from './types';

export interface AudioPreferences {
  musicEnabled: boolean;
  effectsEnabled: boolean;
}

export interface GameSceneData {
  difficulty: Difficulty;
  audioPreferences: AudioPreferences;
}

export interface SettingsSceneData {
  returnSceneKey?: string;
}

export const AUDIO_PREFERENCES_STORAGE_KEY = 'scopone.audio-preferences';

export const DEFAULT_AUDIO_PREFERENCES: AudioPreferences = {
  musicEnabled: true,
  effectsEnabled: true,
};

const cloneDefaultAudioPreferences = (): AudioPreferences => ({
  ...DEFAULT_AUDIO_PREFERENCES,
});

const getBrowserStorage = (): Storage | null => {
  if (typeof window === 'undefined') {
    return null;
  }

  try {
    return window.localStorage;
  } catch {
    return null;
  }
};

export const normalizeAudioPreferences = (value: unknown): AudioPreferences => {
  if (!value || typeof value !== 'object') {
    return cloneDefaultAudioPreferences();
  }

  const candidate = value as Partial<AudioPreferences>;

  return {
    musicEnabled:
      typeof candidate.musicEnabled === 'boolean'
        ? candidate.musicEnabled
        : DEFAULT_AUDIO_PREFERENCES.musicEnabled,
    effectsEnabled:
      typeof candidate.effectsEnabled === 'boolean'
        ? candidate.effectsEnabled
        : DEFAULT_AUDIO_PREFERENCES.effectsEnabled,
  };
};

export const loadAudioPreferences = (storage: Storage | null = getBrowserStorage()): AudioPreferences => {
  if (!storage) {
    return cloneDefaultAudioPreferences();
  }

  try {
    const rawPreferences = storage.getItem(AUDIO_PREFERENCES_STORAGE_KEY);

    if (!rawPreferences) {
      return cloneDefaultAudioPreferences();
    }

    return normalizeAudioPreferences(JSON.parse(rawPreferences));
  } catch {
    return cloneDefaultAudioPreferences();
  }
};

export const saveAudioPreferences = (
  preferences: AudioPreferences,
  storage: Storage | null = getBrowserStorage(),
): AudioPreferences => {
  const normalizedPreferences = normalizeAudioPreferences(preferences);

  if (!storage) {
    return normalizedPreferences;
  }

  try {
    storage.setItem(AUDIO_PREFERENCES_STORAGE_KEY, JSON.stringify(normalizedPreferences));
  } catch {
    return normalizedPreferences;
  }

  return normalizedPreferences;
};