(function () {
    'use strict';

    function params() {
        return new URLSearchParams(window.location.search || '');
    }

    function normalizeOverview(payload) {
        var profile = (payload && payload.profile) || {};
        var role = (payload && payload.bd_profile) || {};
        return {
            profile: {
                userId: String(profile.user_id || role.user_id || ''),
                displayUserId: String(
                    profile.display_user_id ||
                        profile.user_id ||
                        role.user_id ||
                        ''
                ),
                name: String(profile.username || ''),
                avatar: String(profile.avatar || ''),
                contact: String(
                    profile.contact_info || profile.contactInfo || ''
                ),
            },
        };
    }

    function normalizeStats(payload, range) {
        return {
            range: (payload && payload.range) || range,
            agencies: Array.isArray(payload && payload.items)
                ? payload.items.map(function (item) {
                      var agency = item.agency || {};
                      var owner = item.owner || {};
                      return {
                          id: String(agency.agency_id || ''),
                          shortId: String(
                              agency.short_id || agency.agency_id || ''
                          ),
                          name: String(agency.name || ''),
                          avatar: String(agency.avatar || ''),
                          ownerId: String(
                              owner.display_user_id || owner.user_id || ''
                          ),
                          ownerName: String(owner.username || ''),
                          country: String(item.country || owner.country || ''),
                          totalHosts: Number(item.total_hosts || 0),
                          giftedHostCount: Number(item.gifted_host_count || 0),
                          diamondEarnings: Number(item.diamond_earnings || 0),
                          joinedAtMS: Number(item.joined_at_ms || 0),
                      };
                  })
                : [],
        };
    }

    function mockData(range) {
        return {
            profile: {
                userId: '163028',
                displayUserId: '163028',
                name: 'dada',
                avatar: '',
                contact: '1586668885',
            },
            stats: normalizeStats(
                {
                    items: [
                        {
                            agency: {
                                agency_id: '343434',
                                short_id: '343434',
                                name: 'Fami Stars',
                            },
                            owner: {
                                display_user_id: '3534',
                                username: 'Agency owner',
                            },
                            country: 'Saudi Arabia',
                            total_hosts: 12,
                            gifted_host_count: 8,
                            diamond_earnings: 5152051,
                            joined_at_ms: new Date(
                                2025,
                                4,
                                31,
                                15,
                                0
                            ).getTime(),
                        },
                    ],
                },
                range
            ),
        };
    }

    function load(range) {
        if (params().get('mock') === '1')
            return Promise.resolve(mockData(range));
        var api = window.HyAppAPI || {};
        if (!api.bdCenter || !api.user) {
            return Promise.reject(new Error('guild_api_unavailable'));
        }
        return Promise.all([
            api.bdCenter.overview(),
            api.bdCenter.stats({
                start_date: range.startDate,
                end_date: range.endDate,
            }),
        ]).then(function (results) {
            var overview = normalizeOverview(results[0]);
            return {
                profile: overview.profile,
                stats: normalizeStats(results[1], range),
            };
        });
    }

    function commandID() {
        var random =
            window.crypto && window.crypto.randomUUID
                ? window.crypto.randomUUID()
                : Date.now() + '-' + Math.random().toString(16).slice(2);
        return 'fami-bd-invite-agency:' + random;
    }

    function saveContact(value) {
        if (params().get('mock') === '1') return Promise.resolve({});
        return window.HyAppAPI.user.updateContact({ contact_info: value });
    }

    function inviteAgency(displayUserID, agencyName) {
        if (params().get('mock') === '1') return Promise.resolve({});
        var api = window.HyAppAPI;
        // BD 写接口使用内部 user_id；展示 ID 解析由 gateway 完成，避免把短号误当主键。
        return api.user
            .resolveDisplayUserID(displayUserID)
            .then(function (payload) {
                var user =
                    (payload && (payload.user || payload.profile)) ||
                    payload ||
                    {};
                var userID = user.user_id || user.userId;
                if (!userID) throw new Error('agency_owner_not_found');
                return api.bdCenter.inviteAgency({
                    command_id: commandID(),
                    target_user_id: String(userID),
                    agency_name: String(agencyName || '').trim(),
                });
            });
    }

    window.HyGuild = window.HyGuild || {};
    window.HyGuild.bdCenter = {
        load: load,
        saveContact: saveContact,
        inviteAgency: inviteAgency,
    };
})();
