<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, codeSentAt } = storeToRefs(authStore)

if (!authStore.pendingEmail) {
  router.replace('/register')
}

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

const canProceed = computed(() => code.value.trim().length > 0)

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

async function sendCode() {
  authStore.clearError()
  await authStore.sendCode(authStore.pendingEmail, 'register')
  if (!authStore.error) {
    countdown.value = 60
    resume()
  } else {
    toast.error(authStore.error)
  }
}

function handleNext() {
  codeError.value = ''
  if (!canProceed.value) { codeError.value = t('error.codeRequired'); return }
  authStore.verify(code.value.trim())
  router.push('/register/password')
}

onMounted(() => {
  if (Date.now() - codeSentAt.value < 5000) {
    countdown.value = Math.ceil((60_000 - (Date.now() - codeSentAt.value)) / 1000)
    if (countdown.value > 0) resume()
  }
})
</script>

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

    <div class="form">
      <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"
            @click="sendCode"
          >
            <span v-if="countdown > 0">{{ countdown }}s</span>
            <span v-else>{{ t('auth.sendBtn') }}</span>
          </button>
        </template>
      </AppInput>
    </div>

    <AppButton pill block size="lg" :loading="loading" :disabled="!canProceed" class="submit-btn" @click="handleNext">{{ t('common.submit') }}</AppButton>
    <p class="foot-tip">{{ t('auth.hasAccount') }}<RouterLink to="/register" class="link">{{ t('auth.registerNow') }}</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 14px;
  font-size: 13px;
  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>
