<template>
  <PopUpCard />

  <router-view></router-view>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import PopUpCard from './components/PopUpCard.vue';
import useLocalStorage from './mixins/useLocalStorage';
import client from './common/http';
import { IUser } from './types/auth.types';
import { LoadingState } from './types/common.types';
import { useAuthStore } from './stores/auth.store';
import { useSceneriesStore } from './stores/sceneries.store';

export default defineComponent({
  components: { PopUpCard },

  setup() {
    const { setupStorage } = useLocalStorage();

    setupStorage();

    return {
      authStore: useAuthStore(),
      sceneriesStore: useSceneriesStore(),

      tokenState: LoadingState.LOADING,
      LoadingState,
    };
  },

  methods: {
    async autoLogin() {
      try {
        this.tokenState = LoadingState.LOADING;
        const response = await client.post<IUser>('/auth/token');
        this.authStore.setUserData(response.data);
        this.tokenState = LoadingState.SUCCESS;
      } catch (error) {
        this.authStore.removeUserData();
        this.$router.push('/login');
        this.tokenState = LoadingState.ERROR;
      }
    },
  },

  mounted() {
    this.autoLogin();

    if (window.localStorage.getItem('notifyDiscord') !== null) {
      this.sceneriesStore.notifyDiscord = Boolean(Number(window.localStorage.getItem('notifyDiscord')));
    }
  },
});
</script>

<style lang="scss">
@use './styles/global';
</style>
