<!-- /pages/login.vue -->
<template>
  <div>
    <h1>Login or Register</h1>
    <form @submit.prevent="isRegistering ? handleRegister() : handleLogin()">
      <div>
        <label for="email">Email</label>
        <input type="email" id="email" v-model="email" required />
      </div>
      <div v-if="isRegistering">
        <label for="nickname">Nickname</label>
        <input type="text" id="nickname" v-model="nickname" required />
      </div>
      <div>
        <label for="password">Password</label>
        <input type="password" id="password" v-model="password" required />
      </div>
      <div v-if="error">{{ error }}</div>
      <button type="submit" :disabled="loading">
        {{ isRegistering ? 'Register' : 'Login' }}
      </button>
    </form>
    <button @click="isRegistering = !isRegistering">
      {{ isRegistering ? 'Switch to Login' : 'Switch to Register' }}
    </button>
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  layout: 'default', // Using the default layout
});

const { login, register, loading } = useAuth();

const isRegistering = ref(false);
const email = ref('');
const password = ref('');
const nickname = ref('');
const error = ref<string | null>(null);

const handleLogin = async () => {
  error.value = null;
  try {
    await login(email.value, password.value);
  } catch (e: any) {
    error.value = e.data?.message || 'Login failed.';
  }
};

const handleRegister = async () => {
  error.value = null;
  try {
    await register(email.value, password.value, nickname.value);
    // On successful registration, switch to the login view
    isRegistering.value = false;
    // You might want to auto-login or show a success message instead
  } catch (e: any) {
    error.value = e.data?.message || 'Registration failed.';
  }
};
</script>
