<template>
  <router-view/>
  
  <!-- fix auth error -->
  <q-dialog 
    v-model="needReloadPage" 
    persistent 
    transition-show="scale"
    >
    <q-card 
      flat class="q-py-lg q-px-md text-center w80 rounded-card no-scroll"
      style="width: calc(min(100vw, var(--body-width)) - 32px);"
      >
      <q-card-section class="q-pa-none">
        <div class="text-h6 text-weight-bold q-mb-sm">
          {{ $t('telegram_auth_error__title')}}
        </div>
        
        <div class="text-body1 text-grey-8">
          {{ $t('telegram_auth_error__description')}}
        </div>
      </q-card-section>

      <q-card-actions align="center" class="q-mt-lg q-pa-none">
        <q-btn 
          unelevated 
          rounded
          :label="$t('telegram_auth_error__btn')" 
          color="primary" 
          class="full-width q-py-sm text-weight-bold"
          @click="closePage" 
        />
      </q-card-actions>
    </q-card>
  </q-dialog>

</template>

<script setup lang="ts">
  import { ref, computed, watch, inject, onMounted, onUnmounted, getCurrentInstance } from 'vue'
  import { useSettingsStore } from 'stores/settings'
  import { useAuthStore } from 'stores/auth'
  import { useSSEStore } from 'stores/SSE'
  import { useRouter } from 'vue-router'
  import type { WebApp } from '@twa-dev/types'
  import { storeToRefs } from 'pinia'
  import { useQuasar } from 'quasar'
  import { useI18n } from 'vue-i18n'
  import type { CompanyParams } from 'types/Company'

  const authStore = useAuthStore()
  const settingsStore = useSettingsStore()
  const sseStore = useSSEStore()
  const { isAuth } = storeToRefs(authStore)
  const { t } = useI18n()

  const app = getCurrentInstance()
  const isMobile = app?.appContext.config.globalProperties.$isMobile

  const router = useRouter()
  const tg = inject('tg') as WebApp
  const needReloadPage = ref(false)

  tg.onEvent('settingsButtonClicked', async () => {
    await router.push(authStore.isAuth ? { name: 'account' } : { name: 'settings' } )
  })
  
  watch(isAuth, async (newVal: boolean) => {
    if (newVal) sseStore.connect()
    else sseStore.disconnect()

    if (authStore.customer?.company || 
        (authStore.customer?.company &&
        Object.keys(authStore.customer?.company).length === 0
        )) {
      await authStore.updateMyCompany({ name: t('company_edit__my_company')} as CompanyParams)
    }

    if (newVal) await settingsStore.init()
  })

  // displayMode
  const displayMode = computed(() => settingsStore.settings.displayMode)
  const bgColor = getComputedStyle(document.documentElement)
    .getPropertyValue('--bg-base').trim() as `#${string}`
  const headerColor = bgColor || tg.themeParams.header_bg_color || tg.themeParams.bg_color
  
  watch(displayMode, (val) => {
    if (val === 'full' && tg.isVersionAtLeast('8.0') && isMobile) {
      tg.requestFullscreen()
      tg.setHeaderColor('bg_color') 
    } else {
      tg.exitFullscreen()
      tg.expand()
      tg.setHeaderColor(headerColor)
    }
  }, { immediate: true })
  
  onMounted(async () => {
    await settingsStore.init()
    if (isAuth.value) sseStore.connect()
    needReloadPage.value = (!(
      tg.initDataUnsafe.user && 
      Object.keys(tg.initDataUnsafe.user).length !== 0
    ) && isAuth && !authStore.customer?.email) ?? false
  })

  onUnmounted(() => sseStore.disconnect())

  function closePage () {
    tg.close()
  }

  const $q = useQuasar()
  $q.iconMapFn = (iconName) => {
    if (iconName.startsWith('pn-') === true) {
      const name = iconName.substring(3)
      return { cls: 'pn-icon ' + name }
    }
  }
</script>
