<script setup>
import { RouterView } from "vue-router";
import Navbar from "./components/navbar/Navbar.vue";
import useUserInfoStore from "@/stores/useUserInfoStore";
import { ref, provide, onUnmounted, watch } from "vue";
import { getAlertLog } from "@/apis/alert";
import dayjs from "dayjs";

const store = useUserInfoStore();

const alerts = ref([]);
let isToastOpen = ref({
  open: false,
  content: "",
  status: "info",
  to: "body",
});
const forgeLock = ref(true);
const toggleForgeLock = () => {
  forgeLock.value = !forgeLock.value;
};

const cancelToastOpen = () => {
  isToastOpen.value = {
    open: false,
    content: "",
  };
};

let alertInterval = null;
const getAlert = async () => {
  const res = await getAlertLog({
    isRecovery: 1,
    Start_date: dayjs().subtract(30, "day").format("YYYY-MM-DD"),
    End_date: dayjs().format("YYYY-MM-DD"),
  });
  alerts.value = (res.data || []).map((d) => ({ ...d, key: d.id }));
};

const openToast = (status, content, to = "body", confirm = null) => {
  isToastOpen.value = {
    open: true,
    content,
    status,
    to,
    confirm,
  };
};


// 監聽登入狀態，登入時啟動 getAlert 與定時器，登出時清除定時器
watch(
  () => store.user.token,
  (token) => {
    if (token) {
      getAlert();
      alertInterval = setInterval(getAlert, 30 * 1000);
    } else {
      if (alertInterval) {
        clearInterval(alertInterval);
        alertInterval = null;
      }
    }
  },
  { immediate: true }
);

onUnmounted(() => {
  if (alertInterval) {
    clearInterval(alertInterval);
    alertInterval = null;
  }
});

provide("app_toast", { openToast, cancelToastOpen });
provide("app_toggle", { forgeLock, toggleForgeLock });
provide("app_alerts", alerts);
</script>

<template>
  <Toast
    :content="isToastOpen.content"
    :open="isToastOpen.open"
    :status="isToastOpen.status"
    :cancel="cancelToastOpen"
    :confirm="isToastOpen.confirm"
    :to="isToastOpen.to"
  />
  <div v-if="store.user.token" class="min-h-screen">
    <Navbar />
    <div class="px-6 w-full relative app-container">
      <RouterView />
    </div>
  </div>
  <div v-else class="h-screen"><RouterView /></div>
</template>

<style scoped>
header {
  line-height: 1.5;
}

.logo {
  display: block;
  margin: 0 auto 1rem;
}
</style>
