// UserCard (@arcblock/ux) calls sdk.user.getUserPublicInfo per mount without
// in-flight dedup. Pages that render many rows with the same DID fire N
// concurrent requests before the first response warms sessionStorage.
// Patch the bundled SDK singleton so concurrent calls with the same args
// share one Promise.
// Deep import into ux's nested js-sdk copy (intentional; that bundle exposes
// the SDK singleton UserCard actually calls into — patching any other copy
// of @blocklet/js-sdk doesn't affect UserCard).
// eslint-disable-next-line import/extensions
import { getBlockletSDK } from '@arcblock/ux/lib/node_modules/@blocklet/js-sdk/dist/index.js';

type PublicInfoArgs = { did?: string; name?: string };

const sdk = getBlockletSDK() as { user: { getUserPublicInfo: (args: PublicInfoArgs) => Promise<unknown> } };
const original = sdk.user.getUserPublicInfo.bind(sdk.user);
const inflight = new Map<string, Promise<unknown>>();

sdk.user.getUserPublicInfo = (args: PublicInfoArgs) => {
  const key = `${args?.did || ''}|${args?.name || ''}`;
  const pending = inflight.get(key);
  if (pending) return pending;
  const promise = original(args).finally(() => inflight.delete(key));
  inflight.set(key, promise);
  return promise;
};
