<template>
  <div class="auth-container">
    <div class="page-container auth-form">
      <h1>Регистрация</h1>
      <form @submit.prevent="handleRegister">
        <div class="form-group">
          <label for="nickname" class="form-label">Никнейм</label>
          <input type="text" id="nickname" v-model="nickname" class="form-control" required />
        </div>
        <div class="form-group">
          <label for="email" class="form-label">Email</label>
          <input type="email" id="email" v-model="email" class="form-control" required />
        </div>
        <div class="form-group">
          <label for="password" class="form-label">Пароль (минимум 8 символов)</label>
          <input type="password" id="password" v-model="password" class="form-control" required />
        </div>
        <div v-if="error" class="error-message">{{ error }}</div>
        <div v-if="successMessage" class="success-message">{{ successMessage }}</div>
        <button type="submit" :disabled="loading" class="btn btn-primary">
          {{ loading ? 'Регистрируем...' : 'Зарегистрироваться' }}
        </button>
      </form>
      <div class="switch-link">
        <p>
          Уже есть аккаунт?
          <NuxtLink to="/login">Войти</NuxtLink>
        </p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const api = useApi();
const nickname = ref('');
const email = ref('');
const password = ref('');
const error = ref(null);
const loading = ref(false);
const successMessage = ref('');

const handleRegister = async () => {
  loading.value = true;
  error.value = null;
  successMessage.value = '';
  try {
    await api('/auth/register', {
      method: 'POST',
      body: {
        nickname: nickname.value,
        email: email.value,
        password: password.value,
      },
    });
    successMessage.value = 'Регистрация прошла успешно! Пожалуйста, войдите в систему.';
    setTimeout(() => {
        navigateTo('/login');
    }, 2000);
  } catch (err) {
    error.value = err.data?.message || 'An error occurred during registration.';
  } finally {
    loading.value = false;
  }
};

definePageMeta({
  layout: 'login',
});
</script>

<style scoped>
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  width: 100%;
}
.auth-form {
  width: 100%;
  max-width: 420px;
}
.auth-form button {
  width: 100%;
}
.error-message {
  color: var(--danger-color);
  background-color: #fee2e2;
  padding: 1rem;
  border-radius: 0.375rem;
  margin-bottom: 1rem;
  text-align: center;
}
.success-message {
  color: #16a34a;
  background-color: #dcfce7;
  padding: 1rem;
  border-radius: 0.375rem;
  margin-bottom: 1rem;
  text-align: center;
}
.switch-link {
  margin-top: 20px;
  text-align: center;
}
</style>