const pc = window.pc;
import { getRandomAvatar as A, getRandomName as y, Debugger as c, BaseSystem as I, registerModule as _, BaseModule as k } from "./core.mjs";
import { SystemName as b, ModuleName as p } from "./types.mjs";
import { getViverseConfig as g } from "./config.mjs";
const S = (a) => {
  let t;
  const e = /* @__PURE__ */ new Set(), r = (o, h) => {
    const n = typeof o == "function" ? o(t) : o;
    if (!Object.is(n, t)) {
      const v = t;
      t = h ?? (typeof n != "object" || n === null) ? n : Object.assign({}, t, n), e.forEach((f) => f(t, v));
    }
  }, s = () => t, i = { setState: r, getState: s, getInitialState: () => l, subscribe: (o) => (e.add(o), () => e.delete(o)) }, l = t = a(r, s, i);
  return i;
}, C = (a) => a ? S(a) : S, E = (a) => (t, e, r) => {
  const s = r.subscribe;
  return r.subscribe = (d, i, l) => {
    let o = d;
    if (i) {
      const h = l?.equalityFn || Object.is;
      let n = d(r.getState());
      o = (v) => {
        const f = d(v);
        if (!h(n, f)) {
          const w = n;
          i(n = f, w);
        }
      }, l?.fireImmediately && i(n, n);
    }
    return s(o);
  }, a(t, e, r);
}, U = E, m = {
  isOwner: !1,
  isLoggedIn: !1,
  userProfile: {},
  avatarProfile: {},
  credentials: {}
}, V = () => C()(
  U((a) => ({
    ...m,
    setIsOwner: (t) => a({ isOwner: t }),
    setCredentials: (t) => a({ credentials: t }),
    setIsLoggedIn: (t) => a({ isLoggedIn: t }),
    setUserProfile: (t) => a((e) => ({ userProfile: { ...e.userProfile, ...t } })),
    setAvatarProfile: (t) => a((e) => ({ avatarProfile: { ...e.avatarProfile, ...t } })),
    reset: () => a(m)
  }))
), N = async () => {
  try {
    const a = await A();
    return {
      userProfile: {
        displayName: y()
      },
      avatarProfile: {
        id: a.id,
        snapshot: a.headIconUrl,
        fullBodySnapshot: a.snapshotUrl,
        url: a.avatarUrl
      }
    };
  } catch (a) {
    return c.error(
      `Guest authentication failed: ${a instanceof Error ? a.message : "Unknown error"}`
    ), null;
  }
};
class j extends I {
  static systemName = b.Account;
  modules = {};
  store;
  _options;
  constructor(t, e) {
    super(t), this._options = e, this.store = V();
  }
  async start() {
    try {
      await this._setupAuthModule();
      const t = this.modules.auth;
      if (!t) {
        c.error("Auth module failed to initialize."), await this._handleGuestAuth();
        return;
      }
      const e = await t.checkAuth(), r = await t.getProfile();
      if (e && r) {
        const { accountId: s, accessToken: u } = e, { name: d, activeAvatar: i } = r, l = {
          userProfile: {
            accountId: s,
            displayName: d || "Unknown"
          },
          ...i && {
            avatarProfile: {
              id: i.id,
              snapshot: i.headIconUrl,
              fullBodySnapshot: i.snapshot,
              url: i.url
            }
          },
          credentials: {
            accessToken: u
            // token: null, // reticulum token
            // email: null,
          }
        };
        this._updateStateFromProfile(l);
      } else
        await this._handleGuestAuth();
    } catch (t) {
      await this._handleGuestAuth(), c.error("Error during AccountSystem start:", t);
    }
  }
  async _setupAuthModule() {
    try {
      const { modules: t = [] } = this._options || {}, e = t.find((s) => s.name === p.Auth);
      if (!e)
        throw new Error("Auth module could not be found.");
      const r = await e.Module.initialize(this);
      if (!r)
        throw new Error("Module instance could not be created.");
      _(this.modules, r.name, r);
    } catch (t) {
      c.error("Failed to setup the Auth module:", t);
    }
  }
  async _handleGuestAuth() {
    const t = await N();
    t && this._updateStateFromProfile(t);
  }
  _updateStateFromProfile(t) {
    t.userProfile && (t.userProfile.accountId && this.store.getState().setIsLoggedIn(!0), this.store.getState().setUserProfile(t.userProfile), this.viverseApp.context.profile.getState().setProfile({
      displayName: t.userProfile.displayName
    })), t.avatarProfile && (this.store.getState().setAvatarProfile(t.avatarProfile), this.viverseApp.context.profile.getState().setProfile({
      avatarUrl: t.avatarProfile.url,
      snapshot: t.avatarProfile.snapshot,
      fullBodySnapshot: t.avatarProfile.fullBodySnapshot
    })), t.credentials && this.store.getState().setCredentials(t.credentials);
  }
  isLoggedIn() {
    return this.store.getState().isLoggedIn;
  }
  async login() {
    const t = this.modules.auth;
    if (!t)
      throw new Error("Auth module is not available.");
    await t.login();
  }
  getUserProfile() {
    return this.store.getState().userProfile;
  }
  getAvatarProfile() {
    return this.store.getState().avatarProfile;
  }
  destroy() {
    super.destroy(), Object.values(this.modules).forEach((t) => {
      t.destroy && t.destroy(), delete this.modules[t.name];
    });
  }
}
const D = {
  checkAuth: () => Promise.resolve(void 0),
  loginWithWorlds: () => Promise.resolve(),
  getToken: () => Promise.resolve(void 0)
};
class P extends k {
  static moduleName = p.Auth;
  _avatarSdk = null;
  _client = null;
  constructor(t) {
    super(t);
  }
  get _shouldUseFakeViverseClient() {
    return !window.parent || window === window.parent;
  }
  get client() {
    return this._getClient();
  }
  _createClientInstance() {
    const t = this.viverseApp.sdk.core;
    if (!t)
      throw new Error("VIVERSE SDK core is not available.");
    const e = this.system.viverseApp.appId;
    if (!e)
      throw new Error("App ID is not provided for VIVERSE SDK Client initialization.");
    const { htcAccountDomain: r } = g(), s = new t.client({
      clientId: e,
      domain: r
    });
    return window.viverseAuthSdkClient = s, s;
  }
  _getClient() {
    return this._shouldUseFakeViverseClient ? D : this._client;
  }
  /** @hidden */
  static async initialize(t, e) {
    try {
      const r = new P(t);
      return await t.viverseApp.sdk.load(), r._client = r._createClientInstance(), c.log("VIVERSE SDK Client Initialized"), r;
    } catch (r) {
      return c.error(r), null;
    }
  }
  async checkAuth() {
    const t = this._getClient();
    if (!t)
      return c.warn("VIVERSE Client is not available."), null;
    const e = await t.checkAuth();
    return e ? {
      accessToken: e.access_token,
      accountId: e.account_id
    } : (this._shouldUseFakeViverseClient || c.error("No authentication result found."), null);
  }
  login() {
    const t = this._getClient();
    return t ? t.loginWithWorlds() : Promise.reject("VIVERSE SDK Client is not available.");
  }
  async _createAvatarInstance() {
    const t = this._getClient();
    if (!t) return null;
    const e = await t.getToken();
    if (!e)
      return null;
    const r = this.viverseApp.sdk.core;
    if (!r)
      return Promise.reject("VIVERSE SDK core is not available.");
    const s = g(), u = new r.avatar({
      baseURL: s.viverseSdkApiDomain,
      token: e
    });
    return window.viverseSdkAvatar = u, u;
  }
  async getProfile() {
    if (this._avatarSdk || (this._avatarSdk = await this._createAvatarInstance()), !this._avatarSdk)
      return null;
    const t = await this._avatarSdk.getProfile(), e = {
      name: t.name
    };
    return t.activeAvatar && (e.activeAvatar = {
      id: t.activeAvatar.id,
      url: t.activeAvatar.vrmUrl,
      headIconUrl: t.activeAvatar.headIconUrl,
      snapshot: t.activeAvatar.snapshot
    }), e;
  }
}
export {
  j as AccountSystem,
  P as AuthModule
};
