<template></template>

<script setup>
import { useHead } from "#app"; // 匯入 Head
import { ref, onMounted } from "vue"; // 開機自啟
import { useRouter } from "vue-router"; // 匯入路由
const config = useRuntimeConfig();
const $api_host = config.public.apiHost;
const router = useRouter(); // 匯入路由

definePageMeta({
  layout: false, // 禁用 layout
});

// 設置 Head
useHead({
  title: "Lamiter",
  meta: [
    { charset: "utf-8" },
    { "http-equiv": "X-UA-Compatible", content: "IE=edge" },
    { name: "viewport", content: "width=device-width, initial-scale=1, shrink-to-fit=no" },
    { name: "description", content: "" },
    { name: "author", content: "" },
  ],
  link: [
    {
      rel: "stylesheet",
      href: "https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i",
    },
    { rel: "stylesheet", href: "/css/sb-admin-2.min.css" },
    { rel: "stylesheet", href: "/vendor/fontawesome-free/css/all.min.css" },
  ],
  script: [
    { src: "/vendor/jquery/jquery.min.js" },
    { src: "/vendor/bootstrap/js/bootstrap.bundle.min.js" },
    { src: "/vendor/jquery-easing/jquery.easing.min.js" },
    { src: "/js/sb-admin-2.min.js" },
  ],
});

// 🔐 Token 狀態管理（確保 SSR 不報錯）
const authToken = useState("authToken", () => process.client ? localStorage.getItem("token_TCM") || "" : "");

// 🔍 檢查 Token
async function token_check() {
  if (!process.client) return; // 確保在 client-side 執行

  const token = localStorage.getItem("token_TCM");
  console.log("Token:", token);

  if (!token) {
    console.log("無 Token，轉跳首頁");
    router.push("/Home_pages/").then(() => {
      window.location.reload();
    });
    return;
  }

  try {
    const response = await fetch(`${$api_host}/Users/token_check_user`, {
      method: "GET",
      headers: {
        Authorization: token,
      },
    });

    if (!response.ok) throw new Error("Token 驗證失敗");

    const data = await response.json();
    console.log("驗證成功:", data);

    if (data.level >= 9) {
      router.push("/Lamiter_pages/");
    } else if (data.level == 8) {
      router.push("/Manage_pages/");
    }
  } catch (error) {
    console.error("Token 驗證失敗", error);
    router.push("/Home_pages/");
  }
}

// 🔄 開機執行
onMounted(token_check);
</script>

