const KEY = "sociowire:auth";

export function loadAuth() {
  try {
    const raw = localStorage.getItem(KEY);
    if (!raw) return null;
    const v = JSON.parse(raw);
    if (!v || typeof v !== "object") return null;
    return v;
  } catch {
    return null;
  }
}

export function saveAuth(v) {
  try {
    localStorage.setItem(KEY, JSON.stringify(v || {}));
  } catch {}
}

export function clearAuth() {
  try {
    localStorage.removeItem(KEY);
  } catch {}
}

export function decodeJwtPayload(token) {
  try {
    if (!token || typeof token !== "string") return null;
    const parts = token.split(".");
    if (parts.length < 2) return null;
    const b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
    const pad = b64.length % 4 ? "=".repeat(4 - (b64.length % 4)) : "";
    const json = atob(b64 + pad);
    return JSON.parse(json);
  } catch {
    return null;
  }
}

export function jwtExpSeconds(token) {
  const p = decodeJwtPayload(token);
  if (!p || !p.exp) return 0;
  const exp = Number(p.exp);
  return Number.isFinite(exp) ? exp : 0;
}

export function guessUsernameFromToken(token) {
  const p = decodeJwtPayload(token);
  if (!p) return "";
  return (
    (typeof p.preferred_username === "string" && p.preferred_username) ||
    (typeof p.email === "string" && p.email) ||
    (typeof p.sub === "string" && p.sub) ||
    ""
  );
}
