<template>
  <div
    v-if="isAuthPopupOpen"
    class="auth-popup__decorate"
  />
  <transition mode="out-in">
    <UiPopup
      v-if="currentStep === AuthSteps.Registration && isAuthPopupOpen"
      v-model="isAuthPopupOpen"
      transparent-backdrop
      :back="isBackShow"
      class="auth-popup"
      @back="goBack"
    >
      <template #title>{{  $t('auth.create_new') }}</template>
      <AuthRegister
        :additional-text="additionalText"
        @login="onLoginClick"
      />
    </UiPopup>
  </transition>

  <transition mode="out-in">
    <UiPopup
      v-if="currentStep === AuthSteps.Login && isAuthPopupOpen"
      v-model="isAuthPopupOpen"
      transparent-backdrop
      :back="isBackShow"
      class="auth-popup"
      @back="goBack"
    >
      <template #title>{{  $t('auth.welcome_back') }}</template>
      <AuthLogin
        @forgot="onRecoveryClick"
        @create="currentStep = AuthSteps.Registration"
      />
    </UiPopup>
  </transition>

  <transition mode="out-in">
    <UiPopup
      v-if="currentStep === AuthSteps.Recovery && isAuthPopupOpen"
      v-model="isAuthPopupOpen"
      transparent-backdrop
      :back="isBackShow"
      class="auth-popup"
      @back="goBack"
    >
      <template #title>{{  $t('auth.recovery_title')}}</template>
      <AuthRecovery @login="onLoginClick"/>
    </UiPopup>
  </transition>
</template>

<script setup lang="ts">
import { AuthSteps } from '../../runtime';

const { isAuthPopupOpen, currentStep, additionalText } = useAuthPopup();

const backShow = ref(false);

// Куда ведёт «назад» с каждого шага. Registration — начальный, назад с него нет.
const previousStep: Partial<Record<AuthSteps, AuthSteps>> = {
  [AuthSteps.Login]: AuthSteps.Registration,
  [AuthSteps.Recovery]: AuthSteps.Login,
};

function goBack(): void {
  const previous = previousStep[currentStep.value];

  if (previous) {
    currentStep.value = previous;
  }
}

function onLoginClick(): void {
  currentStep.value = AuthSteps.Login;
  backShow.value = true;
}

function onRecoveryClick(): void {
  currentStep.value = AuthSteps.Recovery;
  backShow.value = true;
}

const isBackShow = computed(() => {
  return currentStep.value !== AuthSteps.Registration && backShow.value;
});
</script>

<style lang="scss">
.auth-popup {
  max-width: 448px;
}

.auth-popup__decorate {
  position: fixed;
  inset: 0;
  z-index: $z-index-popup;
  backdrop-filter: blur($blur-sm);
  background-color: $popup-decorate-bg;
}

.auth-popup .ui-input__input::placeholder {
  @include font-base;
}
</style>
