export const THEME_MODE_KEY = 'theme';

export const themeModes = [
  { key: 'light', label: 'روشن' },
  { key: 'dark', label: 'تاریک' },
  { key: 'auto', label: 'خودکار' },
];

export function getThemeMode() {
  const value = localStorage.getItem(THEME_MODE_KEY);
  return themeModes.some((item) => item.key === value) ? value : 'light';
}

export function resolvedThemeMode(mode = getThemeMode()) {
  if (mode !== 'auto') return mode;
  return window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}

export function applyThemeMode(mode) {
  const nextMode = themeModes.some((item) => item.key === mode) ? mode : 'light';
  document.documentElement.dataset.themeMode = nextMode;
  document.documentElement.dataset.theme = resolvedThemeMode(nextMode);
  localStorage.setItem(THEME_MODE_KEY, nextMode);
  window.dispatchEvent(new CustomEvent('theme-mode-change', { detail: { mode: nextMode } }));
  return nextMode;
}

export function watchAutoThemeMode() {
  const query = window.matchMedia?.('(prefers-color-scheme: dark)');
  if (!query) return () => {};

  const sync = () => {
    if (getThemeMode() === 'auto') {
      document.documentElement.dataset.theme = resolvedThemeMode('auto');
    }
  };

  query.addEventListener?.('change', sync);
  return () => query.removeEventListener?.('change', sync);
}
