<template>
  <div
    :class="{'_loading': loading}"
    class="auth-recovery"
  >

    <AuthIcon
      class="auth-recovery__icon"
      icon="envelope"
    />

    <p class="auth-recovery__text">{{ t('auth.recovery_text') }}</p>
    <UiInput
      v-model="form.email"
      :label="$t('email')"
      :placeholder="$t('email')"
      hide-label
      :error="error.email"
      type="email"
      inputmode="email"
      enterkeyhint="send"
      autocomplete="email"
      @update:error="(val: boolean) => error.email = val"
      @enter="submit"
    />

    <UiBtn
      :disabled="loading"
      class="auth-recovery__button"
      wide
      size="l"
      theme="primary"
      @click="submit"
    >{{ t('auth.get_recovery') }}
    </UiBtn>
    <button
      class="auth-recovery__login"
      type="button"
      @click="onLoginClick"
    >{{ t('auth.back_to_login') }}
    </button>
  </div>
</template>

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

const { initRecaptcha, getRecaptchaToken } = useRecaptcha();

const { t } = useI18n();

const form = ref({
  email: '',
  token: '',
} as IPasswordForm);

const error = ref({
  email: 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);
  }
});

async function submit() {
  resetSnackbar();
  error.value.email = false;

  if (!validateEmail(form.value.email)) {
    error.value.email = true;
    showError('error_email');
    return;
  }

  try {
    loading.value = true;
    form.value.token = await getRecaptchaToken('password_reset');
    await useUser(AuthorizationApiService).password(form.value);
    useAuthPopup().closeAuthPopup();
    show('Check your email');
  } catch (error) {
    setErrorState(error);
  } finally {
    loading.value = false;
  }
}
</script>

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

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

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

.auth-recovery__icon {
  margin: 0 auto;
}

.auth-recovery__button {
  margin-top: 8px;
}

.auth-recovery__text {
  @include font-sm;

  text-align: center;
  color: $auth-recovery-text;
}

.auth-recovery__login {
  @include font-sm;

  color: $auth-recovery-login;
  margin-top: 8px;
  padding-block: 8px;

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