export function parseAuthError(text = "", status = 0) {
  // Keycloak token error example:
  // {"error":"invalid_grant","error_description":"Account is not fully set up"}
  const raw = String(text || "");
  let err = "";
  let desc = "";

  try {
    const j = JSON.parse(raw);
    err = String(j.error || "");
    desc = String(j.error_description || j.errorMessage || "");
  } catch {
    // raw is not JSON
  }

  const combined = (err + " " + desc + " " + raw).toLowerCase();

  // Email verification / required action
  if (
    combined.includes("not fully set up") ||
    combined.includes("verify") ||
    combined.includes("verification") ||
    combined.includes("required action") ||
    (combined.includes("email") && combined.includes("verified"))
  ) {
    return {
      code: "email_verification_required",
      message:
        "Tu dois confirmer ton email avant de te connecter. Vérifie ta boîte mail (et le spam), puis réessaie.",
    };
  }

  // Bad credentials
  if (
    combined.includes("invalid user credentials") ||
    (combined.includes("invalid_grant") && !combined.includes("not fully set up"))
  ) {
    return { code: "invalid_credentials", message: "Mauvais username ou password." };
  }

  // Fallback
  if (desc) return { code: "login_failed", message: desc };
  if (err) return { code: "login_failed", message: err };
  if (raw && raw.length < 220) return { code: "login_failed", message: raw };

  return { code: "login_failed", message: status ? `Login failed (${status}).` : "Login failed." };
}
