<template>
  <div class="login-page">
    <div class="login-wrap">
      <div class="login-brand-icon">
        <AppLogo :size="24" />
      </div>
      <h1 class="page-title">{{ t('app.name') }}</h1>
      <p class="page-desc">{{ t('app.tagline') }}</p>

      <div class="login-card">
        <h3 class="app-card__title u-mb-6">{{ t('login.title') }}</h3>
        <el-form size="large" @submit.prevent="onLogin">
          <el-form-item>
            <el-input v-model="form.username" :placeholder="t('login.username')" :disabled="locked" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="form.password" type="password" :placeholder="t('login.password')" show-password :disabled="locked" />
          </el-form-item>
          <el-alert
            v-if="locked"
            type="warning"
            :closable="false"
            show-icon
            :title="lockMessage"
            class="u-mb-4"
          />
          <el-button type="primary" native-type="submit" :loading="loading" :disabled="locked" class="w-full">
            {{ t('login.submit') }}
          </el-button>
        </el-form>
        <p class="form-hint u-mt-4 text-center">{{ t('login.hint') }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onUnmounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import AppLogo from '@/components/AppLogo.vue'
import api from '@/api'

const { t } = useI18n()
const router = useRouter()
const loading = ref(false)
const locked = ref(false)
const lockSeconds = ref(0)
const form = reactive({ username: 'admin', password: 'admin' })
let lockTimer

const lockMessage = computed(() => {
  if (lockSeconds.value <= 0) return t('login.lockDefault')
  if (lockSeconds.value >= 60) {
    return t('login.lockMinutes', { n: Math.ceil(lockSeconds.value / 60) })
  }
  return t('login.lockSeconds', { n: lockSeconds.value })
})

function startLockCountdown(seconds) {
  clearInterval(lockTimer)
  lockSeconds.value = seconds
  locked.value = true
  lockTimer = setInterval(() => {
    lockSeconds.value -= 1
    if (lockSeconds.value <= 0) {
      locked.value = false
      clearInterval(lockTimer)
    }
  }, 1000)
}

async function onLogin() {
  if (locked.value) return
  loading.value = true
  try {
    const { data } = await api.post('/auth/login', form)
    localStorage.setItem('token', data.token)
    localStorage.setItem('user', JSON.stringify(data.user))
    ElMessage.success(t('message.loginSuccess'))
    router.push('/dashboard')
  } catch (e) {
    const status = e.response?.status
    const retryAfter = e.response?.data?.retry_after
    if (status === 429 && retryAfter > 0) {
      startLockCountdown(retryAfter)
      ElMessage.warning(e.response?.data?.error || t('message.loginRateLimit'))
    } else {
      ElMessage.error(e.response?.data?.error || t('message.loginFailed'))
    }
  } finally {
    loading.value = false
  }
}

onUnmounted(() => clearInterval(lockTimer))
</script>
