<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useAuthStore } from '@/stores/auth'
import { useToast } from '@/composables/useToast'
import { useIntervalFn } from '@vueuse/core'
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 authStore = useAuthStore()
const toast = useToast()
const { loading } = storeToRefs(authStore)

const email = ref('')
const code = ref('')
const emailError = ref('')
const codeError = ref('')
const countdown = ref(0)

const canSend = computed(() => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.value))
const canProceed = computed(() => canSend.value && code.value.trim().length > 0)

const { pause, resume } = useIntervalFn(() => {
  if (countdown.value > 0) countdown.value--
  else pause()
}, 1000, { immediate: false })

async function sendCode() {
  emailError.value = ''
  if (!email.value) { emailError.value = t('error.emailRequired'); return }
  if (!canSend.value) { emailError.value = t('error.emailInvalid'); return }
  authStore.clearError()
  await authStore.sendCode(email.value, 'forgot-password')
  if (!authStore.error) {
    countdown.value = 60
    resume()
    toast.info(t('auth.codeSentToast'))
  } else {
    toast.error(authStore.error)
  }
}

async function handleNext() {
  emailError.value = ''
  codeError.value = ''
  if (!email.value) { emailError.value = t('error.emailRequired'); return }
  if (!canSend.value) { emailError.value = t('error.emailInvalid'); return }
  if (!code.value.trim()) { codeError.value = t('error.codeRequired'); return }
  authStore.clearError()
  authStore.forgotPassword(email.value, code.value.trim())
  router.push('/register/password')
}

// 从「创建密码」页返回时恢复已填邮箱，验证码需重新填写
onMounted(() => {
  if (authStore.resetMode && authStore.resetEmail) {
    email.value = authStore.resetEmail
  }
})
</script>

<template>
  <AuthLayout>
    <h1 class="auth-title">{{ t('auth.forgotPasswordTitle') }}</h1>

    <div class="form">
      <AppInput
        v-model="email"
        :label="t('auth.emailLabel')"
        :placeholder="t('auth.emailRegisteredPlaceholder')"
        :error="emailError"
        @keyup.enter="handleNext"
      />

      <AppInput
        v-model="code"
        :label="t('auth.emailVerifyLabel')"
        :placeholder="t('auth.codePlaceholder')"
        :error="codeError"
        suffix
        @keyup.enter="handleNext"
      >
        <template #suffix>
          <button
            class="send-btn"
            :disabled="loading || countdown > 0 || !canSend"
            @click="sendCode"
          >
            <span v-if="countdown > 0">{{ countdown }}s</span>
            <span v-else>{{ t('auth.sendCode') }}</span>
          </button>
        </template>
      </AppInput>
    </div>

    <AppButton pill block size="lg" :loading="loading" :disabled="!canProceed" class="submit-btn" @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; }

.send-btn {
  height: 36px;
  padding: 0 12px;
  font-size: 12px;
  font-weight: 600;
  color: var(--color-primary);
  border: 1px solid rgba(240, 185, 11, 0.35);
  border-radius: 6px;
  white-space: nowrap;
  transition: background 0.2s, opacity 0.2s;
  margin-right: 6px;
}
.send-btn:not(:disabled):hover { background: rgba(240, 185, 11, 0.1); }
.send-btn:disabled { opacity: 0.5; cursor: not-allowed; }
</style>
