export type Theme = 'light' | 'dark';

export function getThemePreference(): Theme {
  if (typeof localStorage !== 'undefined' && localStorage.getItem('theme')) {
    return localStorage.getItem('theme') as Theme;
  }
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}

export function isDark() {
  return getThemePreference() === 'dark';
}

export function setTheme(theme: Theme) {
  localStorage.setItem('theme', theme);
  reflectPreference(theme);
}

export function reflectPreference(theme: Theme) {
  document.documentElement.setAttribute('data-theme', theme);
  
  const themeColorMeta = document.querySelector('meta[name="theme-color"]');
  if (themeColorMeta) {
    themeColorMeta.setAttribute('content', theme === 'dark' ? '#0f172a' : '#ffffff');
  }
}

// Initialize theme on page load
export function initTheme() {
  const theme = getThemePreference();
  reflectPreference(theme);
  
  // Listen for system theme changes
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
    if (!localStorage.getItem('theme')) {
      reflectPreference(e.matches ? 'dark' : 'light');
    }
  });
}

// Toggle theme function
export function toggleTheme() {
  const currentTheme = getThemePreference();
  const newTheme = currentTheme === 'light' ? 'dark' : 'light';
  setTheme(newTheme);
  return newTheme;
} 