<template>
  <PageForm
    back-link="/login"
    :back-text="$t('to_main')"
    :title="$t('register_greeting')"
    :submit-text="$t('next')"
    :handler="onSubmit"
  >
    <UiInput
      id="email"
      class="mb-6"
      :label="$t('email')"
      rules="required|email"
    />

    <UiInput
      id="password"
      :label="$t('password')"
      native-type="password"
      rules="required|password"
      class="mb-6"
    />

    <UiInput
      id="repeat_password"
      :label="$t('repeat_password')"
      native-type="password"
      rules="required|confirmed:@password"
      class="mb-6"
    />

    <UiSelect
      id="wut"
      label="Как вы узнали о нас?"
      placeholder="Выбрать вариант"
      :options="[
        'Рекомендация',
        'Статьи на сторонних площадках',
        'Увидел рекламу',
      ]"
      class="w-100 mb-26"
    />

    <UiCheckbox id="agree" required>
      <I18nT keypath="sign_up_agreement.base" tag="span" scope="global">
        <UiButton type="link">
          {{ $t('sign_up_agreement.privacy_policy') }}
        </UiButton>
        <UiButton type="link">
          {{ $t('sign_up_agreement.user_agreement') }}
        </UiButton>
      </I18nT>
    </UiCheckbox>
  </PageForm>
</template>

<script setup>
definePageMeta({
  layout: 'auth',
  pageTransition: { name: 'fade', mode: 'out-in' },
  middleware: ['guest-only'],
})

const { register } = useAuth()

async function onSubmit(values) {
  try {
    await register(values.email, values.password)

    navigateTo({
      path: '/register/email-confirmation',
      query: {
        email: values.email,
      },
    })
  }
  catch (e) {
    if (e.status === 422) {
      setStaticError({
        status: e.status,
        message: 'You are already registered',
      })
    }
    else {
      setStaticError({
        status: e.status,
        message: 'Something went wrong',
      })
    }
  }
}
</script>
