import type { CookieRef } from 'nuxt/app'
import config from 'virtual:content/content.config'

export function useContentPreference() {
  const locales = config.locale?.list.map((l) => l.code) ?? []
  const variants = config.variant?.list.map((v) => v.code) ?? []

  const localeCookie = useCookie<string>('locale', {
    sameSite: 'lax',
    maxAge: config.locale?.cookieMaxAge ?? 0,
  })

  const variantCookie = useCookie<string>('variant', {
    sameSite: 'lax',
    maxAge: config.variant?.cookieMaxAge ?? 0,
  })

  function prefer(list: string[], cookie: CookieRef<string>) {
    return (item: string) => {
      if (list.includes(item)) {
        cookie.value = item
      }
    }
  }

  function preferred(
    list: string[],
    cookie: CookieRef<string | undefined>,
    fallback: string | undefined
  ) {
    return computed(() => {
      if (cookie.value !== undefined && list.includes(cookie.value)) {
        return cookie.value
      } else if (cookie.value !== undefined) {
        cookie.value = undefined
      }

      return fallback
    })
  }

  return {
    preferredLocale: preferred(locales, localeCookie, config.locale?.default),
    preferLocale: prefer(locales, localeCookie),
    preferredVariant: preferred(variants, variantCookie, config.variant?.default),
    preferVariant: prefer(variants, variantCookie),
  }
}
