import gsap from "gsap";

export async function letsBegin(negl) {
  const tl = await loadStart(negl);
  await loadingAnimation(tl);
  return tl;
}

function loadStart(negl) {
  const body = document.body,
    loader = document.querySelector("#loader"),
    globalContainer = document.querySelector(negl.config.$.globalContainer),
    duration = 1.5;

  return new Promise((resolve) => {
    // ローディングアニメーション追加
    // Add loading animation
    const tl = gsap.timeline();

    // loaderをblurを掛けながら非表示
    // Hide the loader with a blur effect
    tl.to(body, {
      "--blur": "8px",
      "--loader-opacity": 0,
      duration,
      ease: "power2.inout",
      onStart() {},
    })
      // global-containerをblurを掛けながら表示
      // Show the global-container with a blur effect
      .to(
        body,
        {
          "--blur": "0px",
          "--container-opacity": 1,
          duration,
          ease: "power2.inout",
          onStart() {},
          onComplete() {
            loader.style.display = "none";
            globalContainer.style.filter = "none";
            resolve(tl);
          },
        },
        "-=0.5"
      );
  });
}

let loadingAnimation = (tl) => {};

export function animateDetailSvg() {
  const svgGroup = document.querySelector(".dc-svg-group");
  if (svgGroup) {
    svgGroup.classList.add("animation");
    function animationend(event) {
      svgGroup.classList.add("--end");
      svgGroup.firstElementChild.removeEventListener(
        "animationend",
        animationend
      );
    }
    svgGroup.firstElementChild.addEventListener("animationend", animationend);
  }
}

export function addLoadingAnimation(_loadingAnimation) {
  loadingAnimation = _loadingAnimation;
}
