---
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 allListeners = [];
        
        // 单独保存清理事件的监听器引用
        const cleanupListeners = [];
        
        // 定时器引用
        let themeUpdateTimeout = null;
        
        // 添加事件监听器并记录，方便后续统一清理
        function addListener(element, eventType, handler, options) {
          if (!element) {
            console.error(`尝试为不存在的元素添加事件:`, eventType);
            return null;
          }

          element.addEventListener(eventType, handler, options);
          allListeners.push({ element, eventType, handler, options });
          return handler;
        }
        
        // 统一的清理函数，执行完整清理并自销毁
        function selfDestruct() {
          // 1. 清理所有计时器
          if (themeUpdateTimeout) {
            clearTimeout(themeUpdateTimeout);
            themeUpdateTimeout = null;
          }
          
          // 2. 移除普通事件监听器
          allListeners.forEach(({ element, eventType, handler, options }) => {
            try {
              element.removeEventListener(eventType, handler, options);
            } catch (err) {
              console.error(`主题初始化移除事件监听器出错:`, err);
            }
          });
          
          // 清空监听器数组
          allListeners.length = 0;
          
          // 3. 最后移除清理事件监听器自身
          cleanupListeners.forEach(({ element, eventType, handler, options }) => {
            try {
              element.removeEventListener(eventType, handler, options);
            } catch (err) {
              console.error(`主题初始化移除清理监听器出错:`, err);
            }
          });
          
          // 清空清理监听器数组
          cleanupListeners.length = 0;
        }
        
        // 注册清理事件，并保存引用
        function registerCleanupEvents() {
          // 创建统一的清理处理函数
          const cleanup = () => {
            selfDestruct();
          };
          
          // 定义需要监听的所有清理事件
          const cleanupEventTypes = [
            { element: document, eventType: "astro:before-swap", options: { once: true } },
            { element: window, eventType: "beforeunload", options: { once: true } },
            { element: document, eventType: "astro:before-preparation", options: { once: true } },
            { element: document, eventType: "page-transition", options: { once: true } }
          ];
          
          // 注册所有清理事件
          cleanupEventTypes.forEach(({ element, eventType, options }) => {
            // 添加事件监听
            element.addEventListener(eventType, cleanup, options);
            
            // 保存事件引用到清理列表
            cleanupListeners.push({
              element,
              eventType,
              handler: cleanup,
              options
            });
          });
          
          // SPA框架可能使用的事件 - 特殊处理
          if (typeof document.addEventListener === 'function') {
            document.addEventListener("swup:willReplaceContent", cleanup, { once: true });
            cleanupListeners.push({
              element: document,
              eventType: "swup:willReplaceContent",
              handler: cleanup,
              options: { 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);
          
          // 注册清理函数
          registerCleanupEvents();
          
          // 监听页面转换事件，确保在页面转换后重新初始化
          function onPageTransition() {
            // 防止重复执行，使用防抖
            if (themeUpdateTimeout) {
              clearTimeout(themeUpdateTimeout);
            }
            
            // 使用微小延迟确保DOM完全就绪
            themeUpdateTimeout = setTimeout(() => {
              try {
                // 重新初始化主题
                const storedTheme = localStorage.getItem("theme");
                if (storedTheme) {
                  document.documentElement.dataset.theme = storedTheme;
                } else {
                  const systemTheme = getSystemTheme();
                  document.documentElement.dataset.theme = systemTheme;
                }
              } catch (err) {
                console.error("页面转换后主题更新出错:", err);
              } finally {
                themeUpdateTimeout = null;
              }
            }, 10);
          }
          
          // 设置页面转换事件监听
          addListener(document, "astro:page-load", onPageTransition);
          addListener(document, "astro:after-swap", onPageTransition);
          
        } catch (error) {
          console.error("主题初始化失败:", error);
          // 出错时应用默认浅色主题，确保页面正常显示
          document.documentElement.dataset.theme = "light";
          // 即使出错也尝试注册清理事件
          try {
            registerCleanupEvents();
          } catch (e) {
            // 忽略清理注册错误
          }
        }
      })();
    </script>

    <script>
      import '../scripts/swup-init.js';
    </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}
    />

  </body>
</html>
