window.addEventListener('load', function () {
  const header = document.querySelector('.header');
  const mv = document.querySelector('.mv');

  if (!header || !mv) return;

  function toggleHeader() {
    const mvBottom = mv.getBoundingClientRect().bottom;

    if (mvBottom <= -50) {
      header.classList.add('is_show');
    } else {
      header.classList.remove('is_show');
    }
  }

  window.addEventListener('scroll', toggleHeader, { passive: true });

  toggleHeader();
});

window.addEventListener('load', function () {
  const marquees = document.querySelectorAll('.infinite-slider');

  marquees.forEach((marqueeWrapper) => {
    const marquee = marqueeWrapper.querySelector('ul');
    const items = Array.from(marquee.children);
    const speedSeconds = 120;

    const direction = marqueeWrapper.classList.contains('right') ? 'right' : 'left';

    // 開始位置
    const start = parseFloat(marqueeWrapper.dataset.start || 0);

    // 無限スクロール用に複製
    items.forEach((item) => marquee.appendChild(item.cloneNode(true)));

    const marqueeWidth = marquee.scrollWidth / 2;

    let pos;

    if (direction === 'left') {
      pos = -start;
    } else {
      pos = -marqueeWidth + start;
    }

    const pixelsPerFrame = marqueeWidth / (speedSeconds * 60);

    function animate() {
      pos += direction === 'left' ? -pixelsPerFrame : pixelsPerFrame;

      // 無限ループ
      if (pos <= -marqueeWidth) pos += marqueeWidth;
      if (pos >= 0) pos -= marqueeWidth;

      marquee.style.transform = `translateX(${pos}px)`;

      requestAnimationFrame(animate);
    }

    animate();
  });
});

$(function () {
  $('.aco_wrap').each(function () {
    const $acoWrap = $(this);

    $acoWrap.attr('data-close-height', $acoWrap.outerHeight());
  });

  $('.btn_more').on('click', function () {
    const $button = $(this);
    const $acoBlock = $button.closest('.aco_block');
    const $acoWrap = $acoBlock.find('.aco_wrap');
    const closeHeight = Number($acoWrap.attr('data-close-height'));

    if ($acoWrap.hasClass('is-open')) {
      $acoWrap.stop().animate(
        {
          height: closeHeight
        },
        300,
        function () {
          $acoWrap.removeClass('is-open');
        }
      );

      $button.text('続きを見る');
    } else {
      const openHeight = $acoWrap.css('height', 'auto').outerHeight();

      $acoWrap.height(closeHeight);

      $acoWrap.stop().animate(
        {
          height: openHeight
        },
        300,
        function () {
          $acoWrap.css('height', 'auto').addClass('is-open');
        }
      );

      $button.text('閉じる');
    }
  });
});
