(function () {
  var html = document.documentElement;

  var dropEnter = false;
  var dropOrigin = null;
  try {
    dropEnter = sessionStorage.getItem("pageExpandEnter") === "1";
    var raw = sessionStorage.getItem("pageExpandOrigin");
    if (raw) dropOrigin = JSON.parse(raw);
    sessionStorage.removeItem("pageFlipEnter");
  } catch (e) {}

  if (dropEnter) {
    html.classList.add("page-drop-enter");
    html.style.background = "#eef4ff";
  } else {
    html.classList.add("page-boot");
  }

  function viewport() {
    return {
      w: window.innerWidth || document.documentElement.clientWidth || 1,
      h: window.innerHeight || document.documentElement.clientHeight || 1,
    };
  }

  function resolveOrigin() {
    var vp = viewport();
    var rx = 0.72;
    var ry = 0.18;
    if (dropOrigin && typeof dropOrigin.rx === "number") rx = dropOrigin.rx;
    if (dropOrigin && typeof dropOrigin.ry === "number") ry = dropOrigin.ry;
    return {
      x: Math.max(0, Math.min(vp.w, rx * vp.w)),
      y: Math.max(0, Math.min(vp.h, ry * vp.h)),
      vp: vp,
      xPct: (rx * 100).toFixed(3) + "%",
      yPct: (ry * 100).toFixed(3) + "%",
    };
  }

  function easeOutCubic(t) {
    return 1 - Math.pow(1 - t, 3);
  }

  /** 第二波：遮罩从圆心被清开，露出选购页 */
  function playDropEnter() {
    var origin = resolveOrigin();
    var x = origin.x;
    var y = origin.y;
    var vp = origin.vp;
    var endR = Math.hypot(Math.max(x, vp.w - x), Math.max(y, vp.h - y)) + 56;

    html.style.setProperty("--expand-x", origin.xPct);
    html.style.setProperty("--expand-y", origin.yPct);
    html.style.setProperty("--hole-r", "0px");

    var cover = document.createElement("div");
    cover.className = "page-drop-enter-cover";
    document.documentElement.appendChild(cover);

    html.classList.add("page-drop-ready");
    html.classList.remove("page-boot");
    html.classList.add("page-ready");

    var duration = 1050;
    var start = null;
    var faded = false;

    function frame(now) {
      if (start == null) start = now;
      var t = Math.min(1, (now - start) / duration);
      var r = endR * easeOutCubic(t);
      html.style.setProperty("--hole-r", r + "px");
      cover.style.setProperty("--hole-r", r + "px");
      // 第二波清开时，选购页内容同步渐显
      if (!faded && t > 0.02) {
        faded = true;
        document.body.classList.add("page-drop-fade-in");
      }
      if (t < 1) {
        requestAnimationFrame(frame);
        return;
      }
      document.body.classList.add("page-drop-fade-in");
      if (cover.parentNode) cover.parentNode.removeChild(cover);
      html.classList.remove("page-drop-enter", "page-drop-ready");
      document.body.classList.remove("page-drop-fade-in");
      document.body.style.opacity = "";
      html.style.background = "";
      html.style.removeProperty("--expand-x");
      html.style.removeProperty("--expand-y");
      html.style.removeProperty("--hole-r");
      try {
        sessionStorage.removeItem("pageExpandEnter");
        sessionStorage.removeItem("pageExpandOrigin");
      } catch (e) {}
    }

    // 稍停一拍，让第一波铺满感接上，再开第二波清开
    window.setTimeout(function () {
      cover.classList.add("is-clearing");
      requestAnimationFrame(frame);
    }, 90);
  }

  function ready() {
    if (dropEnter) {
      playDropEnter();
      return;
    }
    requestAnimationFrame(function () {
      html.classList.remove("page-boot");
      html.classList.add("page-ready");
    });
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", ready);
  } else {
    ready();
  }
  window.setTimeout(function () {
    if (html.classList.contains("page-boot") && !html.classList.contains("page-ready")) {
      ready();
    }
  }, 1000);

  window.addEventListener("pageshow", function (ev) {
    if (ev.persisted) {
      html.classList.remove("page-leave", "page-boot", "page-flip-leave", "page-drop-enter", "page-drop-leaving", "page-expand-enter", "page-expanding");
      html.classList.add("page-ready");
      document.body.classList.remove("page-exit");
      var leftover = document.querySelector(".page-drop-enter-cover, .page-drop-leave");
      if (leftover && leftover.parentNode) leftover.parentNode.removeChild(leftover);
    }
  });

  function leaveTo(href) {
    if (html.classList.contains("page-leave") || html.classList.contains("page-drop-leaving")) return;
    html.classList.add("page-leave");
    window.setTimeout(function () {
      window.location.href = href;
    }, 400);
  }

  /** 第一波：水滴圆从点击处扩散铺满，再进新页 */
  function expandTo(href, fromEl) {
    if (html.classList.contains("page-drop-leaving")) return;
    html.classList.add("page-drop-leaving");
    html.style.background = "#eef4ff";

    var reduce = false;
    try {
      reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    } catch (e) {}

    var vp = viewport();
    var x = vp.w * 0.72;
    var y = vp.h * 0.18;
    var rect = null;
    if (fromEl) {
      rect = fromEl.getBoundingClientRect();
      x = rect.left + rect.width / 2;
      y = rect.top + rect.height / 2;
    }

    try {
      sessionStorage.setItem("pageExpandEnter", "1");
      sessionStorage.setItem(
        "pageExpandOrigin",
        JSON.stringify({ rx: x / vp.w, ry: y / vp.h })
      );
    } catch (e) {}

    if (reduce || !fromEl || !rect) {
      window.location.href = href;
      return;
    }

    var startR = Math.max(rect.width, rect.height) * 0.5;
    var endR = Math.hypot(Math.max(x, vp.w - x), Math.max(y, vp.h - y)) + 32;
    var startClip = "circle(" + startR + "px at " + x + "px " + y + "px)";
    var endClip = "circle(" + endR + "px at " + x + "px " + y + "px)";

    var drop = document.createElement("div");
    drop.className = "page-drop-leave";
    drop.style.setProperty("--expand-x", x + "px");
    drop.style.setProperty("--expand-y", y + "px");
    drop.style.clipPath = startClip;
    drop.style.webkitClipPath = startClip;
    document.body.appendChild(drop);

    try {
      fromEl.style.transition = "opacity .2s ease, transform .28s ease";
      fromEl.style.opacity = "0";
      fromEl.style.transform = "scale(0.96)";
    } catch (e) {}

    drop.getBoundingClientRect();
    requestAnimationFrame(function () {
      requestAnimationFrame(function () {
        drop.classList.add("is-on");
        drop.style.clipPath = endClip;
        drop.style.webkitClipPath = endClip;
      });
    });

    // 铺满后再跳转，新页接第二波
    window.setTimeout(function () {
      window.location.href = href;
    }, 920);
  }

  window.flipToSales = function (href) {
    expandTo(href || "./sales.html", document.querySelector(".buy-btn"));
  };
  window.expandToSales = window.flipToSales;

  document.addEventListener(
    "click",
    function (event) {
      var link = event.target.closest("a");
      if (!link) return;
      var href = link.getAttribute("href");
      if (!href || href.charAt(0) === "#" || href.indexOf("javascript:") === 0) return;

      if (link.hasAttribute("data-expand") || link.getAttribute("data-flip") === "page") {
        event.preventDefault();
        expandTo(href, link);
        return;
      }

      var isTool =
        link.hasAttribute("data-transition") ||
        /\.html(?:[?#].*)?$/.test(href);
      if (!isTool) return;
      event.preventDefault();
      leaveTo(href);
    },
    true
  );
})();
