/**
 * The JavaScript code you place here will be processed by esbuild, and the
 * output file will be created at `../theme/js/script.min.js` and enqueued by
 * default in `../theme/functions.php`.
 *
 * For esbuild documentation, please see:
 * https://esbuild.github.io/
 */
import { gsap } from 'gsap';
import { ScrollToPlugin } from 'gsap/ScrollToPlugin.js';
import Lenis from 'lenis';
import Rellax from 'rellax';

gsap.registerPlugin(ScrollToPlugin);

import Swiper from 'swiper/bundle';
import { clickEvents } from './dom';
import { screen } from './screen';
import { backToTop } from './backToTop';
import { flexGap } from './flex-gap';
import { videoBackground } from './video-background';

// Initialize Lenis smooth scroll
const lenis = new Lenis({
  duration: 1.2,
  easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
  direction: 'vertical',
  gestureDirection: 'vertical',
  smooth: true,
  mouseMultiplier: 1,
  smoothTouch: false,
  touchMultiplier: 2,
  infinite: false,
});

// Connect Lenis to GSAP's ScrollTrigger
function raf(time) {
  lenis.raf(time);
  requestAnimationFrame(raf);
}
requestAnimationFrame(raf);

// window.dispatchEvent(new Event('ljn:scroll'));
// Update screen parallax on Lenis scroll
 updateCoverVideoClass();
lenis.on('scroll', () => {
  window.dispatchEvent(new Event('ljn:scroll'));
  updateCoverVideoClass();
});

let coverVideoClassHasInitialized = false;

function updateCoverVideoClass() {
	const coverSection = document.querySelector('[data-cover-video]');
	if (!coverSection) return;

	const shouldBeInViewport = window.scrollY <= 10;
	const hasClass = document.body.classList.contains('is-cover-video-in-viewport');
	if (!coverVideoClassHasInitialized) {
		coverVideoClassHasInitialized = true;
	}

	if (shouldBeInViewport === hasClass) return;

	document.body.classList.toggle('is-cover-video-in-viewport', shouldBeInViewport);
}

document.addEventListener('DOMContentLoaded', () => {
	let rellax = null;
	const getRellaxCtor = () => {
		if (typeof Rellax === 'function') return Rellax;
		if (Rellax && typeof Rellax.default === 'function') return Rellax.default;
		return null;
	};
	const initRellax = () => {
		const hasElements = document.querySelector('.rellax');
		if (!hasElements || window.innerWidth < 1024) {
			if (rellax) {
				if (typeof rellax.destroy === 'function') {
					rellax.destroy();
				}
				rellax = null;
			}
			return;
		}
		if (rellax) {
			return;
		}
		const RellaxCtor = getRellaxCtor();
		if (!RellaxCtor) {
			return;
		}
		rellax = new RellaxCtor('.rellax', {
			// center: true,
			// wrapper:'.rellax-container'
		});
	};

	initRellax();
	window.addEventListener('resize', initRellax, { passive: true });


	flexGap();
	clickEvents();
	screen();
	backToTop('.js-back-to-top');
	videoBackground();
	new Swiper('.swiper-galerie', {
		slidesPerView: 1,
		loop: true,
		navigation: {
			nextEl: '.swiper-button-next',
			prevEl: '.swiper-button-prev',
		},
	});
});
