const api = require('../../utils/api');

Page({
  data: {
    statusBarHeight: 20,
    navBarHeight: 44,
    totalNavHeight: 64,
    role: '',
    level: '',
    currentPackage: null,
    loading: true
  },

  onLoad(options) {
    const { role, level } = options;
    const systemInfo = wx.getSystemInfoSync();
    const statusBarHeight = systemInfo.statusBarHeight || 20;
    const menuButton = wx.getMenuButtonBoundingClientRect();
    const navBarHeight = menuButton.height + (menuButton.top - statusBarHeight) * 2;

    this.setData({
      statusBarHeight,
      navBarHeight,
      totalNavHeight: statusBarHeight + navBarHeight,
      role: role || '',
      level: level || ''
    });

    this.loadBenefits();
  },

  async loadBenefits() {
    try {
      const res = await api.payment.getPackages();
      const body = res.data || {};
      const list = Array.isArray(body) ? body : body?.data || [];

      if (!list.length) {
        this.setData({ loading: false });
        return;
      }

      // 映射逻辑与 recharge.js 保持一致
      const allPackages = list.map((p) => {
        const attrs = p.attributes || {};
        const benefits = p.benefits || attrs.benefits || [];
        const gradientStart = p.gradientStart || attrs.gradient_start || '#60A5FA';
        const gradientEnd = p.gradientEnd || attrs.gradient_end || '#2563EB';
        const tagColor = p.tagColor || attrs.tag_color || '#1E3A8A';

        let vipType = attrs.type || p.vipType || '';
        if (vipType === 'monthly') vipType = 'month';
        if (vipType === 'yearly') vipType = 'year';
        if (vipType === 'lifetime') vipType = 'svip';

        return {
          id: p.id,
          title: p.title,
          subtitle: p.subtitle || attrs.subtitle || (benefits[0] || ''),
          benefits,
          vipType,
          gradient: `background: linear-gradient(180deg, ${gradientStart}, ${gradientEnd});`,
          iconGradient: `background: linear-gradient(180deg, ${gradientStart}, ${gradientEnd});`,
          checkColor: tagColor || gradientEnd
        };
      });

      // 根据 role 或 level 寻找匹配的套餐
      let currentPackage = null;
      
      if (this.data.role) {
        // 优先根据 role 匹配 (soulmate, guardian, companion, listener)
        currentPackage = allPackages.find(p => p.vipType === this.data.role);
      }
      
      if (!currentPackage && this.data.level) {
        // 如果 role 没匹配到，尝试根据 levelText 匹配 (SVIP, VIP)
        if (this.data.level === 'SVIP') {
          currentPackage = allPackages.find(p => p.vipType === 'svip');
        } else if (this.data.level === 'VIP') {
          currentPackage = allPackages.find(p => p.vipType === 'month' || p.vipType === 'year');
        }
      }

      // 如果还是没找到，默认取第一个（兜底）
      if (!currentPackage && allPackages.length > 0) {
        currentPackage = allPackages[0];
      }

      this.setData({
        currentPackage,
        loading: false
      });
    } catch (err) {
      console.error('Failed to load benefits:', err);
      this.setData({ loading: false });
    }
  },

  onBack() {
    wx.navigateBack({ delta: 1 });
  }
});