<script setup lang="ts">
import { LogoutReason, useAuthStore } from '@/stores/auth-store'
import { useTemplateRef, ref, computed } from 'vue'
import ModalWrapper from './common/ModalWrapper.vue'
import AppButton from './common/AppButton.vue'

const timeoutModal = useTemplateRef('timeoutModal')
const secondsUntilLogout = ref(30)
const timeoutTimerId = ref<number | undefined>()
const timePhrase = computed(() => {
  if (secondsUntilLogout.value !== 1) {
    return secondsUntilLogout.value + ' seconds'
  }
  return secondsUntilLogout.value + ' second'
})

const authStore = useAuthStore()

function start() {
  if (timeoutModal.value?.isOpen()) return
  secondsUntilLogout.value = 30
  timeoutModal.value?.show()
  timeoutTimerId.value = window.setInterval(() => {
    secondsUntilLogout.value = secondsUntilLogout.value - 1
    if (secondsUntilLogout.value <= 0) {
      authStore.onUserLoggedOut(LogoutReason.INACTIVITY_TIMEOUT)
      window.clearInterval(timeoutTimerId.value)
    }
  }, 1000)
}

function dismissTimeout() {
  window.clearInterval(timeoutTimerId.value)
  timeoutModal.value?.close()
}

defineExpose({ start })
</script>
<template>
  <ModalWrapper ref="timeoutModal">
    <template v-slot:default>
      <p>
        You've been inactive for a while, so to ensure the safety of your personal information, you
        will be logged out in
        <strong>{{ timePhrase }}</strong>
        unless you click below to remain logged in.
      </p>
    </template>
    <template v-slot:buttons>
      <AppButton @click="dismissTimeout()">Stay Logged In</AppButton>
    </template>
  </ModalWrapper>
</template>
