class CBHeader {
	constructor(header, arrow_down, arrow_up) {
		this.header = header;
		this.logo = this.header.querySelector('a'); //Header part 1
		this.burgerBtn = this.header.querySelector('button'); //Header part 2
		this.mainMenu = this.header.querySelector('ul'); //Header part 3
		this.loginMenu = this.header.querySelector('nav'); //Header part 4
		this.arrow_down = arrow_down;
		this.arrow_up = arrow_up;
	}

	init() {
		window.addEventListener('resize', (e) => {
			this.checkResponsive();
		});
		this.checkResponsive();
		this.toggleMobileMenu();
	}

	checkResponsive() {
		const width = window.innerWidth;
		if (
			width <= 1100 && this.header.classList.contains('mobile') ||
			width > 1100 && !this.header.classList.contains('mobile')
		) {
			return;
		}

		//Remove the header content
		this.header.innerHTML = '';

		//Add the mobile menu and login menu to the mobile wrapper
		if (width <= 1100) {
			this.header.classList.add('mobile');
			let mobileWrapper = document.createElement('section');
			let mobileMenu = this.mainMenu.cloneNode(true);

			//Add arrow icons to the menu items that have children
			mobileMenu.querySelectorAll('li').forEach(el => {
				if (el.querySelector('ul') !== null) {
					el.querySelector('a').insertAdjacentHTML('afterend', `<button onclick="this.parentNode.classList.toggle('active');">${this.arrow_down}</button>`);
				}
			});

			//Add the mobile menu and login menu to the mobile wrapper
			mobileWrapper.append(mobileMenu, this.loginMenu);
			this.header.append(this.logo, this.burgerBtn, mobileWrapper);
			this.toggleMobileSubMenu();
		}

		//Add the desktop menu and login menu to the header
		if (width > 1100) {
			this.header.classList.remove('mobile');
			this.header.append(this.logo, this.mainMenu, this.loginMenu);
		}
	}

	toggleMobileMenu() {
		this.header.querySelector('button').addEventListener('click', (e) => {
			e.preventDefault();
			this.header.classList.toggle('active');

			//Close all submenus when the mobile menu is closed
			if (!this.header.classList.contains('active')) {
				this.header.querySelector('nav').querySelector('button').classList.remove('active');
				this.header.querySelectorAll('section > ul > li').forEach(el => {
					el.classList.remove('active');
				});
			}
		});
	}

	toggleMobileSubMenu() {
		// this.header.querySelectorAll('section > ul > li > a').forEach(el => {
		// 	const parent = el.parentElement;
		// 	if (parent.querySelector('ul'))
		// 		el.addEventListener('click', (e) => {
		// 			if (!parent.classList.contains('active')) {
		// 				e.preventDefault();
		// 				parent.classList.toggle('active');
		// 			}
		// 		});
		// });
	}
}

CBFooter = function () {
	//Handle scroll to anchor links with offset.
	function scrollToAnchor(elName) {
		const targetElement = document.querySelector(`a[name=${elName}]`);
		if (targetElement) {
			const headerOffset = 80;
			const elementPosition = targetElement.getBoundingClientRect().top + window.scrollY;
			const offsetPosition = elementPosition - headerOffset;
			window.scrollTo({
				top: offsetPosition,
				behavior: "smooth"
			});
		}
	}

	//Add event sto links with hash
	document.querySelectorAll('a[href^="#"]').forEach(anchor => {
		anchor.addEventListener("click", function (e) {
			e.preventDefault();
			const elName = this.getAttribute("href").substring(1);
			scrollToAnchor(elName);
		});
	});

	//Scroll to anchor if hash is present in URL
	if (window.location.hash) {
		setTimeout(() => {
			const elName = window.location.hash.substring(1);
			scrollToAnchor(elName);
		}, 100); // Small delay to ensure the page is loaded before scrolling
	}
}

function CBError(errors){
	var _errno=null;
	var _error=null;
	function errno(){return _errno;}
	function error(){return _error;}
	function reset(){_errno=null;error=null;}
	function set(errno,replaceObj,ret){
		_errno=errno;
		_error=errors[errno];
		for(let i in replaceObj){
			_error=_error.replace('{'+i+'}',replaceObj[i]);
		}
		if(typeof(ret)=='undefined'){ret=false;}
		return ret;
	}
	return {
		errno	:errno,
		error	:error,
		reset	:reset,
		set		:set
	}
}


let CBUnsubscribeToInsights = function (
	formElement,
	confirmModalElement,
	emailErrorElement,
	formErrorElement,
	recaptchaSiteKey,
) {
	function clearErrors() {
		if (emailErrorElement) {
			emailErrorElement.textContent = '';
			emailErrorElement.style.display = 'none';
		}
		if (formErrorElement) {
			formErrorElement.textContent = '';
			formErrorElement.style.display = 'none';
		}
	}

	function displayError(errorMessage, field) {
		if (field === 'email' && emailErrorElement) {
			emailErrorElement.textContent = errorMessage;
			emailErrorElement.style.display = 'block';
		} else if (formErrorElement) {
			formErrorElement.textContent = errorMessage;
			formErrorElement.style.display = 'block';
		}
	}


	function handleErrorResponse(response) {
		try {
			let errorData = JSON.parse(response);
			if (errorData.email) {
				displayError(errorData.email, 'email');
			}
			if (errorData.form) {
				displayError(errorData.form, 'form');
			} else if (errorData.message || errorData.error) {
				displayError(errorData.message || errorData.error, 'form');
			} else {
				displayError('An error occurred. Please try again.', 'form');
			}
		} catch (e) {
			displayError(response || 'An error occurred. Please try again.', 'form');
		}
	}

	function Ctrl_stateChange() {
		if (this.readyState === XMLHttpRequest.DONE) {
			let response = this.responseText.trim();
			
			if (this.status === 200 && response === 'Success') {
				if (confirmModalElement) {
					confirmModalElement.removeAttribute('hidden');
					confirmModalElement.showModal();
					document.body.style.overflow = 'hidden';
				}
				formElement.reset();
				return;
			}

			if (this.status === 200 || (this.status >= 400 && this.status < 500)) {
				handleErrorResponse(response);
			} else {
				displayError('An error occurred. Please try again.', 'form');
			}
		}
	}

	function Ctrl_formSubmit(token) {
		var FD = new FormData(formElement);
		FD.append('token', token);

		console.log('Ctrl_formSubmit', FD);
		clearErrors();
		Data_send(FD);
	}

	function Data_send(FD) {
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = Ctrl_stateChange;
		xhr.open('POST', window.location.href, true);
		xhr.send(FD);
	}

	formElement.addEventListener('submit', handleSubmit);

	function handleSubmit(e) {
		e.preventDefault();
		e.stopPropagation();
		if (!recaptchaSiteKey) {
			Ctrl_formSubmit('');
			return;
		}
		var recaptchaSK = recaptchaSiteKey
		grecaptcha.ready(function () {
			grecaptcha.execute(recaptchaSK, { action: 'submit' }).then(function (token) {
				Ctrl_formSubmit(token);
			});
		});
	}

	function closeConfirmModal(e) {
		if (e) {
			e.preventDefault();
			e.stopPropagation();
		}
		confirmModalElement.setAttribute('hidden', '');
		confirmModalElement.close();
		document.body.style.overflow = '';
	}

	confirmModalElement.querySelector('button[aria-label="Close"]').addEventListener('click', closeConfirmModal);

	confirmModalElement.addEventListener('click', function (event) {
		if (event.target === confirmModalElement) {
			closeConfirmModal(event);
		}
	});

	confirmModalElement.addEventListener('cancel', function (e) {
		e.preventDefault();
		closeConfirmModal();
	});
};
