import { clearFabPositions } from '../composables/useDraggableFab'

const TOKEN_KEY = 'token'
const REMEMBER_KEY = 'wordloop_remember'
const USERNAME_KEY = 'wordloop_username'

/** 未设置过时默认勾选「记住登录」 */
export function getRememberPreference(): boolean {
  const v = localStorage.getItem(REMEMBER_KEY)
  if (v === null) return true
  return v === '1'
}

export function setRememberPreference(remember: boolean) {
  localStorage.setItem(REMEMBER_KEY, remember ? '1' : '0')
}

export function getSavedUsername(): string {
  return localStorage.getItem(USERNAME_KEY) || ''
}

export function setSavedUsername(username: string) {
  localStorage.setItem(USERNAME_KEY, username)
}

function clearTokenStores() {
  localStorage.removeItem(TOKEN_KEY)
  sessionStorage.removeItem(TOKEN_KEY)
}

export function getToken(): string | null {
  if (getRememberPreference()) {
    return localStorage.getItem(TOKEN_KEY)
  }
  return sessionStorage.getItem(TOKEN_KEY)
}

export function setAuth(token: string, remember: boolean, username?: string) {
  clearFabPositions()
  setRememberPreference(remember)
  clearTokenStores()
  if (remember) {
    localStorage.setItem(TOKEN_KEY, token)
  } else {
    sessionStorage.setItem(TOKEN_KEY, token)
  }
  if (username) {
    setSavedUsername(username)
  }
}

/** 退出登录：清除凭证，保留用户名与「记住」偏好供下次登录 */
export function clearAuth() {
  clearFabPositions()
  clearTokenStores()
}

/** 完全清除本地登录相关数据 */
export function clearAuthAll() {
  clearTokenStores()
  localStorage.removeItem(REMEMBER_KEY)
  localStorage.removeItem(USERNAME_KEY)
}

export function isLoggedIn(): boolean {
  return !!getToken()
}
