/**
 * 앱 설정 스토어 — 테마, 언어 전환
 */
import { create } from 'zustand';
import i18n from '@/lib/i18n/config';

type Theme = 'dark' | 'light';
type Language = 'ko' | 'en';

interface SettingsStore {
  theme: Theme;
  language: Language;
  setTheme: (theme: Theme) => void;
  toggleTheme: () => void;
  setLanguage: (lang: Language) => void;
  toggleLanguage: () => void;
}

function applyTheme(theme: Theme) {
  const root = document.documentElement;
  if (theme === 'light') {
    root.classList.add('light');
    root.classList.remove('dark');
  } else {
    root.classList.add('dark');
    root.classList.remove('light');
  }
}

const savedTheme = (localStorage.getItem('kcg-theme') as Theme) ?? 'dark';
const savedLang = (localStorage.getItem('kcg-lang') as Language) ?? 'ko';

// 초기 적용
applyTheme(savedTheme);
i18n.changeLanguage(savedLang);

export const useSettingsStore = create<SettingsStore>((set, get) => ({
  theme: savedTheme,
  language: savedLang,

  setTheme: (theme) => {
    applyTheme(theme);
    localStorage.setItem('kcg-theme', theme);
    set({ theme });
  },

  toggleTheme: () => {
    const next = get().theme === 'dark' ? 'light' : 'dark';
    get().setTheme(next);
  },

  setLanguage: (lang) => {
    i18n.changeLanguage(lang);
    localStorage.setItem('kcg-lang', lang);
    set({ language: lang });
  },

  toggleLanguage: () => {
    const next = get().language === 'ko' ? 'en' : 'ko';
    get().setLanguage(next);
  },
}));
