import { writable } from 'svelte/store';

export type ThemeName = 'ianos' | 'verified';

export type Preferences = {
  hasSeenBoot: boolean;
  simpleModePreferred: boolean;
  reducedMotion: boolean;
  theme: ThemeName;
};

const defaultPreferences: Preferences = {
  hasSeenBoot: false,
  simpleModePreferred: false,
  reducedMotion: false,
  theme: 'ianos'
};

function readPreferences(): Preferences {
  if (typeof localStorage === 'undefined') return defaultPreferences;

  try {
    const saved = localStorage.getItem('ianos.preferences');
    if (!saved) {
      return {
        ...defaultPreferences,
        reducedMotion: window.matchMedia('(prefers-reduced-motion: reduce)').matches
      };
    }

    return {
      ...defaultPreferences,
      ...JSON.parse(saved),
      reducedMotion: window.matchMedia('(prefers-reduced-motion: reduce)').matches
    };
  } catch {
    return defaultPreferences;
  }
}

function createPreferencesStore() {
  const { subscribe, set, update } = writable<Preferences>(defaultPreferences);

  return {
    subscribe,
    initialise() {
      set(readPreferences());
    },
    updatePreference(partial: Partial<Preferences>) {
      update((current) => {
        const next = { ...current, ...partial };
        if (typeof localStorage !== 'undefined') {
          localStorage.setItem('ianos.preferences', JSON.stringify(next));
          localStorage.setItem('hasSeenBoot', String(next.hasSeenBoot));
        }
        return next;
      });
    },
    markBootSeen() {
      this.updatePreference({ hasSeenBoot: true });
    },
    resetBoot() {
      this.updatePreference({ hasSeenBoot: false });
    },
    setTheme(theme: ThemeName) {
      this.updatePreference({ theme });
    }
  };
}

export const preferences = createPreferencesStore();
