<template>
  <div
    data-theme="light"
    lang="vi"
  >
    <slot></slot>
    <Transition>
      <SnackBar
        v-if="$store.snackbar"
        v-bind="$store.snackbar"
        @close="$store.snackbar = undefined"
      />
    </Transition>
    <div
      id="modals"
      class="absolute top-0"
    >
      <Modal
        v-if="$store.showmodal"
        v-bind="$store.showmodal"
        @close="$store.showmodal = undefined"
      />
    </div>
  </div>
</template>

<script setup>
import { onMounted } from "vue";
import { useRoute } from "vue-router";
import SnackBar from "@/components/snackbar/SnackBar.vue";
import Modal from "@/components/Modal.vue";
import { throttle } from "es-toolkit";

const route = useRoute();
const { $getdata, $requestLogin, $store } = useNuxtApp();
const authorized = ref(false);

function getViewport() {
  let viewport;
  const width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

  // Follow Bulma's breakpoints: https://bulma.io/documentation/start/responsiveness/#breakpoints
  if (width <= 768)
    viewport = 1; // 'mobile'
  else if (width <= 1023)
    viewport = 2; // 'tablet'
  else if (width <= 1215)
    viewport = 3; // 'desktop'
  else if (width <= 1407)
    viewport = 4; // 'widescreen'
  else viewport = 5; // 'fullhd'

  if (viewport !== $store.viewport) {
    $store.commit("viewport", viewport);
  }
}

async function checkRedirect() {
  if (route.query.username && route.query.token) {
    let row = await $getdata(
      "user",
      null,
      {
        filter: { username: route.query.username },
        values: "id,avatar,username,fullname,type,type__code,type__name,is_admin",
      },
      true,
    );
    if (row === "error" || row === undefined) return; /* $requestLogin(); */
    else {
      row.token = route.query.token;
      $store.commit("login", row);
    }
  } else if (!$store.login) return; /* $requestLogin(); */
  // await checkLogin();
}

async function checkLogin() {
  if ($store.login ? $store.login.token : false) {
    $store.commit("rights", await $getdata("grouprights", { group: $store.login.type }));
    let authtoken = await $getdata("token", { token: $store.login.token }, undefined, true);
    if (authtoken ? authtoken.expiry : true) return; /* $requestLogin(); */
    authorized.value = true;
  }
  // else $requestLogin();
}

onMounted(() => {
  checkRedirect();
  getViewport();
  const throttledGetViewport = throttle(getViewport, 400);
  window.addEventListener("resize", throttledGetViewport);
});
</script>

<style lang="css" scoped>
.v-enter-active,
.v-leave-active {
  transition: all 0.3s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
  top: 0;
}
</style>
