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 ?? '',
      });
    }
  }
}));

// Status/navigation bar colour per theme so the PWA reads edge-to-edge
// (the system bars blend with the app background instead of showing bands).
const THEME_COLORS = { dark: '#0b1120', light: '#e6f7f4' } as const;

function setThemeColorMeta(effective: 'light' | 'dark') {
  let meta = document.querySelector(
    'meta[name="theme-color"]',
  ) as HTMLMetaElement | null;
  if (!meta) {
    meta = document.createElement('meta');
    meta.name = 'theme-color';
    document.head.appendChild(meta);
  }
  meta.content = THEME_COLORS[effective];
}

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

  const effective =
    theme === 'system'
      ? window.matchMedia('(prefers-color-scheme: dark)').matches
        ? 'dark'
        : 'light'
      : theme;

  root.classList.add(effective);
  setThemeColorMeta(effective);
}

// Keep the theme in sync when the OS theme changes (only when set to "system").
if (typeof window !== 'undefined') {
  window
    .matchMedia('(prefers-color-scheme: dark)')
    .addEventListener('change', () => {
      if (useAppStore.getState().theme === 'system') applyTheme('system');
    });
}
