// Theme utility functions with enhanced authentication flow support
export function getCurrentTheme(): 'light' | 'dark' {
  if (typeof window === 'undefined') return 'dark';
  
  // Check if theme was already set during initialization
  const initialTheme = (window as any).__INITIAL_THEME__;
  if (initialTheme) return initialTheme;
  
  const savedTheme = localStorage.getItem('theme') as 'light' | 'dark';
  if (savedTheme) return savedTheme;
  
  // Default to system preference
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}

export function setTheme(theme: 'light' | 'dark') {
  if (typeof window === 'undefined') return;
  
  // Store for immediate access
  (window as any).__INITIAL_THEME__ = theme;
  
  // Dispatch event - let the layout handle the actual DOM updates
  window.dispatchEvent(new CustomEvent('themeChanged', { 
    detail: { theme } 
  }));
}

export function initializeTheme() {
  if (typeof window === 'undefined') return;
  
  const savedTheme = getCurrentTheme();
  setTheme(savedTheme);
}

export function toggleTheme() {
  const currentTheme = getCurrentTheme();
  const newTheme = currentTheme === 'light' ? 'dark' : 'light';
  setTheme(newTheme);
  return newTheme;
}

// Enhanced function to ensure theme consistency during auth flows
export function ensureThemeConsistency() {
  if (typeof window === 'undefined') return;
  
  const currentTheme = getCurrentTheme();
  const documentTheme = document.documentElement.getAttribute('data-theme');
  
  // If themes are out of sync, force synchronization
  if (currentTheme !== documentTheme) {
    document.documentElement.setAttribute('data-theme', currentTheme);
    document.documentElement.classList.remove('light', 'dark');
    document.documentElement.classList.add(currentTheme);
    
    document.body.classList.remove('light', 'dark');
    document.body.classList.add(currentTheme);
    
    localStorage.setItem('theme', currentTheme);
  }
}