/**
 * Theme Scripts.
 *
 * Handles go-to-top button and smooth scroll functionality.
 *
 * @package YourTheme
 */

(function () {
	'use strict';

	/**
	 * Initialize everything when DOM is ready.
	 */
	document.addEventListener('DOMContentLoaded', () => {
		document.body.classList.add('js');
		document.body.classList.remove('no-js');

		goTop();
		initSmoothScroll();
	});

	/**
	 * Go To Top Button Handler.
	 */
	function goTop() {
		const btnGoTop = document.querySelector('.js-gotop');

		if (!btnGoTop) {
			return;
		}

		// Click listener
		if (!btnGoTop.dataset.initialized) {
			btnGoTop.addEventListener('click', () => {
				window.scrollTo({ top: 0, behavior: 'smooth' });
			});
			btnGoTop.dataset.initialized = "true";
		}

		// Scroll listener
		let ticking = false;
		const handleScroll = () => {
			if (!ticking) {
				window.requestAnimationFrame(() => {
					const currentScroll = window.pageYOffset || document.documentElement.scrollTop;
					const threshold = 300;

					if (currentScroll > threshold) {
						if (!btnGoTop.classList.contains('is-active')) {
							btnGoTop.classList.remove('is-hiding');
							btnGoTop.classList.add('is-active');
						}
					} else {
						if (btnGoTop.classList.contains('is-active')) {
							btnGoTop.classList.remove('is-active');
							btnGoTop.classList.add('is-hiding');
							
							// Jeda agar animasi CSS selesai (sesuai durasi di SCSS)
							setTimeout(() => {
								btnGoTop.classList.remove('is-hiding');
							}, 500);
						}
					}
					ticking = false;
				});
				ticking = true;
			}
		};

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

	/**
	 * Smooth Scroll Handler.
	 */
	function initSmoothScroll() {
		const smoothLinks = document.querySelectorAll('.js-smooth-scroll');
		smoothLinks.forEach((link) => {
			link.addEventListener('click', (event) => {
				event.preventDefault();
				const targetId = link.getAttribute('href');
				const targetEl = document.querySelector(targetId);
				if (targetEl) {
					targetEl.scrollIntoView({ behavior: 'smooth' });
				}
			});
		});
	}

})();
