import { ref, watch } from 'vue'
import { useCookie } from '#imports'

const parseValue = <T>(value: unknown, fallback: T): T => {
  if (value === null || value === undefined) {
    return fallback
  }
  if (typeof value === 'string') {
    try {
      return JSON.parse(value) as T
    } catch {
      return value as unknown as T
    }
  }
  return value as T
}

export const usePersistedValue = <T>(key: string, fallback: T) => {
  const cookie = useCookie<string | null>(`pref:${key}`, {
    sameSite: 'lax',
  })
  const initial = parseValue(cookie.value, fallback)
  const state = ref<T>(initial)

  watch(
    state,
    (value) => {
      cookie.value = JSON.stringify(value)
    },
    { deep: true },
  )

  return state
}
