import { ref } from 'vue';

const THEME_KEY = 'theme';
const THEMES = {
  LIGHT: 'light',
  DARK: 'dark'
} as const;

const isDark = ref(false);
let initialized = false;

const setTheme = (theme: typeof THEMES[keyof typeof THEMES]) => {
  if (process.client) {
    document.documentElement.setAttribute('data-theme', theme);
    localStorage.setItem(THEME_KEY, theme);
    isDark.value = theme === THEMES.DARK;
  }
};

const initializeTheme = () => {
  if (process.client && !initialized) {
    const savedTheme = localStorage.getItem(THEME_KEY) as typeof THEMES[keyof typeof THEMES] | null;
    const prefersDark = window.matchMedia?.('(prefers-color-scheme: dark)').matches;
    const theme = savedTheme || (prefersDark ? THEMES.DARK : THEMES.LIGHT);
    setTheme(theme);
    window.matchMedia?.('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
      if (!localStorage.getItem(THEME_KEY)) {
        setTheme(e.matches ? THEMES.DARK : THEMES.LIGHT);
      }
    });
    initialized = true;
  }
};

const toggleTheme = () => {
  setTheme(isDark.value ? THEMES.LIGHT : THEMES.DARK);
};

export const useTheme = () => {
  if (process.client) {
    initializeTheme();
  }

  return {
    isDark,
    toggleTheme
  };
};