<script setup>
  import { useTheme } from 'vuetify'
  import ScrollToTop from '@core/components/ScrollToTop.vue'
  import initCore from '@core/initCore'
  import {
    initConfigStore,
    useConfigStore,
  } from '@core/stores/config'
  import { hexToRgb } from '@layouts/utils'
  import { useAlert } from '@/composables/useAlert'

  const { alert, setAlert } = useAlert()
  const { global } = useTheme()

  // ℹ️ Sync current theme with initial loader theme
  initCore()
  initConfigStore()

  const configStore = useConfigStore()

  const { width: windowWidth } = useWindowSize();
  const isMobile = ref(false)
  isMobile.value = windowWidth.value < 768

  const versionDev = import.meta.env.VITE_VAPP

  const atualVersionCookie = useCookie('vApp').value
  const cookieOptions = { maxAge: 70 * 24 * 60 * 60 }
  if (!atualVersionCookie) {
    useCookie('vApp', versionDev, cookieOptions)
    useCookie('vApp', cookieOptions).value = versionDev
  }

  const clearCache = async () => {
    if ('caches' in window) {
      caches.keys().then(cacheNames => {
        cacheNames.forEach(cacheName => {
          caches.delete(cacheName)
        })
      })
    }

    // Limpar Caches
    if ('caches' in window) {
      const cacheNames = await caches.keys()

      await Promise.all(cacheNames.map(cacheName => caches.delete(cacheName)))
    }

    if (window.indexedDB && indexedDB.databases) {
      indexedDB.databases().then(databases => {
        databases.forEach(db => {
          indexedDB.deleteDatabase(db.name)
        })
      })
    }

    window.localStorage.clear()
    window.location.reload()
  }

  if (atualVersionCookie && atualVersionCookie !== versionDev) {
    useCookie('vApp', cookieOptions).value = versionDev
    clearCache()
  }
</script>

<template>
  <VLocaleProvider :rtl="configStore.isAppRTL">
    <!-- ℹ️ This is required to set the background color of active nav link based on currently active global theme's primary -->
    <VApp :style="`--v-global-theme-primary: ${hexToRgb('#F27405')}`">
      <!-- Alert -->
      <Transition name="slide-right">
        <VAlert v-if="alert.show" :color="alert.color" :icon="alert.icon"
          :style="`position: fixed; top: 80px; right: ${isMobile ? '0px' : '15px'}; z-index: 214748364799; ${isMobile ? 'width: 93%; padding-right: 20px;' : ''}`"
          :text="alert.message" />
      </Transition>

      <RouterView />
      <!--<ScrollToTop />-->
    </VApp>
  </VLocaleProvider>
</template>

<style>

  .slide-right-enter-active,
  .slide-right-leave-active {
    transition: transform 0.3s ease;
  }

  .slide-right-enter-from,
  .slide-right-leave-to {
    transform: translateX(100%);
  }

  .slide-right-enter-to,
  .slide-right-leave-from {
    transform: translateX(0);
  }
</style>
