<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useAuthStore } from '@/stores/auth'
import { useI18n } from 'vue-i18n'
import AuthLayout from '@/components/auth/AuthLayout.vue'
import AppInput from '@/components/common/AppInput.vue'
import AppButton from '@/components/common/AppButton.vue'

const { t } = useI18n()
const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const { loading } = storeToRefs(authStore)
const email = ref('')
const inviteCode = ref('')
const emailError = ref('')

onMounted(() => {
  const code = route.query.code
  if (code && typeof code === 'string') {
    inviteCode.value = code
  }
})

function validate() {
  emailError.value = ''
  if (!email.value) { emailError.value = t('error.emailRequired'); return false }
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.value)) { emailError.value = t('error.emailInvalid'); return false }
  return true
}

async function handleNext() {
  if (!validate()) {
    return
  }
  authStore.clearError()
  const status = await authStore.checkAccountForRegister(email.value)
  if (status === 'error') {
    emailError.value = authStore.error || t('error.networkError')
    return
  }
  if (status === 'registered') {
    emailError.value = t('error.emailAlreadyRegistered')
    return
  }
  authStore.register(email.value, inviteCode.value || undefined)
  router.push('/register/verify')
}
</script>

<template>
  <AuthLayout>
    <h1 class="auth-title">{{ t('auth.registerTitle') }}</h1>
    <div class="form">
      <AppInput v-model="email" :label="t('auth.emailRegister')" :placeholder="t('auth.emailPlaceholder')" :error="emailError" @keyup.enter="handleNext" />
      <AppInput v-model="inviteCode" :label="t('auth.inviteCodeLabel')" :placeholder="t('auth.inviteCodePlaceholder')" @keyup.enter="handleNext" />
    </div>
    <AppButton pill block size="lg" class="submit-btn" :loading="loading" @click="handleNext">{{ t('common.next') }}</AppButton>
    <p class="foot-tip">{{ t('auth.hasAccount') }}<RouterLink to="/login" class="link">{{ t('auth.loginNow') }}</RouterLink></p>
  </AuthLayout>
</template>

<style scoped>
.auth-title { font-size: 30px; font-weight: 700; color: #fff; margin-bottom: 32px; }
.form { display: flex; flex-direction: column; gap: 20px; }
.submit-btn { margin-top: 32px; }
.foot-tip { margin-top: 20px; text-align: center; font-size: 13px; color: #666; }
.link { color: var(--color-primary); }
.link:hover { opacity: 0.8; }
</style>
