/**
 * Client-side helpers for the backend JWT stored in localStorage (`accessToken`).
 * Used to detect expiry before API calls so pages like /report can redirect early.
 */

/** Must match clientAuthFetch redirect target */
export const LOGIN_SESSION_EXPIRED_HREF = "/login?session=expired";

/**
 * Decode JWT payload (no signature verification — UX only; server still validates).
 */
export function decodeJwtPayload(
  token: string
): Record<string, unknown> | null {
  try {
    const parts = token.split(".");
    if (parts.length < 2) return null;
    const payload = parts[1];
    const base64 = payload.replace(/-/g, "+").replace(/_/g, "/");
    const padded = base64.padEnd(
      base64.length + ((4 - (base64.length % 4)) % 4),
      "="
    );
    const binary = atob(padded);
    const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
    const json = new TextDecoder().decode(bytes);
    return JSON.parse(json) as Record<string, unknown>;
  } catch {
    return null;
  }
}

/**
 * True if `exp` claim is reached or passed. False if no `exp` (let API decide).
 */
export function isBackendJwtExpired(token: string): boolean {
  const payload = decodeJwtPayload(token);
  const exp = payload?.exp;
  if (typeof exp !== "number") return false;
  return Date.now() / 1000 >= exp;
}
