(function () {
    'use strict';

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

    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 normalizeBalance(value) {
        value = value || {};
        return {
            available: Number(
                value.available_amount || value.availableAmount || 0
            ),
            frozen: Number(value.frozen_amount || value.frozenAmount || 0),
            displayUSD: String(value.display_usd || value.displayUSD || '0.00'),
        };
    }

    function normalizeSeller(value) {
        value = value || {};
        return {
            userId: String(value.user_id || value.userId || ''),
            displayUserId: String(
                value.display_user_id || value.displayUserId || ''
            ),
            nickname: String(value.nickname || ''),
            avatar: String(value.avatar || ''),
            sortOrder: Number(value.sort_order || value.sortOrder || 0),
            pointAmount: Number(value.point_amount || value.pointAmount || 0),
            sellerCoinAmount: Number(
                value.seller_coin_amount || value.sellerCoinAmount || 0
            ),
            serviceCountries:
                value.service_country_codes || value.serviceCountryCodes || [],
        };
    }

    function normalizeTransaction(value) {
        value = value || {};
        return {
            id: String(value.transaction_id || value.transactionId || ''),
            bizType: String(value.biz_type || value.bizType || ''),
            availableDelta: Number(
                value.available_delta || value.availableDelta || 0
            ),
            counterpartyUserId: String(
                value.counterparty_user_id || value.counterpartyUserId || ''
            ),
            createdAtMS: Number(value.created_at_ms || value.createdAtMs || 0),
        };
    }

    function normalizeOverview(value) {
        value = value || {};
        var address = value.withdraw_address || value.withdrawAddress || {};
        return {
            balance: normalizeBalance(value.balance),
            pointsPerUSD: Number(
                value.points_per_usd || value.pointsPerUSD || 0
            ),
            feeBPS: Number(value.fee_bps || value.feeBPS || 0),
            minimumPoints: Number(
                value.minimum_points || value.minimumPoints || 0
            ),
            policyInstance: String(
                value.policy_instance_code || value.policyInstance || ''
            ),
            address: String(
                address.usdt_trc20_address || address.usdtTRC20Address || ''
            ),
            sellers: (value.coin_sellers || value.coinSellers || [])
                .map(normalizeSeller)
                .filter(function (item) {
                    return (
                        item.userId &&
                        item.pointAmount > 0 &&
                        item.sellerCoinAmount > 0
                    );
                }),
        };
    }

    function normalizeHistory(value) {
        var items = Array.isArray(value)
            ? value
            : (value && (value.transactions || value.items)) || [];
        return items.map(normalizeTransaction);
    }

    function mockData() {
        return {
            balance: {
                available: 5152051511212,
                frozen: 0,
                displayUSD: '51520515.11',
            },
            pointsPerUSD: 100000,
            feeBPS: 500,
            minimumPoints: 1000000,
            policyInstance: 'fami-guild-demo',
            address: '',
            sellers: [
                {
                    userId: '34343',
                    displayUserId: '34343',
                    nickname: 'Coin Seller One',
                    avatar: '',
                    sortOrder: 1,
                    pointAmount: 100000,
                    sellerCoinAmount: 92000,
                    serviceCountries: ['SA', 'TR'],
                },
                {
                    userId: '34344',
                    displayUserId: '34344',
                    nickname: 'Coin Seller Two',
                    avatar: '',
                    sortOrder: 2,
                    pointAmount: 100000,
                    sellerCoinAmount: 90000,
                    serviceCountries: [],
                },
            ],
            history: [
                {
                    id: 'demo-1',
                    bizType: 'point_transfer_to_coin_seller',
                    availableDelta: -1000000,
                    counterpartyUserId: '34343',
                    createdAtMS: Date.now() - 3600000,
                },
            ],
        };
    }

    function load() {
        if (query().get('mock') === '1') return Promise.resolve(mockData());
        var api = window.HyAppAPI && window.HyAppAPI.pointWallet;
        if (!api)
            return Promise.reject(new Error('point_wallet_api_unavailable'));
        return Promise.all([
            api.overview(),
            api.history(30).catch(function () {
                // 流水故障不应遮住余额和提现入口；页面会单独提示历史暂不可用。
                return null;
            }),
        ]).then(function (results) {
            var data = normalizeOverview(results[0]);
            data.history = normalizeHistory(results[1]);
            data.historyUnavailable = results[1] === null;
            return data;
        });
    }

    function transferToCoinSeller(sellerUserID, pointAmount) {
        if (query().get('mock') === '1') return Promise.resolve({});
        return window.HyAppAPI.pointWallet.transferToCoinSeller({
            command_id: commandID('fami-point-coin-seller'),
            seller_user_id: String(sellerUserID || ''),
            point_amount: Number(pointAmount || 0),
        });
    }

    function withdrawUSDT(pointAmount, address) {
        if (query().get('mock') === '1') return Promise.resolve({});
        return window.HyAppAPI.pointWallet.withdrawUSDT({
            command_id: commandID('fami-point-usdt'),
            gross_point_amount: Number(pointAmount || 0),
            usdt_trc20_address: String(address || '').trim(),
        });
    }

    function saveAddress(address) {
        if (query().get('mock') === '1') return Promise.resolve({});
        // 地址写入继续复用通用工资钱包用户资料接口；资金冻结仍只由 POINT 提现接口完成。
        return window.HyAppAPI.salaryWallet.saveWithdrawAddress({
            usdt_trc20_address: String(address || '').trim(),
        });
    }

    window.HyGuild = window.HyGuild || {};
    window.HyGuild.wallet = {
        load: load,
        saveAddress: saveAddress,
        transferToCoinSeller: transferToCoinSeller,
        withdrawUSDT: withdrawUSDT,
    };
})();
