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

const THEME_KEY = 'daneshyar-theme';

export function getStoredTheme(): Theme {
  try {
    const value = localStorage.getItem(THEME_KEY);
    return value === 'dark' ? 'dark' : 'light';
  } catch {
    return 'light';
  }
}

export function applyTheme(theme: Theme): void {
  document.documentElement.setAttribute('data-theme', theme);
}

export function setTheme(theme: Theme): void {
  try {
    localStorage.setItem(THEME_KEY, theme);
  } catch {
    /* حالت خصوصی مرورگر */
  }
  applyTheme(theme);
}

/** موقع بوت اپ صدا زده می‌شود تا فلش سفید/سیاه نداشته باشیم. */
export function initTheme(): Theme {
  const theme = getStoredTheme();
  applyTheme(theme);
  return theme;
}
