const AUTH_KEY = '_auth'

export const useAuthToken = () => {
  const token = ref<string | null>(null)
  const isLoaded = ref(false)

  // Token betöltése - LocalStorage (működik web + native)
  const loadToken = async (): Promise<string | null> => {
    if (typeof window === 'undefined') return null

    token.value = localStorage.getItem(AUTH_KEY)
    isLoaded.value = true
    return token.value
  }

  // Token mentése
  const setToken = async (newToken: string): Promise<void> => {
    if (typeof window === 'undefined') return

    token.value = newToken
    localStorage.setItem(AUTH_KEY, newToken)
  }

  // Token törlése (kijelentkezés)
  const clearToken = async (): Promise<void> => {
    if (typeof window === 'undefined') return

    token.value = null
    localStorage.removeItem(AUTH_KEY)
  }

  // Getter a token értékhez
  const getToken = (): string | null => {
    return token.value
  }

  return {
    token: readonly(token),
    isLoaded: readonly(isLoaded),
    loadToken,
    setToken,
    clearToken,
    getToken
  }
}
