import { toTypeInfo as c } from "@arcblock/did";
import { types as i } from "@ocap/mcrypto";
import { BlockletSDK as l } from "@blocklet/js-sdk";
let s = null;
try {
  s = new l();
} catch (e) {
  console.error("Failed to initialize BlockletSDK:", e), s = null;
}
const n = "ux_user_", u = 60 * 60 * 1e3, f = (e) => {
  if (typeof sessionStorage > "u") return null;
  try {
    const r = `${n}${e}`, t = sessionStorage.getItem(r);
    if (!t) return null;
    const o = JSON.parse(t), a = o.timestamp || 0;
    return Date.now() - a > u ? (sessionStorage.removeItem(r), null) : o.user;
  } catch (r) {
    return console.error(`Failed to load user cache for did ${e}:`, r), null;
  }
}, m = (e, r) => {
  if (!(typeof sessionStorage > "u"))
    try {
      const t = `${n}${e}`, o = {
        user: r,
        timestamp: Date.now()
      };
      sessionStorage.setItem(t, JSON.stringify(o));
    } catch (t) {
      console.error(`Failed to save user cache for did ${e}:`, t);
    }
};
function g(e) {
  if (!e) return null;
  let r = "";
  return e.fullName ? r = e.fullName.charAt(0).toUpperCase() : e.email ? r = e.email.split("@")[0].charAt(0).toUpperCase() : r = e.did ? e.did.charAt(0).toUpperCase() : "?", r;
}
function S(e) {
  if (!e || typeof e != "string") return !1;
  try {
    const r = c(e);
    return r.role !== void 0 && r.role !== i.RoleType.ROLE_APPLICATION;
  } catch (r) {
    return console.error("Failed to check if did is user did:", r), !1;
  }
}
async function I(e) {
  if (!e) return null;
  const r = f(e);
  if (r)
    return r;
  if (!s) return null;
  try {
    const t = await s.user.getUserPublicInfo({ did: e });
    return t && m(e, t), t;
  } catch (t) {
    return console.error("Failed to get user by did:", t), null;
  }
}
function U(e) {
  if (!(typeof sessionStorage > "u"))
    if (e)
      try {
        sessionStorage.removeItem(`${n}${e}`);
      } catch (r) {
        console.error(`Failed to remove cache for did ${e}:`, r);
      }
    else
      try {
        const r = [];
        for (let t = 0; t < sessionStorage.length; t++) {
          const o = sessionStorage.key(t);
          o && o.startsWith(n) && r.push(o);
        }
        r.forEach((t) => sessionStorage.removeItem(t));
      } catch (r) {
        console.error("Failed to clear all user caches:", r);
      }
}
export {
  U as clearUserCache,
  g as createNameOnlyAvatar,
  I as getUserByDid,
  S as isUserDid
};
