// در لود کلاینت، زبان ذخیره‌شده در localStorage را اعمال می‌کند و در صورت تفاوت با زبان فعلی،
// به مسیر همان زبان ریدایرکت می‌شود (تا انتخاب زبان کاربر بین رفرش‌ها/سشن‌ها حفظ شود).
// نکته: داخل plugin نمی‌توان useI18n() را صدا زد؛ از nuxtApp.$i18n استفاده می‌کنیم.
import { LOCALE_STORAGE_KEY } from '~/composables/useLanguage'

// @ts-ignore
export default defineNuxtPlugin((nuxtApp) => {
  // @ts-ignore
  const i18n = nuxtApp.$i18n
  if (!i18n) return

  let stored: string | null = null
  try {
    stored = localStorage.getItem(LOCALE_STORAGE_KEY)
  } catch (e) {
    return
  }
  if (!stored) return

  // @ts-ignore
  const codes = (unref(i18n.locales) as any[]).map((l) => (typeof l === 'string' ? l : l.code))
  // @ts-ignore
  if (codes.includes(stored) && stored !== unref(i18n.locale)) {
    // @ts-ignore - setLocale نیاز به context روتر دارد
    nuxtApp.runWithContext(() => i18n.setLocale(stored))
  }
})
