<template>
  <div class="login-page">
    <!-- Fullscreen wallpaper slideshow -->
    <div class="wallpaper-bg" :style="{ backgroundImage: `url(${currentWallpaper})` }" />
    <div class="wallpaper-overlay" />

    <div class="login-center">
      <v-card elevation="0" rounded="xl" class="login-card pa-10" border>

        <!-- Error -->
        <v-alert v-if="error" type="error" density="compact" class="mb-4" closable @click:close="error = ''" rounded="lg" variant="tonal">
          {{ error }}
        </v-alert>

        <!-- Lockout -->
        <v-alert v-if="lockoutUntil" type="warning" density="compact" class="mb-4" rounded="lg" variant="tonal">
          账户已锁定，请 {{ remainingMinutes }} 分钟后重试
        </v-alert>

        <!-- Form -->
        <v-form @submit.prevent="doLogin">
          <v-text-field
            v-model="username"
            label="用户名"
            variant="outlined"
            density="comfortable"
            prepend-inner-icon="mdi-account-outline"
            :disabled="loading"
            class="mb-4"
            autocomplete="username"
            rounded="lg"
            hide-details="auto"
          />

          <v-text-field
            v-model="password"
            label="密码"
            variant="outlined"
            density="comfortable"
            prepend-inner-icon="mdi-lock-outline"
            :append-inner-icon="showPassword ? 'mdi-eye' : 'mdi-eye-off'"
            :type="showPassword ? 'text' : 'password'"
            @click:append-inner="showPassword = !showPassword"
            :disabled="loading"
            class="mb-4"
            autocomplete="current-password"
            rounded="lg"
            hide-details="auto"
          />

          <v-text-field
            v-if="needTotp"
            v-model="totpCode"
            label="TOTP 验证码"
            variant="outlined"
            density="comfortable"
            prepend-inner-icon="mdi-shield-key-outline"
            :disabled="loading"
            class="mb-4"
            autocomplete="one-time-code"
            rounded="lg"
            hide-details="auto"
          />

          <v-btn
            type="submit"
            color="primary"
            variant="flat"
            block
            size="large"
            :loading="loading"
            :disabled="!!lockoutUntil"
            rounded="lg"
            class="mt-2"
            height="48"
          >
            登录
          </v-btn>
        </v-form>

        <div v-if="failedAttempts > 0 && !lockoutUntil" class="text-center mt-4">
          <v-chip size="small" variant="tonal" color="warning" label>
            已失败 {{ failedAttempts }} 次
          </v-chip>
        </div>
      </v-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ApiError, TotpRequiredError, http } from '@/api'

const route = useRoute()
const router = useRouter()
const auth = useAuthStore()

const username = ref('')
const password = ref('')
const totpCode = ref('')
const showPassword = ref(false)
const loading = ref(false)
const error = ref('')
const needTotp = ref(false)
const failedAttempts = ref(0)
const lockoutUntil = ref<string | null>(null)

// ── Wallpaper slideshow ──
const wallpapers = ref<string[]>([])
const currentIndex = ref(0)
let rotateTimer: ReturnType<typeof setInterval> | null = null

const currentWallpaper = computed(() => {
  if (wallpapers.value.length === 0) return ''
  return wallpapers.value[currentIndex.value]
})

async function loadWallpapers() {
  try {
    const data = await http.get<{ urls: string[] }>('/settings/bing-wallpapers')
    if (data?.urls?.length) {
      wallpapers.value = data.urls
      // Random start position
      currentIndex.value = Math.floor(Math.random() * data.urls.length)
    }
  } catch { /* gradient fallback */ }
}

function startRotation() {
  if (rotateTimer) clearInterval(rotateTimer)
  if (wallpapers.value.length <= 1) return
  // Rotate every hour
  rotateTimer = setInterval(() => {
    currentIndex.value = (currentIndex.value + 1) % wallpapers.value.length
  }, 3600_000)
}

onMounted(async () => {
  await loadWallpapers()
  startRotation()
})

onUnmounted(() => {
  if (rotateTimer) clearInterval(rotateTimer)
  if (lockoutTimer) clearInterval(lockoutTimer)
})

const now = ref(Date.now())
let lockoutTimer: ReturnType<typeof setInterval> | null = null

const remainingMinutes = computed(() => {
  if (!lockoutUntil.value) return 0
  const diff = new Date(lockoutUntil.value).getTime() - now.value
  return Math.max(0, Math.ceil(diff / 60000))
})

watch(lockoutUntil, (val) => {
  if (lockoutTimer) { clearInterval(lockoutTimer); lockoutTimer = null }
  if (val) {
    lockoutTimer = setInterval(() => { now.value = Date.now() }, 30000)
  }
})

async function doLogin() {
  if (!username.value || !password.value) {
    error.value = '请输入用户名和密码'
    return
  }

  loading.value = true
  error.value = ''

  try {
    await auth.login(username.value, password.value, needTotp.value ? totpCode.value : undefined)
    const redirect = (route.query.redirect as string) || '/'
    router.push(redirect)
  } catch (e: any) {
    if (e instanceof TotpRequiredError) {
      needTotp.value = true
      error.value = e.message
    } else if (e instanceof ApiError) {
      if (e.status === 429) {
        lockoutUntil.value = new Date(Date.now() + 15 * 60 * 1000).toISOString()
        error.value = '登录尝试过多，账户已锁定 15 分钟'
      } else {
        failedAttempts.value++
        error.value = e.message
      }
    } else {
      error.value = '网络错误，请重试'
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-page {
  position: relative;
  width: 100%;
  min-height: 100vh;
  overflow: hidden;
}

/* Fullscreen wallpaper with fade */
.wallpaper-bg {
  position: fixed;
  inset: 0;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  transition: background-image 1.5s ease-in-out;
  z-index: 0;
}

.wallpaper-overlay {
  position: fixed;
  inset: 0;
  background: linear-gradient(135deg, rgba(0,0,0,0.45) 0%, rgba(0,0,0,0.2) 100%);
  z-index: 1;
}

.login-center {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 24px;
}

.login-card {
  backdrop-filter: blur(4px);
  background: rgba(var(--v-theme-surface), 0.92) !important;
  width: 100%;
  max-width: 420px;
}
</style>
