<template>
  <div class="login-container">
    <h2>Smurf Habits</h2>
    <form @submit.prevent="handleLogin">
      <div v-if="error" class="error-message">{{ error }}</div>
      <div class="form-group">
        <label for="email">Email</label>
        <input v-model="email" type="email" id="email" placeholder="papa@smurf.village" required />
      </div>
      <div class="form-group">
        <label for="password">Password</label>
        <input v-model="password" type="password" id="password" required />
      </div>
      <button type="submit" :disabled="loading">{{ loading ? 'Logging in...' : 'Login' }}</button>
    </form>
    <div class="register-link">
      <p>No account? <NuxtLink to="/register">Register</NuxtLink></p>
    </div>
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  layout: 'login',
});

const { login } = useAuth();
const email = ref('');
const password = ref('');
const error = ref<string | null>(null);
const loading = ref(false); // This is the local loading state

const handleLogin = async () => {
  loading.value = true;
  error.value = null;
  try {
    await login(email.value, password.value);
    await navigateTo('/'); // Explicitly navigate on success
  } catch (err: any) {
    console.error(err);
    error.value = err.data?.message || 'Login failed. Please check your credentials.';
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.login-container {
  width: 100%;
  max-width: 350px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  text-align: center;
}

h2 {
  color: #4a90e2;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
  text-align: left;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #4a90e2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

button:disabled {
  background-color: #a3bde3;
  cursor: not-allowed;
}

.register-link {
  margin-top: 20px;
}

.error-message {
  color: #bf616a;
  background-color: #fbe2e5;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 15px;
}
</style>
