<script setup>
import axios from 'axios'
import { ref } from 'vue'
import { useRouter } from 'vue-router';

const username = ref('')
const password = ref('')
const error = ref('')
const router = useRouter()

async function login() {
  error.value = ''

  try {
    const response = await axios.post('/api/v1/auth/login', {
      username: username.value,
      password: password.value,
    }, {
      headers: {
        'Content-Type': 'application/json',
      },
    });

    if (response.status == 200) {
      localStorage.setItem("user-token", response.headers.token)
      localStorage.setItem("user-id", response.headers.user_id)
      router.push({ name: 'feeds' })
    }
  } catch (err) {
    console.error('Login failed:', err)
    error.value = 'Login failed. Please check your username and password.'
  }
}
</script>

<template>
  <div class="login-page">
    <h1>Login</h1>
    <form @submit.prevent="login">
      <div class="form-group">
        <label for="username">Username/Email:</label>
        <input v-model="username" type="text" id="username" name="username" required />
      </div>
      <div class="form-group">
        <label for="password">Password:</label>
        <input v-model="password" type="password" id="password" name="password" required />
      </div>
      <p v-if="error" class="login-error">{{ error }}</p>
      <button type="submit">Login</button>
    </form>
  </div>
</template>

<style scoped>
.login-page {
  max-width: 420px;
  margin: 2rem auto;
  padding: 0 1rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  margin-bottom: 1rem;
}

.form-group input {
  min-height: 44px;
  padding: 0.5rem;
  font-size: 1rem;
}

.login-page button {
  min-height: 44px;
  padding: 0.5rem 1.5rem;
  font-size: 1rem;
  cursor: pointer;
}

.login-error {
  color: #c0392b;
}
</style>
