/**
 * Custom JS for theme elements
 */

/**
 * WooCommerce active class for category list
 */
let url = window.location.href;
let catLink = document.querySelectorAll(".wc-block-product-categories-list li a");
catLink.forEach((item) => {
	if (item.href === url) {
		item.classList.add("active");
	}
});

//T&C box checked on click
let threadwearsCheckDivTerms = document.querySelector('.woocommerce-terms-and-conditions-checkbox-text');
if (threadwearsCheckDivTerms !== null) {
	threadwearsCheckDivTerms.onclick = function (e) {
		this.classList.toggle('checked');
	}
}


// Product Variation Custom js

document.addEventListener('DOMContentLoaded', function () {

	document.querySelectorAll('.variations select').forEach(function (select) {

		var wrapper = document.createElement('div');
		wrapper.className = 'custom-variation';

		select.querySelectorAll('option').forEach(function (option) {

			var value = option.value;
			var text = option.textContent;

			if (!value) return;

			var btn = document.createElement('div');
			btn.className = 'variation-option';
			btn.setAttribute('data-value', value);
			btn.textContent = text;

			btn.addEventListener('click', function () {
				wrapper.querySelectorAll('.variation-option')
					.forEach(el => el.classList.remove('active'));

				btn.classList.add('active');

				select.value = value;
				select.dispatchEvent(new Event('change', { bubbles: true }));
			});

			wrapper.appendChild(btn);
		});

		select.after(wrapper);
	});

	// Clear button fix 
	document.addEventListener('click', function (e) {
		if (e.target.closest('.reset_variations')) {
			document.querySelectorAll('.variation-option')
				.forEach(el => el.classList.remove('active'));
		}
	});

});

function threadwearsCartUpdate() {
	let btnTrigger = document.querySelector('button[name="update_cart"]');
	if (btnTrigger !== null) {
		btnTrigger.addEventListener('click', function () {
			setTimeout(function () {
				threadwearsQtyChange();
			}, 5000);
			setTimeout(function () {
				threadwearsCartUpdate();
			}, 5000);
		});
	}
}
threadwearsCartUpdate();


// Cusstom Checkboxs for Checkout Page
let checkDivAccount = document.querySelector('.woocommerce-account-fields .checkbox span');
if (checkDivAccount !== null) {
	checkDivAccount.onclick = function (e) {
		this.classList.toggle('checked');
	}
}

document.addEventListener('click', function (event) {
	if (event.target.classList.contains('woocommerce-terms-and-conditions-checkbox-text')) {
		event.target.classList.toggle('checked');
	}
});

let checkDivShipping = document.querySelector('.woocommerce-shipping-fields .checkbox span');
if (checkDivShipping !== null) {
	checkDivShipping.onclick = function (e) {
		this.classList.toggle('checked');
	}
}

// Sticky Mobile Icon Menu body padding bottom
let fixedMenu = document.querySelector('.wp-mobile-icon-menu');
if (fixedMenu !== null) {
	document.body.style.paddingBottom = `${fixedMenu.clientHeight}px`;
}
