<template>
  <div class="login-wrap">
    <div class="login-card">
      <div class="brand">
        <div class="brand-logo">📡</div>
        <h1>WebRTC 信令服务器</h1>
        <p>后台管理系统</p>
      </div>
      <el-form @submit.prevent="onSubmit">
        <el-form-item>
          <el-input
            v-model="token"
            size="large"
            placeholder="请输入管理令牌 (X-Admin-Token)"
            :prefix-icon="'Key'"
            @keyup.enter="onSubmit"
          />
        </el-form-item>
        <el-button
          type="primary"
          size="large"
          class="login-btn"
          :loading="loading"
          @click="onSubmit"
        >
          登 录
        </el-button>
        <p class="hint">
          默认令牌与服务器 <code>application.yml</code> 中的
          <code>admin.token</code> 一致（当前默认：<code>webrtc-admin-token</code>）。
        </p>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus';

const route = useRoute();
const router = useRouter();
const user = useUserStore();
const token = ref(import.meta.env.VITE_ADMIN_TOKEN || 'webrtc-admin-token');
const loading = ref(false);

async function onSubmit() {
  if (!token.value.trim()) {
    ElMessage.warning('请输入管理令牌');
    return;
  }
  loading.value = true;
  try {
    await user.login(token.value.trim());
    ElMessage.success('登录成功');
    const redirect = (route.query.redirect as string) || '/dashboard';
    router.replace(redirect);
  } catch (e: unknown) {
    const err = e as { response?: { data?: { message?: string } } };
    ElMessage.error(err?.response?.data?.message || '令牌校验失败');
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped>
.login-wrap {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #1b1f2d 0%, #2b3a67 100%);
}
.login-card {
  width: 380px;
  background: #fff;
  border-radius: 16px;
  padding: 36px 32px;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.25);
}
.brand {
  text-align: center;
  margin-bottom: 24px;
}
.brand-logo {
  font-size: 40px;
}
.brand h1 {
  font-size: 20px;
  margin: 10px 0 4px;
  color: #1f2937;
}
.brand p {
  margin: 0;
  color: #909399;
  font-size: 13px;
}
.login-btn {
  width: 100%;
}
.hint {
  margin-top: 16px;
  font-size: 12px;
  color: #909399;
  line-height: 1.6;
}
.hint code {
  background: #f0f2f5;
  padding: 1px 5px;
  border-radius: 4px;
  color: #3b82f6;
}
</style>
