function getBridge() {
  const bridge = globalThis.__NAPCAT_BRIDGE__;
  if (!bridge) throw new Error('[QCE Overlay] Bridge未初始化');
  return bridge;
}

export const GroupApi = {
  async getGroups(forceRefresh = false) {
    const { core } = getBridge();
    const impl = core?.apis?.GroupApi?.getGroups || core?.apis?.group?.getGroups;
    if (!impl) throw new Error('[QCE Overlay] GroupApi.getGroups 不可用');
    return impl.call(core.apis.GroupApi || core.apis.group, forceRefresh);
  },

  async fetchGroupDetail(groupId) {
    const { core } = getBridge();
    const impl = core?.apis?.GroupApi?.fetchGroupDetail || core?.apis?.group?.fetchGroupDetail;
    if (impl) return impl.call(core.apis.GroupApi || core.apis.group, String(groupId));
    
    const { actions, instance } = getBridge();
    const handler = actions?.get?.('get_group_info');
    if (!handler) throw new Error('[QCE Overlay] get_group_info 不可用');
    const result = await handler.handle({ group_id: Number(groupId) }, 'plugin', instance?.config);
    return result?.data;
  },

  async getGroupMemberAll(groupId, forceRefresh = false) {
    const { core } = getBridge();
    const impl = core?.apis?.GroupApi?.getGroupMemberAll || core?.apis?.group?.getGroupMemberAll;
    if (impl) return impl.call(core.apis.GroupApi || core.apis.group, String(groupId), forceRefresh);
    
    const { actions, instance } = getBridge();
    const handler = actions?.get?.('get_group_member_list');
    if (!handler) throw new Error('[QCE Overlay] get_group_member_list 不可用');
    const result = await handler.handle({ group_id: Number(groupId) }, 'plugin', instance?.config);
    return { result: { infos: new Map(result?.data?.map(m => [m.user_id, m]) || []) } };
  }
};

export const NTQQGroupApi = GroupApi;
export default GroupApi;
