<template>
  <div class="register-container">
    <h2>Create Account</h2>
    <form @submit.prevent="handleRegister">
      <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" required />
      </div>
      
      <div class="form-group">
        <label for="nickname">Nickname (optional)</label>
        <input v-model="nickname" type="text" id="nickname" />
      </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 ? 'Registering...' : 'Register' }}
      </button>
    </form>
    
    <div class="login-link">
      <p>Already have an account? <NuxtLink to="/login">Log In</NuxtLink></p>
    </div>
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  layout: 'login', // Using the same simple layout as the login page
});

const api = useApi();

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

const handleRegister = async () => {
  if (!email.value || !password.value) {
    error.value = 'Email and Password are required.';
    return;
  }

  loading.value = true;
  error.value = null;

  try {
    await api('/auth/register', {
      method: 'POST',
      body: {
        email: email.value,
        password: password.value,
        nickname: nickname.value || undefined, // Send undefined if empty
      },
    });

    // On success, redirect to login page
    await navigateTo('/login');

  } catch (err: any) {
    console.error('Registration failed:', err);
    error.value = err.data?.message || 'An unexpected error occurred.';
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.register-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;
}

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

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