<script setup lang="ts">
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useVuelidate } from '@vuelidate/core';
import { required, minLength, helpers } from '@vuelidate/validators';
import { useAuthStore } from '@/stores/auth.store';
import { useUiStore } from '@/stores/ui.store';
import AppInput from '@/components/common/AppInput.vue';
import AppButton from '@/components/common/AppButton.vue';

const router = useRouter();
const authStore = useAuthStore();
const uiStore = useUiStore();

const form = reactive({ phone: '', password: '', confirmPassword: '' });
const loading = ref(false);

const phoneRegex = helpers.regex(/^\+?[0-9\s\-()]{7,20}$/);

const rules = {
  phone: {
    required: helpers.withMessage('Введите номер телефона', required),
    format: helpers.withMessage('Введите корректный номер', phoneRegex),
  },
  password: {
    required: helpers.withMessage('Введите пароль', required),
    minLen: helpers.withMessage('Минимум 8 символов', minLength(8)),
  },
  confirmPassword: {
    required: helpers.withMessage('Подтвердите пароль', required),
    match: helpers.withMessage('Пароли не совпадают', () => form.password === form.confirmPassword),
  },
};

const v$ = useVuelidate(rules, form);

async function submit() {
  const valid = await v$.value.$validate();
  if (!valid) return;

  loading.value = true;
  try {
    await authStore.register({ phone: form.phone, password: form.password });
    router.replace('/setup');
  } catch (err: unknown) {
    const message = (err as { response?: { data?: { message?: string } } })
      ?.response?.data?.message ?? 'Ошибка регистрации. Попробуйте ещё раз.';
    uiStore.addToast(message, 'error');
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <div class="auth-page">
    <div class="auth-page__grain" aria-hidden="true" />

    <div class="auth-card">
      <div class="auth-card__wordmark">Daiting</div>
      <h1 class="auth-card__heading">Создать аккаунт</h1>
      <p class="auth-card__sub">Начните своё путешествие</p>

      <form class="auth-form" @submit.prevent="submit" novalidate>
        <AppInput
          v-model="form.phone"
          label="Телефон"
          placeholder="+7 999 000 00 00"
          type="tel"
          name="phone"
          autocomplete="tel"
          required
          :error="v$.phone.$errors.map(e => e.$message as string)"
          @blur="v$.phone.$touch()"
        />
        <AppInput
          v-model="form.password"
          label="Пароль"
          placeholder="Минимум 8 символов"
          type="password"
          name="password"
          autocomplete="new-password"
          required
          :error="v$.password.$errors.map(e => e.$message as string)"
          @blur="v$.password.$touch()"
        />
        <AppInput
          v-model="form.confirmPassword"
          label="Подтверждение пароля"
          placeholder="Повторите пароль"
          type="password"
          name="confirm-password"
          autocomplete="new-password"
          required
          :error="v$.confirmPassword.$errors.map(e => e.$message as string)"
          @blur="v$.confirmPassword.$touch()"
        />
        <AppButton type="submit" :loading="loading" full-width size="lg" class="auth-form__submit">
          Зарегистрироваться
        </AppButton>
      </form>

      <p class="auth-card__footer">
        Уже есть аккаунт?
        <RouterLink to="/login" class="auth-card__link">Войти</RouterLink>
      </p>
    </div>
  </div>
</template>

<style scoped lang="scss">
.auth-page {
  min-height: 100dvh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--color-base);
  padding: 24px;
  position: relative;
  overflow: hidden;

  &__grain {
    position: absolute;
    inset: 0;
    background-image: url('@/assets/grain.svg');
    background-repeat: repeat;
    opacity: 0.3;
    pointer-events: none;
  }

  &::after {
    content: '';
    position: absolute;
    inset: 0;
    background: radial-gradient(ellipse 80% 70% at 50% 0%, rgba(196, 92, 58, 0.06) 0%, transparent 70%);
    pointer-events: none;
  }
}

.auth-card {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 420px;
  animation: fade-up var(--transition-base) both;

  &__wordmark {
    font-family: var(--font-display);
    font-size: 1.5rem;
    color: var(--color-signal);
    margin-bottom: 32px;
    letter-spacing: 0.04em;
  }

  &__heading {
    font-family: var(--font-display);
    font-size: 2.25rem;
    color: var(--color-cream);
    margin: 0 0 8px;
  }

  &__sub {
    font-family: var(--font-mono);
    font-size: 0.875rem;
    color: var(--color-muted);
    margin: 0 0 40px;
  }

  &__footer {
    margin-top: 24px;
    font-family: var(--font-mono);
    font-size: 0.8125rem;
    color: var(--color-muted);
    text-align: center;
  }

  &__link {
    color: var(--color-cream);
    transition: color var(--transition-fast);
    &:hover { color: var(--color-signal); }
  }
}

.auth-form {
  display: flex;
  flex-direction: column;
  gap: 20px;

  &__submit { margin-top: 8px; }
}
</style>
