(function () {
    'use strict';

    var METRICS = [
        { key: 'diamond_earnings', format: 'count' },
        { key: 'diamond_exchanged', format: 'count' },
        { key: 'gift_senders', format: 'count' },
        { key: 'online_duration_ms', format: 'duration' },
        { key: 'valid_mic_duration_ms', format: 'duration' },
        { key: 'valid_mic_days', format: 'count' },
        { key: 'private_message_senders', format: 'count' },
        { key: 'new_followers', format: 'count' },
    ];

    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)) || [];
        for (var i = 0; i < items.length; i += 1) {
            var item = items[i] || {};
            if (
                String(
                    item.asset_type || item.assetType || ''
                ).toUpperCase() === assetType
            ) {
                return item;
            }
        }
        return null;
    }

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

    function normalizeAgency(payload) {
        var agency =
            payload && Object.prototype.hasOwnProperty.call(payload, 'agency')
                ? payload.agency
                : payload;
        if (!agency) return null;
        return {
            id: String(agency.agency_id || agency.agencyId || ''),
            shortId: String(
                agency.short_id ||
                    agency.shortId ||
                    agency.agency_id ||
                    agency.agencyId ||
                    ''
            ),
            name: String(agency.name || ''),
            joinedAtMS: Number(agency.joined_at_ms || agency.joinedAtMs || 0),
        };
    }

    function normalizeStats(payload, range) {
        var source =
            (payload && (payload.metrics || payload.stats)) || payload || {};
        var metrics = {};
        METRICS.forEach(function (definition) {
            var value = source[definition.key];
            metrics[definition.key] =
                value === undefined || value === null ? null : Number(value);
        });
        return {
            range: (payload && payload.range) || range,
            metrics: metrics,
        };
    }

    function mockData(range) {
        return {
            profile: {
                userId: '163028',
                displayUserId: '163028',
                name: 'dada',
                avatar: '',
                contact: '1586668885',
            },
            agency: {
                id: '163030',
                shortId: '163030',
                name: 'Fami Stars',
                joinedAtMS: new Date(2025, 5, 12, 16, 0).getTime(),
            },
            pointBalance: 5152051511212,
            stats: normalizeStats(
                {
                    diamond_earnings: 50000,
                    diamond_exchanged: 50000,
                    gift_senders: 50000,
                    online_duration_ms: 53 * 60 * 1000,
                    valid_mic_duration_ms: 53 * 60 * 1000,
                    valid_mic_days: 12,
                    private_message_senders: 50000,
                    new_followers: 50000,
                },
                range
            ),
            errors: {},
        };
    }

    function load(range) {
        if (params().get('mock') === '1') {
            return Promise.resolve(mockData(range));
        }
        var api = window.HyAppAPI || {};
        if (!api.user || !api.hostCenter || !api.wallet) {
            return Promise.reject(new Error('guild_api_unavailable'));
        }

        return Promise.all([
            settled(api.user.me()),
            settled(api.hostCenter.agency()),
            settled(api.wallet.balances(['POINT'])),
            settled(
                api.hostCenter.stats({
                    start_date: range.startDate,
                    end_date: range.endDate,
                })
            ),
        ]).then(function (results) {
            // 资料是页面身份校验的最低要求；其余读模型可以分别降级，不能因统计服务晚发布让联系方式和余额也不可见。
            if (!results[0].ok) throw results[0].error;
            var errors = {};
            if (!results[1].ok) errors.agency = results[1].error;
            if (!results[2].ok) errors.balance = results[2].error;
            if (!results[3].ok) errors.stats = results[3].error;
            var point = results[2].ok
                ? firstBalance(results[2].value, 'POINT')
                : null;
            return {
                profile: normalizeProfile(results[0].value),
                agency: results[1].ok
                    ? normalizeAgency(results[1].value)
                    : null,
                pointBalance: point
                    ? Number(
                          point.available_amount || point.availableAmount || 0
                      )
                    : null,
                stats: results[3].ok
                    ? normalizeStats(results[3].value, range)
                    : normalizeStats({}, range),
                errors: errors,
            };
        });
    }

    function saveContact(value) {
        if (params().get('mock') === '1') {
            return Promise.resolve({ contact_info: value });
        }
        var api = window.HyAppAPI || {};
        if (!api.user || !api.user.updateContact) {
            return Promise.reject(new Error('guild_api_unavailable'));
        }
        return api.user.updateContact({ contact_info: value });
    }

    window.HyGuild = window.HyGuild || {};
    window.HyGuild.hostCenter = {
        metrics: Object.freeze(METRICS.slice()),
        load: load,
        saveContact: saveContact,
    };
})();
