(function () {
    'use strict';

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

    function settled(promise) {
        return Promise.resolve(promise).then(
            function (value) {
                return { ok: true, value: value };
            },
            function (error) {
                return { ok: false, error: error };
            }
        );
    }

    function firstBalance(payload, assetType) {
        var items = Array.isArray(payload)
            ? payload
            : (payload && (payload.balances || payload.items)) || [];
        return (
            items.find(function (item) {
                return (
                    String(
                        item.asset_type || item.assetType || ''
                    ).toUpperCase() === assetType
                );
            }) || null
        );
    }

    function normalizeProfile(payload) {
        var profile =
            (payload && (payload.profile || payload.user)) || payload || {};
        return {
            contact: String(profile.contact_info || profile.contactInfo || ''),
        };
    }

    function normalizeOverview(payload) {
        var agency = (payload && payload.agency) || {};
        return {
            agency: {
                id: String(agency.agency_id || agency.agencyId || ''),
                shortId: String(
                    agency.short_id ||
                        agency.shortId ||
                        agency.agency_id ||
                        agency.agencyId ||
                        ''
                ),
                name: String(agency.name || ''),
                avatar: String(agency.avatar || agency.avatar_url || ''),
                createdAtMS: Number(
                    agency.created_at_ms || agency.createdAtMs || 0
                ),
            },
        };
    }

    function normalizeStats(payload, range) {
        var source = payload || {};
        var summary = source.summary || {};
        return {
            range: source.range || range,
            summary: {
                total_earnings: Number(summary.total_earnings || 0),
                gift_income: Number(summary.gift_income || 0),
                share_income: Number(summary.share_income || 0),
                total_hosts: Number(summary.total_hosts || 0),
                gifted_host_count: Number(summary.gifted_host_count || 0),
            },
            hosts: Array.isArray(source.hosts)
                ? source.hosts.map(function (host) {
                      return {
                          membershipId: String(host.membership_id || ''),
                          userId: String(host.host_user_id || ''),
                          displayUserId: String(
                              host.display_user_id || host.host_user_id || ''
                          ),
                          name: String(host.username || ''),
                          avatar: String(host.avatar || ''),
                          joinedAtMS: Number(host.joined_at_ms || 0),
                          diamondEarnings: Number(host.diamond_earnings || 0),
                          diamondExchanged: Number(host.diamond_exchanged || 0),
                          giftSenders: Number(host.gift_senders || 0),
                          onlineDurationMS: Number(
                              host.online_duration_ms || 0
                          ),
                          validMicDurationMS: Number(
                              host.valid_mic_duration_ms || 0
                          ),
                          validMicDays: Number(host.valid_mic_days || 0),
                          removable: host.removable !== false,
                      };
                  })
                : [],
        };
    }

    function mockData(range) {
        return {
            agency: {
                id: '343434',
                shortId: '343434',
                name: 'Fami Stars Agency',
                avatar: '',
                createdAtMS: new Date(2025, 9, 12, 15, 0).getTime(),
            },
            contact: '+20 1524151515',
            pointBalance: 5152051511212,
            stats: normalizeStats(
                {
                    summary: {
                        total_earnings: 10000,
                        gift_income: 10000,
                        share_income: 10000,
                        total_hosts: 1,
                        gifted_host_count: 1,
                    },
                    hosts: [
                        {
                            membership_id: '8001',
                            host_user_id: '3534',
                            display_user_id: '3534',
                            username: 'Host dada',
                            diamond_earnings: 343434,
                            diamond_exchanged: 343434,
                            gift_senders: 343434,
                            online_duration_ms: 165 * 60 * 1000,
                            valid_mic_duration_ms: 152 * 60 * 1000,
                            valid_mic_days: 12,
                            joined_at_ms: new Date(
                                2025,
                                4,
                                31,
                                15,
                                0
                            ).getTime(),
                        },
                    ],
                },
                range
            ),
            errors: {},
        };
    }

    function load(range) {
        if (params().get('mock') === '1')
            return Promise.resolve(mockData(range));
        var api = window.HyAppAPI || {};
        if (!api.user || !api.agencyCenter || !api.wallet) {
            return Promise.reject(new Error('guild_api_unavailable'));
        }
        return Promise.all([
            settled(api.user.me()),
            settled(api.agencyCenter.overview()),
            settled(api.wallet.balances(['POINT'])),
            settled(
                api.agencyCenter.stats({
                    start_date: range.startDate,
                    end_date: range.endDate,
                })
            ),
        ]).then(function (results) {
            // owner 身份和 agency 资料是页面最小事实；余额/统计允许独立降级，避免聚合服务故障遮住管理入口。
            if (!results[0].ok) throw results[0].error;
            if (!results[1].ok) throw results[1].error;
            var overview = normalizeOverview(results[1].value);
            var profile = normalizeProfile(results[0].value);
            var point = results[2].ok
                ? firstBalance(results[2].value, 'POINT')
                : null;
            return {
                agency: overview.agency,
                contact: profile.contact,
                pointBalance: point
                    ? Number(
                          point.available_amount || point.availableAmount || 0
                      )
                    : null,
                stats: results[3].ok
                    ? normalizeStats(results[3].value, range)
                    : normalizeStats({}, range),
                errors: {
                    balance: results[2].ok ? null : results[2].error,
                    stats: results[3].ok ? null : results[3].error,
                },
            };
        });
    }

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

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

    function inviteHost(displayUserID) {
        if (params().get('mock') === '1') return Promise.resolve({});
        var api = window.HyAppAPI;
        // 邀请写接口只接受内部 user_id；先通过公共解析接口把用户输入的展示 ID 转换，禁止前端猜测两种 ID 相同。
        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('host_not_found');
                return api.agencyCenter.inviteHost({
                    command_id: commandID('fami-agency-invite-host'),
                    target_user_id: String(userID),
                });
            });
    }

    function removeHost(hostUserID) {
        if (params().get('mock') === '1') return Promise.resolve({});
        return window.HyAppAPI.agencyCenter.removeHost(hostUserID, {
            command_id: commandID('fami-agency-remove-host'),
        });
    }

    window.HyGuild = window.HyGuild || {};
    window.HyGuild.agencyCenter = {
        load: load,
        saveContact: saveContact,
        inviteHost: inviteHost,
        removeHost: removeHost,
    };
})();
