<template>
  <div class="login-view">
    <div class="login-card">
      <div class="login-header">
        <div class="login-logo">Fischer AgentKit</div>
        <div class="login-subtitle">企业级 AI Agent 工作台</div>
      </div>

      <a-form
        layout="vertical"
        :model="form"
        @finish="handleSubmit"
        autocomplete="off"
      >
        <a-form-item
          label="用户名"
          name="username"
          :rules="[{ required: true, message: '请输入用户名' }]"
        >
          <a-input
            v-model:value="form.username"
            size="large"
            placeholder="请输入用户名"
            :disabled="authStore.isLoading"
            @pressEnter="handleSubmit"
          >
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item
          label="密码"
          name="password"
          :rules="[{ required: true, message: '请输入密码' }]"
        >
          <a-input-password
            v-model:value="form.password"
            size="large"
            placeholder="请输入密码"
            :disabled="authStore.isLoading"
            @pressEnter="handleSubmit"
          >
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>

        <a-alert
          v-if="authStore.error"
          :message="authStore.error"
          type="error"
          show-icon
          class="login-error"
          closable
          @close="authStore.error = null"
        />

        <a-form-item name="rememberMe" class="login-remember">
          <a-checkbox v-model:checked="form.rememberMe">
            记住我（30 天内免登录）
          </a-checkbox>
        </a-form-item>

        <a-button
          type="primary"
          html-type="submit"
          size="large"
          block
          :loading="authStore.isLoading"
          class="login-submit"
        >
          登录
        </a-button>
      </a-form>

      <div class="login-footer">
        <span class="login-hint">
          首次部署？请通过 <code>AGENTKIT_ADMIN_USERNAME</code> /
          <code>AGENTKIT_ADMIN_PASSWORD</code> 环境变量创建管理员账号。
        </span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import { useAuthStore } from '@/stores/auth'

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

const form = reactive({
  username: '',
  password: '',
  rememberMe: false,
})

/** Redirect target after successful login (defaults to /agent). */
const redirectTarget = (): string => {
  const redirect = route.query.redirect
  return typeof redirect === 'string' && redirect.startsWith('/')
    ? redirect
    : '/agent'
}

async function handleSubmit(): Promise<void> {
  if (!form.username || !form.password) return
  try {
    await authStore.login(form.username, form.password, form.rememberMe)
    router.replace(redirectTarget())
  } catch {
    /* error already in authStore.error */
  }
}

onMounted(async () => {
  // If a refresh token is already stored, run the cold-start probe
  // so the user is taken straight to the main app (F1) without
  // seeing the login page.
  if (authStore.startupState === 'pending') {
    await authStore.startupCheck()
    if (authStore.isAuthenticated) {
      router.replace(redirectTarget())
    }
  } else if (authStore.isAuthenticated) {
    router.replace(redirectTarget())
  }
})
</script>

<style scoped>
.login-view {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bg-secondary, #fbfbfa);
}

.login-card {
  width: 380px;
  padding: 40px 32px 32px;
  background: var(--bg-elevated, #ffffff);
  border: 1px solid var(--border-color, #ededec);
  border-radius: var(--radius-xl, 14px);
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.04), 0 1px 2px rgba(0, 0, 0, 0.02);
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.login-logo {
  font-size: 22px;
  font-weight: 700;
  color: var(--text-primary, #1a1a1a);
  letter-spacing: -0.01em;
}

.login-subtitle {
  margin-top: 6px;
  font-size: 13px;
  color: var(--text-tertiary, #6b6b6a);
}

.login-error {
  margin-bottom: 16px;
}

.login-submit {
  margin-top: 4px;
  font-weight: 600;
}

/* 显式绑定到 token — AntD ConfigProvider token 在 tauri 冷启动时序
   不稳定，这里兜底强制使用项目主色（#1a1a1a 近黑），避免蓝色兜底。 */
.login-submit.ant-btn-primary,
.login-submit.ant-btn-primary:hover,
.login-submit.ant-btn-primary:focus {
  background-color: var(--color-primary, #1a1a1a);
  border-color: var(--color-primary, #1a1a1a);
  color: var(--text-inverse, #ffffff);
}
.login-submit.ant-btn-primary:hover {
  background-color: var(--color-primary-hover, #2f2f2f);
  border-color: var(--color-primary-hover, #2f2f2f);
}

.login-remember {
  margin-bottom: 16px;
}

.login-footer {
  margin-top: 24px;
  text-align: center;
}

.login-hint {
  font-size: 12px;
  color: var(--text-quaternary, #9b9b9a);
  line-height: 1.6;
}

.login-hint code {
  padding: 1px 5px;
  background: var(--bg-tertiary, #f7f7f5);
  border-radius: 3px;
  font-size: 11px;
  color: var(--text-secondary, #4a4a4a);
}
</style>
