/*
 * Copyright (c) 2023-2025 Datalayer, Inc.
 * Distributed under the terms of the Modified BSD License.
 */
// ── Utilities ─────────────────────────────────────────────────────
/**
 * Decode the payload of a JWT without verifying the signature.
 * Returns `null` on any error (malformed token, invalid base64, etc.).
 */
export function parseJwtPayload(token) {
    try {
        const parts = token.split('.');
        if (parts.length < 2)
            return null;
        // Base64Url → Base64 → JSON
        const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
        const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), '=');
        const json = atob(padded);
        return JSON.parse(json);
    }
    catch {
        return null;
    }
}
/**
 * Extract the Datalayer user object from a JWT, returning `null` if the
 * token is missing or cannot be decoded.
 */
export function getDatalayerJwtUser(token) {
    if (!token)
        return null;
    const payload = parseJwtPayload(token);
    return payload?.user ?? null;
}
/**
 * Format a human-readable display name from a JWT user.
 * Prefers "FirstName LastName", falls back to handle.
 */
export function getDatalayerDisplayName(user, fallback = '') {
    if (!user)
        return fallback;
    const full = `${user.firstName ?? ''} ${user.lastName ?? ''}`.trim();
    return full || user.handle || fallback;
}
