// Thin wrapper around browser localStorage for the JWT.
//
// The Angular application injected localStorage through the
// BROWSER_STORAGE InjectionToken. React has no dependency injection
// container, so the equivalent seam is a small module that the rest
// of the code imports. Keeping every read/write of the token behind
// these three functions preserves the single-point-of-change benefit
// the InjectionToken provided (e.g. swapping to sessionStorage later).
const TOKEN_KEY = 'travlr-token';

export function getToken(): string {
  return localStorage.getItem(TOKEN_KEY) ?? '';
}

export function saveToken(token: string): void {
  localStorage.setItem(TOKEN_KEY, token);
}

export function clearToken(): void {
  localStorage.removeItem(TOKEN_KEY);
}

// Decode the JWT payload without verifying the signature (verification
// happens server side). Returns null for malformed tokens instead of
// throwing, which the original Angular service did not guard against.
export function decodeTokenPayload(
  token: string
): { _id?: string; email?: string; name?: string; exp?: number } | null {
  try {
    return JSON.parse(atob(token.split('.')[1]));
  } catch {
    return null;
  }
}

export function isTokenValid(token: string): boolean {
  const payload = decodeTokenPayload(token);
  if (!payload || typeof payload.exp !== 'number') {
    return false;
  }
  return payload.exp > Date.now() / 1000;
}
