const TOKEN_KEY = 'AccessToken'
const TOKEN_EVENT = 'auth-token-changed'

function notifyTokenChange() {
  if (!import.meta.client) return
  try {
    window.dispatchEvent(new Event(TOKEN_EVENT))
  } catch {
    // ignore
  }
}

export function setToken(token?: string, remember?: boolean) {
  if (!token || !import.meta.client) return
  try {
    const storage = remember ? localStorage : sessionStorage
    storage.setItem(TOKEN_KEY, token)
    notifyTokenChange()
  } catch {
    // ignore storage errors
  }
}

export function getToken() {
  if (!import.meta.client) return ''
  try {
    return localStorage.getItem(TOKEN_KEY) || sessionStorage.getItem(TOKEN_KEY) || ''
  } catch {
    return ''
  }
}

export function removeToken() {
  if (!import.meta.client) return
  try {
    localStorage.removeItem(TOKEN_KEY)
    sessionStorage.removeItem(TOKEN_KEY)
    notifyTokenChange()
  } catch {
    // ignore storage errors
  }
}
