<template>
  <div class="login-page">
    <div class="login-wrap">
      <div class="login-brand-icon">
        <BrandIcon :size="24" />
      </div>
      <h1 class="page-title">{{ t('common.brand') }}</h1>
      <p class="page-desc">{{ t('login.subtitle') }}</p>
      <div class="login-card">
        <h3 class="app-card__title u-mb-6">{{ t('login.title') }}</h3>
        <el-form size="large" @submit.prevent="submit">
          <el-form-item :label="t('login.username')">
            <el-input v-model="username" placeholder="admin" />
          </el-form-item>
          <el-form-item :label="t('common.password')">
            <el-input v-model="password" type="password" show-password :placeholder="t('login.passwordPlaceholder')" />
          </el-form-item>
          <el-button type="primary" native-type="submit" :loading="loading" class="w-full">
            {{ t('login.submit') }}
          </el-button>
        </el-form>
        <p class="form-hint u-mt-4 text-center">{{ t('login.footer') }}</p>
      </div>
      <div class="u-mt-4">
        <LocaleSwitcher />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import api from '@/api/client'
import BrandIcon from '@/components/BrandIcon.vue'
import LocaleSwitcher from '@/components/LocaleSwitcher.vue'

const router = useRouter()
const { t } = useI18n()
const username = ref('admin')
const password = ref('admin123')
const loading = ref(false)

async function submit() {
  loading.value = true
  try {
    await api.post('/login', { username: username.value, password: password.value })
    ElMessage.success(t('login.success'))
    router.push('/dashboard')
  } catch (e: any) {
    if (e.response?.status === 429) {
      const sec = e.response?.data?.retry_after_sec
      ElMessage.error(sec ? t('login.rateLimitedSec', { sec }) : t('login.rateLimited'))
    } else if (e.response?.status === 403) {
      ElMessage.error(t('login.ipBlocked'))
    } else {
      ElMessage.error(t('login.failed'))
    }
  } finally {
    loading.value = false
  }
}
</script>
