const { request } = require('../../utils_new/request');

Page({
  data: {
    statusBarHeight: 20,
    navBarHeight: 44,
    totalNavHeight: 64,
    loading: true,
    items: []
  },
  onLoad() {
    const sys = wx.getSystemInfoSync();
    const menu = wx.getMenuButtonBoundingClientRect();
    const statusBarHeight = sys.statusBarHeight || 20;
    const navBarHeight = menu.height + (menu.top - statusBarHeight) * 2;
    this.setData({ 
      statusBarHeight,
      navBarHeight,
      totalNavHeight: statusBarHeight + navBarHeight
    });
    this.load();
  },
  onBack() {
    wx.navigateBack({ delta: 1 });
  },
  async load() {
    this.setData({ loading: true });
    try {
      try {
          const res = await request({ url: '/api/backpack', method: 'GET' });
          const body = res.data || {};
          if (body.code !== 0) throw new Error(body.message || '加载失败');
          const items = (body.data?.items || body.data || []).map((x) => ({
            id: x.id || x.item_id || '',
            name: x.name || x.item_name || '',
            quantity: Number(x.quantity || 0),
            image_url: x.image_url || x.imageUrl || ''
          }));
          this.setData({ items });
      } catch (err) {
          console.log('API failed, using mock data');
          this.setData({
              items: [
                  { id: 1, name: '新手礼包', quantity: 1, image_url: '' },
                  { id: 2, name: '加速卡', quantity: 5, image_url: '' }
              ]
          });
      }
    } finally {
      this.setData({ loading: false });
    }
  }
});

