<template>
  <header class="sticky inset-x-0 top-0 w-full bg-neutral-10 z-10">
      <Header/>
      <Navbar/>
  </header>
  <main>
    <Loading v-if="loadingStore.isLoading" />
    <router-view>
    </router-view>
  </main>
</template>

<script>
import { storeToRefs } from 'pinia';
import LoginStore from '@/stores/login.js';
import LoadingStore from '@/stores/loading.js';
import AllMapDataStore from '@/stores/allMapData.js';
import Header from "@/components/Header.vue";
import Navbar from "@/components/Navbar.vue";
import Loading from '@/components/Loading.vue';
import { saveFilter, leaveFilter } from '@/module/alertModal.js';

export default {
  name: 'MainContainer',
  setup() {
    const loginStore = LoginStore();
    const loadingStore = LoadingStore();
    const allMapDataStore = AllMapDataStore();
    const { checkLogin } = loginStore;
    const { tempFilterId, createFilterId,  temporaryData, postRuleData, ruleData } = storeToRefs(allMapDataStore);

    return { checkLogin, loadingStore, temporaryData, tempFilterId, createFilterId, postRuleData, ruleData, allMapDataStore };
  },
  watch: {
    $route: function(to, from) {
      // 離開 Map Log 頁要將 Funnel 的規則刪除, Map Filter 會帶上次儲存的 Funnel, 所以不用做
      if(from.name === 'Map' && from.params.type === 'log') {
        this.tempFilterId = null;
        this.temporaryData = [];
        this.postRuleData = [];
      }
    }
  },
  components: {
    Header,
    Navbar,
    Loading,
    saveFilter,
    leaveFilter
  },
  created() {
    /**
     * Save token in Headers.
     */
    const token = document.cookie.replace(/(?:(?:^|.*;\s*)luciaToken\s*\=\s*([^;]*).*$)|^.*$/, "$1");
    this.$http.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    /**
     * check login for 'my-account' api
     */
    this.checkLogin();
  },
  beforeRouteUpdate(to, from, next) {
    // 離開 Discover 頁時判斷是否有無資料和需要存檔
    if ((from.name === 'Map') && this.tempFilterId) {
      leaveFilter(next, this.allMapDataStore.addFilterId, to.path)
    } else {
      next();
    }
  },
};
</script>
