import { create } from 'zustand';
import { db } from '../database/db';

interface AppState {
  theme: 'light' | 'dark' | 'system';
  language: string;
  loadSettings: () => Promise<void>;
  setTheme: (theme: 'light' | 'dark' | 'system') => Promise<void>;
}

export const useAppStore = create<AppState>((set) => ({
  theme: 'system',
  language: 'fr',

  loadSettings: async () => {
    const settings = await db.settings.get(1);
    if (settings) {
      set({ theme: settings.theme, language: settings.language });
      applyTheme(settings.theme);
    }
  },

  setTheme: async (theme) => {
    set({ theme });
    applyTheme(theme);
    const settings = await db.settings.get(1);
    if (settings) {
      await db.settings.put({ ...settings, theme });
    } else {
      // Fallback (should not happen: populate always seeds settings + a profile)
      const firstProfile = await db.profiles.orderBy('createdAt').first();
      await db.settings.add({
        id: 1,
        theme,
        language: 'fr',
        activeProfileId: firstProfile?.id ?? '',
      });
    }
  }
}));

function applyTheme(theme: 'light' | 'dark' | 'system') {
  const root = window.document.documentElement;
  root.classList.remove('light', 'dark');

  if (theme === 'system') {
    const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    root.classList.add(systemTheme);
    return;
  }

  root.classList.add(theme);
}
