<template>
  <ClientOnly>
    <div
      :class="{'_loading': loading}"
      class="auth-register"
    >
      <AuthIcon class="auth-register__icon" />
      <p
        v-if="additionalText"
        class="auth-register__text"
      >{{ t(additionalText) }}
      </p>
      <UiInput
        v-model="form.email"
        :placeholder="t('email')"
        :label="t('email')"
        hide-label
        :error="error.email"
        type="email"
        inputmode="email"
        enterkeyhint="next"
        autocomplete="email"
        @update:error="(val: boolean) => error.email = val"
        @enter="usernameRef?.focus()"
      />
      <UiInput
        ref="usernameRef"
        v-model="form.username"
        :label="t('auth.username')"
        :placeholder="t('auth.username')"
        hide-label
        :error="error.username"
        name="login-name"
        enterkeyhint="next"
        @update:error="(val: boolean) => error.username = val"
        @enter="passwordRef?.focus()"
      />
      <UiInput
        ref="passwordRef"
        v-model="form.password_hash"
        :label="t('auth.password')"
        :placeholder="t('auth.password')"
        hide-label
        :error="error.password_hash"
        type="password"
        enterkeyhint="send"
        autocomplete="new-password"
        @update:error="(val: boolean) => error.password_hash = val"
        @enter="submit"
      />

      <div class="auth-register__buttons">
        <UiBtn
          :disabled="loading"
          wide
          size="l"
          theme="primary"
          @click="submit"
        >{{ t('auth.sign_up') }}
        </UiBtn>
        <p class="auth-register__login">
          {{ t('login_text') }}
          <button
            class="auth-register__login-button"
            type="button"
            @click="onLoginClick"
          >
            {{ t('auth.log_in') }}
          </button>
        </p>
      </div>

      <p class="auth-register__agreement">{{ t('auth.agree_begin') }}
        <NuxtLink
          :to="generateLink('/terms')"
          class="auth-register__agreement-link"
          target="_blank"
        >{{ t('auth.agree_terms') }}
        </NuxtLink>
        {{ t('auth.agree_and') }}
        <NuxtLink
          :to="generateLink('/policy')"
          class="auth-register__agreement-link"
          target="_blank"
        >{{ t('auth.agree_policy') }}
        </NuxtLink>
      </p>
    </div>
  </ClientOnly>
</template>

<script setup lang="ts">
import type { IRegistrateForm } from '../../types';
import { validateEmail, validatePassword, validateUsername } from '../../runtime';
import { AuthorizationApiService } from '../../services/api/authorization.service';

const { initRecaptcha, getRecaptchaToken } = useRecaptcha();

defineProps<{
  additionalText?: string;
}>();

const { t } = useI18n();
const { generateLink } = useGenerateLink();

const usernameRef = ref();
const passwordRef = ref();

const form = ref({
  username: '',
  email: '',
  password_hash: '',
  token: '',
} as IRegistrateForm);

const error = ref({
  username: false,
  email: false,
  password_hash: false,
});

const emit = defineEmits<{
  (eventName: 'login'): void
}>();

function onLoginClick() {
  emit('login');
}

const loading = ref(false);

const { setErrorState, showError, show, resetSnackbar } = useSnackbar();
// Загружаем reCAPTCHA при открытии формы (onMounted) — даёт Google время собрать данные о поведении
onMounted(async () => {
  try {
    await initRecaptcha();
    console.log('reCAPTCHA готов для этой формы');
  } catch (err) {
    console.error('Ошибка инициализации reCAPTCHA:', err);
  }
});

function validateForm(): boolean {
  const { username, email, password_hash } = form.value;

  const errors = {
    username: !validateUsername(username),
    email: !validateEmail(email),
    password_hash: !validatePassword(password_hash),
  };

  if (!validateEmail(email)) showError('error_email');
  if (!validatePassword(password_hash)) showError('error_password');
  if (!validateUsername(username)) showError('error_username');

  error.value = errors;

  return !Object.values(errors).some(Boolean);
}

async function submit() {
  resetSnackbar();
  if (!validateForm()) return;

  try {
    loading.value = true;

    // Уникальное действие для каждой формы
    // здесь 'register', в других формах — 'password_reset' или 'contact_form'
    form.value.token = await getRecaptchaToken('register');

    await useUser(AuthorizationApiService).register(form.value);

    useAuthPopup().closeAuthPopup();
    show('Registration success');
  } catch (err) {
    setErrorState(err);
    console.error('Ошибка reCAPTCHA или регистрации:', err);
  } finally {
    loading.value = false;
  }
}
</script>

<style lang="scss">
.auth-register {
  display: grid;
  row-gap: 16px;
  align-items: start;

  @include from-br(sm) {
    row-gap: 8px;
  }
}

.auth-register._loading {
  @include from-br(sm) {
    cursor: wait;
  }
}

.auth-register__icon {
  margin: 0 auto;
}

.auth-register__buttons {
  display: grid;
  row-gap: 8px;
  padding-top: 24px;
  border-top: 1px solid $auth-register-border;
}

.auth-register__agreement {
  @include font-xs;

  font-weight: 400;
  color: $auth-register-agreement;
  text-align: center;
}

.auth-register__agreement-link {
  color: $auth-register-link;

  @include hover(color) {
    color: $auth-register-link--hover;
  }
}

.auth-register__text {
  text-align: center;
}

.auth-register .ui-input:nth-last-child(1 of .ui-input) {
  padding-bottom: 16px;
}

.auth-register__login {
  @include font-sm;

  text-align: center;
  color: $auth-register-login;
}

.auth-register__login-button {
  color: $auth-register-link;

  @include hover(color) {
    color: $auth-register-link--hover;
  }
}
</style>
