Page({
  data: {
    userInfo: null,
    weekStartDay: 0,
    ziHourSect: 'lateZiNextDay',
    solarTime: true,
    showBuddhist: false,
    highlightLunar: true,
    bookmarks: []
  },

  onLoad() {
    this.loadSettings();
    this.loadBookmarks();
  },

  onShow() {
    this.loadBookmarks();
  },

  loadSettings() {
    const settings = wx.getStorageSync('lunar-settings') || {};
    this.setData({
      weekStartDay: settings.weekStartDay || 0,
      ziHourSect: settings.ziHourSect || 'lateZiNextDay',
      solarTime: settings.solarTime !== false,
      showBuddhist: settings.showBuddhist === true,
      highlightLunar: settings.highlightLunar !== false
    });
  },

  saveSettings() {
    const { weekStartDay, ziHourSect, solarTime, showBuddhist, highlightLunar } = this.data;
    wx.setStorageSync('lunar-settings', { weekStartDay, ziHourSect, solarTime, showBuddhist, highlightLunar });
  },

  loadBookmarks() {
    const bookmarks = wx.getStorageSync('lunar-bookmarks') || [];
    this.setData({ bookmarks });
  },

  setWeekStart(e) {
    this.setData({ weekStartDay: Number(e.currentTarget.dataset.v) });
    this.saveSettings();
  },

  setZiSect(e) {
    this.setData({ ziHourSect: e.currentTarget.dataset.v });
    this.saveSettings();
  },

  onSolarTimeChange(e) {
    this.setData({ solarTime: e.detail.value });
    this.saveSettings();
  },

  onBuddhistChange(e) {
    this.setData({ showBuddhist: e.detail.value });
    this.saveSettings();
  },

  onHighlightLunarChange(e) {
    this.setData({ highlightLunar: e.detail.value });
    this.saveSettings();
  },

  removeBookmark(e) {
    const date = e.currentTarget.dataset.date;
    let bookmarks = this.data.bookmarks.filter(b => b.date !== date);
    wx.setStorageSync('lunar-bookmarks', bookmarks);
    this.setData({ bookmarks });
    wx.showToast({ title: '已删除', icon: 'success' });
  },

  navTo(e) {
    wx.navigateTo({ url: e.currentTarget.dataset.url });
  },

  login() {
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        this.setData({ userInfo: res.userInfo });
        wx.setStorageSync('lunar-user-info', res.userInfo);
        wx.showToast({ title: '登录成功', icon: 'success' });
      },
      fail: () => {
        wx.showToast({ title: '登录失败', icon: 'none' });
      }
    });
  }
});
