export type DashboardLocale = 'en' | 'fa'

export const DASHBOARD_LOCALE_STORAGE_KEY = 'meshkee.dashboard.locale'

export function isDashboardLocale(value: unknown): value is DashboardLocale {
  return value === 'en' || value === 'fa'
}

export function getLocaleDirection(locale: DashboardLocale): 'ltr' | 'rtl' {
  return locale === 'fa' ? 'rtl' : 'ltr'
}

export function applyDocumentLocale(locale: DashboardLocale): void {
  if (typeof document === 'undefined') return
  const root = document.documentElement
  root.lang = locale
  root.dir = getLocaleDirection(locale)
}

export function readStoredLocale(fallback: DashboardLocale = 'fa'): DashboardLocale {
  if (typeof localStorage === 'undefined') return fallback
  try {
    const raw = localStorage.getItem(DASHBOARD_LOCALE_STORAGE_KEY)
    return isDashboardLocale(raw) ? raw : fallback
  } catch {
    return fallback
  }
}

export function writeStoredLocale(locale: DashboardLocale): void {
  if (typeof localStorage === 'undefined') return
  try {
    localStorage.setItem(DASHBOARD_LOCALE_STORAGE_KEY, locale)
  } catch {
    // ignore quota / private mode
  }
}
