const birthProfile = require('../../utils/birth-profile.js');

Page({
  data: {
    loggedIn: false,
    profiles: [],
    activeProfileId: '',
    maxFree: birthProfile.MAX_PROFILES,
    canAdd: true,
    showAddForm: false,
    formName: '',
    formGender: 'male',
    formDate: '1990-01-01',
    formTime: '12:00'
  },

  onShow() {
    this.setData({ loggedIn: birthProfile.isLoggedIn() });
    this.loadProfiles();
  },

  loadProfiles() {
    const render = () => {
      const profiles = birthProfile.getProfiles();
      const active = birthProfile.getActiveProfile();
      this.setData({
        profiles,
        activeProfileId: active ? active.id : '',
        canAdd: profiles.length < this.data.maxFree
      });
    };
    // 已登录时先从服务端同步，失败静默回退本地
    if (birthProfile.isLoggedIn()) {
      birthProfile.syncFromServer().then(render).catch(render);
    } else {
      render();
    }
  },

  toggleAddForm() {
    if (!this.data.showAddForm && !this.data.canAdd) {
      wx.showToast({ title: `最多可免费绑定 ${this.data.maxFree} 个生辰`, icon: 'none' });
      return;
    }
    this.setData({ showAddForm: !this.data.showAddForm });
  },

  onFormName(e) {
    this.setData({ formName: e.detail.value });
  },

  setFormGender(e) {
    this.setData({ formGender: e.currentTarget.dataset.g });
  },

  onFormDate(e) {
    this.setData({ formDate: e.detail.value });
  },

  onFormTime(e) {
    this.setData({ formTime: e.detail.value });
  },

  submitProfile() {
    const { formName, formGender, formDate, formTime } = this.data;
    if (!formDate || !formTime) {
      wx.showToast({ title: '请选择出生日期和时间', icon: 'none' });
      return;
    }
    const result = birthProfile.addProfile({
      name: formName.trim() || '未命名',
      gender: formGender,
      birthday: formDate,
      birthTime: formTime
    });
    if (!result.ok) {
      wx.showToast({ title: result.msg, icon: 'none' });
      return;
    }
    // 已登录时推送到服务端（静默失败，不影响本地）
    birthProfile.pushProfileToServer(result.profile);
    this.setData({ showAddForm: false, formName: '' });
    wx.showToast({ title: '绑定成功', icon: 'success' });
    this.loadProfiles();
  },

  removeProfile(e) {
    const id = e.currentTarget.dataset.id;
    const profile = this.data.profiles.find(p => p.id === id);
    if (!profile) return;
    wx.showModal({
      title: '删除生辰',
      content: `确定删除「${profile.name}」的生辰信息吗？`,
      success: (res) => {
        if (!res.confirm) return;
        birthProfile.removeProfile(id);
        birthProfile.removeProfileFromServer(profile);
        wx.showToast({ title: '已删除', icon: 'success' });
        this.loadProfiles();
      }
    });
  },

  // 未登录时引导回个人中心登录
  goLogin() {
    wx.navigateBack();
  }
});
