---
import "@/styles/global.css";
import Header from "@/components/Header.astro";
import Footer from "@/components/Footer.astro";
import {
  ICP,
  PSB_ICP,
  PSB_ICP_URL,
  SITE_NAME,
  SITE_DESCRIPTION,
} from "@/consts";
import { AstroSeo } from "@astrolib/seo";

// 定义Props接口
interface Props {
  title?: string;
  description?: string;
  date?: Date;
  tags?: string[];
  skipSrTitle?: boolean; // 控制是否跳过屏幕阅读器标题
  pageType?: "page" | "article" | "directory" ; // 更有语义的页面类型
}

// 获取完整的 URL
const canonicalURL = new URL(Astro.url.pathname, Astro.site);

// 从props中获取页面特定信息
const {
  title = SITE_NAME,
  description = SITE_DESCRIPTION,
  date,
  tags,
  skipSrTitle = false, // 默认显示屏幕阅读器标题
  pageType = "page", // 默认为普通页面
} = Astro.props;
---

<!doctype html>
<html
  lang="zh-CN"
  class="m-0 w-full h-full"
>
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width"
    />
    <meta
      name="referrer"
      content="no-referrer"
    />
    <link
      rel="icon"
      type="image/svg+xml"
      href="/favicon.svg"
    />
    <meta
      name="generator"
      content={Astro.generator}
    />


    <!-- 使用 AstroSeo 组件替换原有的 SEO 标签 -->
    <AstroSeo
      title={title}
      description={description || `${SITE_NAME} - 个人博客`}
      canonical={canonicalURL.toString()}
      openGraph={{
        type: pageType,
        url: canonicalURL.toString(),
        title: title,
        description: description || `${SITE_NAME} - 个人博客`,
        site_name: SITE_NAME,
      }}
      twitter={{
        cardType: "summary_large_image",
        site: SITE_NAME,
        handle: SITE_NAME,
      }}
      additionalMetaTags={[
        // 仅对文章类型添加标准OpenGraph文章标记
        ...(date && pageType === "article" ? [{
          property: "article:published_time",
          content: date.toISOString(),
        }] : []),
        // 文章标签使用标准格式
        ...(pageType === "article" && tags ? tags.map((tag) => ({
          property: "article:tag",
          content: tag,
        })) : []),
      ]}
    />

    <!-- 主题切换脚本 -->
    <script is:inline>
      // 立即执行主题初始化，采用"无闪烁"加载方式
      (function () {
        // 存储事件监听器，便于清理
        const listeners = [];
        
        // 添加事件监听器并记录，方便后续统一清理
        function addListener(element, eventType, handler, options) {
          if (!element) return null;
          
          element.addEventListener(eventType, handler, options);
          listeners.push({ element, eventType, handler, options });
          return handler;
        }
        
        // 清理函数 - 移除所有事件监听器
        function cleanup() {
          listeners.forEach(({ element, eventType, handler, options }) => {
            try {
              element.removeEventListener(eventType, handler, options);
            } catch (err) {
              // 忽略错误
            }
          });
          
          // 清空数组
          listeners.length = 0;
        }
        
        // 注册清理函数 - 确保在页面转换前清理事件
        function registerCleanup() {
          const cleanupEvents = [
            "astro:before-preparation",
            "astro:before-swap",
            "swup:willReplaceContent"
          ];

          // 为每个事件注册一次性清理函数
          cleanupEvents.forEach((eventName) => {
            document.addEventListener(eventName, cleanup, { once: true });
          });

          // 页面卸载时清理
          window.addEventListener("beforeunload", cleanup, { once: true });
        }

        try {
          // 获取系统首选主题
          const getSystemTheme = () => {
            return window.matchMedia("(prefers-color-scheme: dark)").matches
              ? "dark"
              : "light";
          };

          const storedTheme =
            typeof localStorage !== "undefined"
              ? localStorage.getItem("theme")
              : null;
          const systemTheme = getSystemTheme();
          let theme = "light"; // 默认浅色主题

          // 按照逻辑优先级应用主题
          if (storedTheme) {
            // 如果有存储的主题设置，则应用它
            theme = storedTheme;
          } else if (systemTheme) {
            // 如果没有存储的设置，检查系统主题
            theme = systemTheme;
          }

          // 立即设置文档主题，在DOM渲染前应用，避免闪烁
          document.documentElement.dataset.theme = theme;
          
          // 监听系统主题变化（只有当主题设为跟随系统时才响应）
          const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");

          const handleMediaChange = (e) => {
            // 只有当主题设置为跟随系统时才更新主题
            if (!localStorage.getItem("theme")) {
              const newTheme = e.matches ? "dark" : "light";
              document.documentElement.dataset.theme = newTheme;
            }
          };

          // 添加系统主题变化监听
          addListener(mediaQuery, "change", handleMediaChange);
          
          // 注册清理函数
          registerCleanup();
          
          // 监听页面转换事件，确保在页面转换后重新初始化
          function onPageTransition() {
            // 重新初始化主题
            if (storedTheme) {
              document.documentElement.dataset.theme = storedTheme;
            } else {
              const systemTheme = getSystemTheme();
              document.documentElement.dataset.theme = systemTheme;
            }
          }
          
          // 设置页面转换事件监听
          document.addEventListener("astro:page-load", onPageTransition);
          document.addEventListener("astro:after-swap", onPageTransition);
          
        } catch (error) {
          // 出错时应用默认浅色主题，确保页面正常显示
          document.documentElement.dataset.theme = "light";
        }
      })();
    </script>
  </head>
  <body
    class="m-0 w-full h-full bg-gray-50 dark:bg-dark-bg flex flex-col min-h-screen"
  >
    <Header />
    <main class="pt-16 flex-grow max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 w-full">
      {!skipSrTitle && <h1 class="sr-only">{title}</h1>}
      <slot />
    </main>
    <Footer
      icp={ICP}
      psbIcp={PSB_ICP}
      psbIcpUrl={PSB_ICP_URL}
    />

    <!-- 预获取脚本 -->
    <script is:inline>
      // 在DOM加载完成后执行
      document.addEventListener("astro:page-load", () => {
        // 获取所有视口预获取链接
        const viewportLinks = document.querySelectorAll(
          '[data-astro-prefetch="viewport"]',
        );

        if (viewportLinks.length > 0) {
          // 创建一个交叉观察器
          const observer = new IntersectionObserver((entries) => {
            entries.forEach((entry) => {
              if (entry.isIntersecting) {
                const link = entry.target;
                // 进入视口时，添加data-astro-prefetch="true"属性触发预获取
                if (link.getAttribute("data-astro-prefetch") === "viewport") {
                  link.setAttribute("data-astro-prefetch", "true");
                }
                // 一旦预获取，就不再观察这个链接
                observer.unobserve(link);
              }
            });
          });

          // 观察所有视口预获取链接
          viewportLinks.forEach((link) => {
            observer.observe(link);
          });
        }
      });
    </script>
  </body>
</html>
