<template>
  <view class="register">
    <view class="form">
      <input class="input" v-model="phone" placeholder="手机号（选填）" type="text" />
      <input class="input" v-model="email" placeholder="邮箱（选填）" type="text" />
      <input class="input" v-model="nickname" placeholder="昵称" type="text" />
      <input class="input" v-model="password" placeholder="密码" type="password" password />
      <button class="btn-primary" @tap="handleRegister" :loading="loading">注册</button>
      <view class="links">
        <text class="link" @tap="goLogin">已有账号？去登录</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useUserStore } from '../../store/user'

const userStore = useUserStore()
const phone = ref('')
const email = ref('')
const nickname = ref('')
const password = ref('')
const loading = ref(false)

async function handleRegister() {
  if (!password.value || (!phone.value && !email.value)) {
    uni.showToast({ title: '请填写手机号/邮箱和密码', icon: 'none' })
    return
  }
  loading.value = true
  try {
    await userStore.register({
      phone: phone.value || undefined,
      email: email.value || undefined,
      password: password.value,
      nickname: nickname.value || undefined,
    })
    uni.showToast({ title: '注册成功', icon: 'success' })
    uni.switchTab({ url: '/pages/index/index' })
  } catch (e: any) {
    uni.showToast({ title: e.message || '注册失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

const goLogin = () => uni.navigateTo({ url: '/pages/login/index' })
</script>

<style scoped>
.register { padding: 100rpx 40rpx; }
.input {
  background: var(--card); border-radius: 12rpx; padding: 24rpx 30rpx; font-size: 28rpx;
  margin-bottom: 24rpx; border: 1rpx solid var(--border);
}
.btn-primary {
  background: var(--brand); color: var(--card); border-radius: 12rpx; padding: 24rpx;
  font-size: 30rpx; text-align: center; margin-top: 30rpx; border: none;
}
.links { text-align: center; margin-top: 40rpx; }
.link { font-size: 26rpx; color: var(--brand); }
</style>
