<template>
  <div class="login-page">
    <div class="header">
      <img src="@/assets/logo-placeholder.png" alt="Logo" class="logo" v-if="false" />
      <h2 class="title">校园活动管理平台</h2>
      <p class="subtitle">欢迎登录</p>
    </div>

    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="请输入用户名"
          :rules="[{ required: true, message: '请输入用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="请输入密码"
          :rules="[{ required: true, message: '请输入密码' }]"
        />
      </van-cell-group>

      <div style="margin: 32px 16px;">
        <van-button round block type="primary" native-type="submit" :loading="loading">
          登录
        </van-button>
        <div class="actions">
          <router-link to="/register" class="link">注册账号</router-link>
        </div>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { login } from '@/services/auth';
import { showToast } from 'vant';

const router = useRouter();
const authStore = useAuthStore();

const username = ref('');
const password = ref('');
const loading = ref(false);

const onSubmit = async () => {
  loading.value = true;
  try {
    const res = await login({
      username: username.value,
      password: password.value,
    });
    
    // Save token and user info
    authStore.setToken(res.accessToken);
    authStore.setUser(res.userInfo);
    
    showToast('登录成功');
    router.replace('/home');
  } catch (error) {
    // Error is handled by interceptor or catch block
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped lang="scss">
.login-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background-color: #f7f8fa;

  .header {
    text-align: center;
    margin-bottom: 40px;

    .title {
      font-size: 28px;
      color: #333;
      margin: 10px 0;
    }
    .subtitle {
      font-size: 14px;
      color: #999;
    }
  }

  .actions {
    margin-top: 16px;
    text-align: center;
    
    .link {
      color: var(--van-primary-color);
      font-size: 14px;
      text-decoration: none;
    }
  }
}
</style>
