export const SHARED_LANGUAGE_COOKIE = 'rentaldrivego-language'
export const SHARED_LANGUAGE_KEY = 'rentaldrivego-language'
export const SHARED_THEME_KEY = 'rentaldrivego-theme'

function readEmployeeToken() {
  return null
}

function decodeEmployeeId(token: string | null) {
  if (!token) return null

  try {
    const encoded = token.split('.')[1] ?? ''
    const normalized = encoded.replace(/-/g, '+').replace(/_/g, '/')
    const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=')
    const payload = JSON.parse(atob(padded)) as { sub?: string }
    return typeof payload.sub === 'string' && payload.sub ? payload.sub : null
  } catch {
    return null
  }
}

export function getScopedPreferenceKey(baseKey: string) {
  const employeeId = decodeEmployeeId(readEmployeeToken())
  return employeeId ? `${baseKey}:${employeeId}` : baseKey
}

export function getScopedPreferenceCookieName(baseKey: string) {
  const employeeId = decodeEmployeeId(readEmployeeToken())
  return employeeId ? `${baseKey}--${employeeId}` : baseKey
}

function readCookie(name: string) {
  if (typeof document === 'undefined') return null

  return document.cookie
    .split(';')
    .map((chunk) => chunk.trim())
    .find((chunk) => chunk.startsWith(`${name}=`))
    ?.slice(name.length + 1) ?? null
}

function writeCookie(name: string, value: string) {
  if (typeof document === 'undefined') return
  document.cookie = `${name}=${value}; path=/; max-age=31536000; samesite=lax`
}

export function readCurrentUserScopedPreference(baseKey: string) {
  if (typeof window === 'undefined') return null

  const scopedCookie = readCookie(getScopedPreferenceCookieName(baseKey))
  if (scopedCookie) return scopedCookie

  return window.localStorage.getItem(getScopedPreferenceKey(baseKey))
}

export function readScopedPreference(baseKey: string, legacyKeys: string[] = []) {
  if (typeof window === 'undefined') return null

  const scopedCookie = readCookie(getScopedPreferenceCookieName(baseKey))
  if (scopedCookie) return scopedCookie

  const sharedCookie = readCookie(baseKey)
  if (sharedCookie) return sharedCookie

  const scopedKey = getScopedPreferenceKey(baseKey)
  const candidates = [scopedKey, baseKey, ...legacyKeys]

  for (const key of candidates) {
    const value = window.localStorage.getItem(key)
    if (value) return value
  }

  return null
}

export function writeScopedPreference(baseKey: string, value: string, legacyKeys: string[] = []) {
  if (typeof window === 'undefined') return

  const scopedKey = getScopedPreferenceKey(baseKey)
  const scopedCookie = getScopedPreferenceCookieName(baseKey)

  writeCookie(baseKey, value)
  if (scopedCookie !== baseKey) {
    writeCookie(scopedCookie, value)
  }

  window.localStorage.setItem(scopedKey, value)
  window.localStorage.setItem(baseKey, value)

  for (const key of legacyKeys) {
    window.localStorage.setItem(key, value)
  }
}
