---
import "@fancyapps/ui/dist/fancybox/fancybox.css";
import "@/styles/fancybox-custom.css";
// Fancybox 管理器组件
---

<script>
  let Fancybox: any;

  async function setup() {
    const selectors = [
      ".custom-md img, #post-cover img, .moment-images img",
      ".moment-images a[data-fancybox]",
      "[data-fancybox]:not(.moment-images a)"
    ];

    // 检查页面是否存在需要 Fancybox 的元素
    const hasElements = selectors.some(selector => document.querySelector(selector));

    if (!hasElements) return;

    // 动态导入资源
    if (!Fancybox) {
      const mod = await import("@fancyapps/ui");
      Fancybox = mod.Fancybox;
    }

    // 通用配置
    const commonOptions = {
      Thumbs: {
        autoStart: true,
        showOnStart: "yes",
      },
      Toolbar: {
        display: {
          left: ["infobar"],
          middle: [
            "zoomIn",
            "zoomOut",
            "toggle1to1",
            "rotateCCW",
            "rotateCW",
            "flipX",
            "flipY",
          ],
          right: ["slideshow", "thumbs", "close"],
        },
      },
      animated: true,
      dragToClose: true,
      keyboard: {
        Escape: "close",
        Delete: "close",
        Backspace: "close",
        PageUp: "next",
        PageDown: "prev",
        ArrowUp: "next",
        ArrowDown: "prev",
        ArrowRight: "next",
        ArrowLeft: "prev",
      },
      fitToView: true,
      preload: 3,
      infinite: true,
      Panzoom: {
        maxScale: 3,
        minScale: 1,
      },
      caption: false,
    };

    // 绑定图片
    Fancybox.bind(".custom-md img, #post-cover img, .moment-images img", {
      ...commonOptions,
      groupAll: true,
      Carousel: {
        transition: "slide",
        preload: 2,
      },
    });

    // 绑定链接
    Fancybox.bind(".moment-images a[data-fancybox]", {
      ...commonOptions,
      source: (el: any) => el.getAttribute("data-src") || el.getAttribute("href"),
    });

    // 绑定其他
    Fancybox.bind("[data-fancybox]:not(.moment-images a)", commonOptions);
  }

  function cleanupFancybox() {
    if (Fancybox) {
      Fancybox.close();
      Fancybox.unbind(document.body);
    }
  }

  // 初始化
  setup();

  // Swup 生命周期整合
  document.addEventListener("swup:content:replace", setup);
  document.addEventListener("swup:visit:start", cleanupFancybox);
</script>
