/**
 * トップページ（index.htmlなど）用制御ファイル
 * Control file for the top page (such as index.html)
 *
 * data-page="home" ページ独自の処理を行います。
 * Performs page-specific processing for data-page="home".
 */
import { world, negl, utils } from "negl";
import { scrollSnap } from "#/parts/helper/scrollSnap";
import { setupMenu } from "#/parts/menu-box";
import { addLoadingAnimation } from "#/parts/loader-ghibli";
import { isLowPerformanceMode } from "#/parts/helper/detectGPU";

let _loadFns;

export default async function (transitionState) {
  const goTo = setupSlider(transitionState);
  _loadFns = setupMenu(negl);

  const { world } = negl;
  // メッシュのクリックでテーマ切り替え
  // Switch themes by clicking on the mesh
  const menuBox = world.getObByEl(".menu-box");

  // clickにイベントを登録
  // Register events for click
  menuBox.click = ({ transition }) => {
    // アクティブのスライダのURLに遷移
    // Transition to the URL of the active slider
    const sliderO = world.getObByEl(".slider");
    const modIdx = Math.round(sliderO.getModIdx()) + 1;
    const url = sliderO.dataAttrs[`click-${modIdx}`];
    transition.go(url);
  };

  const menuTriangles = world.getObByElAll(".menu-triangle");
  menuTriangles[0].click = goTo.bind(null, -2);
  menuTriangles[1].click = goTo.bind(null, 2);

  addLoadingAnimation(loadAnimation);
}

function setupSlider(transitionState) {
  if (utils.isTouchDevices() || isLowPerformanceMode()) {
    const sliderOs = world.getObByElAll(".slider");
    sliderOs.forEach((o) => {
      if (
        o.$.el.classList.contains("left") ||
        o.$.el.classList.contains("right")
      ) {
        world.removeOb(o);
      }
    });
  }
  const sliderOs = world.getObByElAll(".slider");
  const slideNum = sliderOs[0].slides.length;
  // 初期表示のスライド番号
  // Initial slide number for display
  let activeSlideIdx = Math.round(Math.random() * slideNum);

  if (
    transitionState &&
    transitionState.next.store.get("slideIdx") !== undefined
  ) {
    activeSlideIdx = transitionState.next.store.get("slideIdx");
  }
  sliderOs.forEach((o, i) => {
    o.setTo(activeSlideIdx);
  });

  return scrollSnap(
    (slideIdx, delta) => {
      // z軸方向の移動
      // Movement in the z-axis direction
      sliderOs.forEach((sliderO) => sliderO.goTo(-slideIdx));
    },
    { speed: 10, damping: 3 },
    -activeSlideIdx
  );
}

export function loadAnimation() {
  _loadFns.forEach((loadFn, idx) => setTimeout(loadFn, idx * 100));
}
