const screen = () => {
	init();
};

const init = () => {
	addListenners();

	window.dispatchEvent(new Event('resize'));
	setTimeout(() => {
		scrollAppear();
		parallax();
		// window.dispatchEvent(new Event('scroll'));
	}, 100);
};
const addListenners = () => {
	window.addEventListener(
		'scroll',
		() => {
			onscroll();
		},
		false
	);

	window.addEventListener(
		'resize',
		() => {
			onresize();
		},
		false
	);
};
const onresize = () => {};
const onscroll = () => {
	parallax();
	scrollAppear();
};

const parallax = () => {
	let depth, i, layer, layers, len, movement, topDistance, translate3d;
	layers = document.querySelectorAll("[data-type='parallax']");

	for (i = 0, len = layers.length; i < len; i++) {
		layer = layers[i];
		topDistance =
			window.scrollY -
			layer.parentElement.offsetTop +
			window.innerHeight / 2;
		depth = layer.getAttribute('data-depth') || 1;
		topDistance = topDistance / 10;
		movement = Math.round(-(topDistance * depth));
		// console.log("movement :: ", movement)
		translate3d = 'translate3d(0, ' + movement + 'px, 0)';
		layer.style['-webkit-transform'] = translate3d;
		layer.style['-moz-transform'] = translate3d;
		layer.style['-ms-transform'] = translate3d;
		layer.style['-o-transform'] = translate3d;
		layer.style.transform = translate3d;
	}
};

const scrollAppear = () => {
	const elements = document.querySelectorAll('.scroll-appear');
	const elTemp = document.getElementsByClassName('scroll-appear-temporise');
	let d = 0 + elTemp.length * 100;
	if (elements.length > 0) {
		elements.forEach((el) => {
			try {
				if (
					isInViewport(el, -window.innerHeight / 5) &&
					!el.classList.contains('scroll-appear-ok') &&
					!el.classList.contains('scroll-appear-temporise')
				) {
					el.classList.add('scroll-appear-temporise');
					setTimeout(() => {
						el.classList.add('scroll-appear-ok');
						try {
							el.classList.remove('scroll-appear-temporise');
						} catch (error) {
							console.log('no temporise');
						}
					}, d);
					d += 100;
				}
			} catch (error) {
				el.classList.add('scroll-appear-ok');
			}
		});
	}
};

const isInViewport = (el, gap, decal) => {
	const d = decal || 0;
	const elY = el.getBoundingClientRect().top + d;
	const wY = window.innerHeight;
	const g = gap || 0;
	return elY < wY + g && elY + el.offsetHeight > 0 - g;
};

export { screen };
