export type ThemePreference = 'system' | 'light' | 'dark';
export type EffectiveTheme = 'light' | 'dark';

export const THEME_STORAGE_KEY = 'actionpanel_ai_theme_preference';

export const isThemePreference = (value: unknown): value is ThemePreference => (
  value === 'system' || value === 'light' || value === 'dark'
);

export const resolveEffectiveTheme = (theme: ThemePreference): EffectiveTheme => (
  theme === 'light' ? 'light' : 'dark'
);

export const readStoredThemePreference = (): ThemePreference => {
  if (typeof window === 'undefined') {
    return 'dark';
  }

  try {
    const value = window.localStorage.getItem(THEME_STORAGE_KEY);
    return isThemePreference(value) ? value : 'dark';
  } catch {
    return 'dark';
  }
};

export const writeStoredThemePreference = (theme: ThemePreference) => {
  if (typeof window === 'undefined') {
    return;
  }

  try {
    window.localStorage.setItem(THEME_STORAGE_KEY, theme);
  } catch {
    // Storage can be unavailable in private contexts; in-memory React state still applies the theme.
  }
};

export const applyThemeToElement = (element: Element, effectiveTheme: EffectiveTheme) => {
  element.classList.toggle('dark', effectiveTheme === 'dark');
};

export const applyThemeToDocument = (effectiveTheme: EffectiveTheme) => {
  if (typeof document === 'undefined') {
    return;
  }

  applyThemeToElement(document.documentElement, effectiveTheme);
};

export const applyStoredThemeToDocument = () => {
  applyThemeToDocument(resolveEffectiveTheme(readStoredThemePreference()));
};
