const app = getApp()

Page({
  data: {
    coupons: []
  },
  onLoad() {
    this.fetchCoupons();
  },
  fetchCoupons() {
    const { request } = require('../../utils/request')
    request({ url: '/coupons' })
      .then((data) => {
        const list = Array.isArray(data) ? data : (data && data.results) || []
        this.setData({ coupons: list })
      })
      .catch(() => {
        this.setData({
          coupons: [
            {
              id: 1,
              amount: '50',
              unit: '元',
              title: '新人见面礼',
              desc: '无门槛使用，适用于所有课程',
              expiry: '2023-12-31',
              status: 'available',
              color: 'from-blue-500 to-cyan-400',
              bgStart: 'from-blue-50',
              bgEnd: 'to-cyan-50',
              shadow: 'shadow-blue-100'
            },
            {
              id: 2,
              amount: '8.5',
              unit: '折',
              title: '编程课程专享',
              desc: '仅限编程开发类课程使用',
              expiry: '2023-11-30',
              status: 'available',
              color: 'from-violet-500 to-fuchsia-500',
              bgStart: 'from-violet-50',
              bgEnd: 'to-fuchsia-50',
              shadow: 'shadow-violet-100'
            },
            {
              id: 3,
              amount: '100',
              unit: '元',
              title: '高阶课程抵扣券',
              desc: '满 999 元可用',
              expiry: '2023-10-15',
              status: 'claimed',
              color: 'from-orange-400 to-rose-500',
              bgStart: 'from-orange-50',
              bgEnd: 'to-rose-50',
              shadow: 'shadow-orange-100'
            }
          ]
        })
      })
  },
  handleClaim(e) {
      const id = e.currentTarget.dataset.id;
      if (this.data.coupons.find(c => c.id === id).status === 'claimed') return;

      const updatedCoupons = this.data.coupons.map(c => 
        c.id === id ? { ...c, status: 'claimed' } : c
      );
      this.setData({ coupons: updatedCoupons });
      wx.showToast({
        title: '领取成功',
        icon: 'success'
      })
  }
})
