import { create } from 'zustand';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Appearance } from 'react-native';

export type ThemeMode = 'system' | 'light' | 'dark';

const STORAGE_KEY = '@rebreak/theme';

function resolveColorScheme(mode: ThemeMode): 'light' | 'dark' {
  if (mode === 'system') {
    return Appearance.getColorScheme() === 'dark' ? 'dark' : 'light';
  }
  return mode;
}

type ThemeState = {
  mode: ThemeMode;
  colorScheme: 'light' | 'dark';
  setMode: (mode: ThemeMode) => Promise<void>;
  init: () => Promise<void>;
};

export const useThemeStore = create<ThemeState>((set, get) => {
  // Listen for OS-level theme changes and update store when mode === 'system'.
  Appearance.addChangeListener(() => {
    if (get().mode === 'system') {
      set({ colorScheme: resolveColorScheme('system') });
    }
  });

  return {
    mode: 'system',
    colorScheme: 'light',

    init: async () => {
      const stored = await AsyncStorage.getItem(STORAGE_KEY);
      const mode: ThemeMode =
        stored === 'light' || stored === 'dark' || stored === 'system' ? stored : 'system';
      set({ mode, colorScheme: resolveColorScheme(mode) });
    },

    setMode: async (mode) => {
      await AsyncStorage.setItem(STORAGE_KEY, mode);
      set({ mode, colorScheme: resolveColorScheme(mode) });
    },
  };
});
