import request from '../../../../utils/request';

Page({
    data: {
        dimensions: [],
        achievedMap: {},
        isLoading: true,
        selectedBadge: null,
        showDetail: false,
        activeTab: 0
    },

    onLoad() {
        this.fetchData();
    },

    switchTab(e) {
        const index = e.currentTarget.dataset.index;
        if (index !== undefined) {
            this.setData({ activeTab: index });
        }
    },

    async fetchData() {
        this.setData({ isLoading: true });
        wx.showLoading({ title: '加载中...' });
        try {
            // Fetch Config Tree
            const treeRes = await request.get('/config/badge/tree');
            const list = Array.isArray(treeRes) ? treeRes : (treeRes.data || []);

            // DEBUG: Force Unlock All
            let achievedMap = {};
            list.forEach(dim => {
                if (dim.groups) {
                    dim.groups.forEach(grp => {
                        if (grp.badges) {
                            grp.badges.forEach(b => {
                                achievedMap[b.id] = true;
                            });
                        }
                    });
                }
            });

            // Original logic commented out for debug
            /*
            try {
                const profile = await request.get('/profile/detail');
                if (profile && profile.achievedBadges) {
                    profile.achievedBadges.forEach(b => {
                        const id = typeof b === 'string' ? b : b.id;
                        achievedMap[id] = true;
                    });
                }
            } catch (e) {
                // Silent fail
            }
            */

            this.setData({
                dimensions: list,
                achievedMap
            });
        } catch (e) {
            console.error('Fetch badge tree failed', e);
            wx.showToast({ title: '加载失败', icon: 'none' });
        } finally {
            this.setData({ isLoading: false });
            wx.hideLoading();
        }
    },

    onBadgeTap(e) {
        const badge = e.currentTarget.dataset.badge;
        this.setData({
            selectedBadge: badge,
            showDetail: true
        });
    },

    closeDetail() {
        this.setData({ showDetail: false });
    },

    noop() { }
});
