<script setup lang="ts">
import { computed, watch } from 'vue';

import { AuthenticationLoginExpiredModal } from '@easyflow/common-ui';
import { useWatermark } from '@easyflow/hooks';
import { LockScreen } from '@easyflow/layouts';
import { preferences } from '@easyflow/preferences';
import { useAccessStore, useUserStore } from '@easyflow/stores';

import { useAuthStore } from '#/store';
import LoginForm from '#/views/_core/authentication/login.vue';

const accessStore = useAccessStore();
const userStore = useUserStore();
const authStore = useAuthStore();
const { destroyWatermark, updateWatermark } = useWatermark();

const avatar = computed(
  () => userStore.userInfo?.avatar ?? preferences.app.defaultAvatar,
);

async function handleLogout() {
  await authStore.logout(false);
}

watch(
  () => ({
    enable: preferences.app.watermark,
    content: preferences.app.watermarkContent,
  }),
  async ({ enable, content }) => {
    if (enable) {
      await updateWatermark({
        content:
          content ||
          `${userStore.userInfo?.username} - ${userStore.userInfo?.realName}`,
      });
    } else {
      destroyWatermark();
    }
  },
  {
    immediate: true,
  },
);
</script>

<template>
  <div class="authenticated-standalone-layout">
    <slot></slot>
    <AuthenticationLoginExpiredModal
      v-model:open="accessStore.loginExpired"
      :avatar
    >
      <LoginForm />
    </AuthenticationLoginExpiredModal>
    <Transition v-if="preferences.widget.lockScreen" name="slide-up">
      <LockScreen
        v-if="accessStore.isLockScreen"
        :avatar
        @to-login="handleLogout"
      />
    </Transition>
  </div>
</template>

<style scoped>
.authenticated-standalone-layout {
  width: 100%;
  height: 100vh;
  min-height: 0;
  overflow: hidden;
  background-color: var(--el-bg-color);
}
</style>
