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
	}
}


function CBContactForm(formElement,submitElement,successElement,enquiryElement,feedbackElements,inputElements,validationElements,recaptchaSiteKey){
	function View_clearValidationElements(){	for(let i in validationElements){validationElements[i].innerHTML='';}}
	function View_clearInputElements(){			for(let i in inputElements){inputElements[i].value='';}
												inputElements.enquiry_type.classList.remove('selected');}

	function View_displayError(field,message){	validationElements[field].innerHTML=message;}
	function View_displaySuccess(){				successElement.style.display='';	}

	function View_hideSuccess(){				successElement.style.display='none';	}

	function View_disableSubmission(){			submitElement.disabled=true;		}
	function View_disableFeedback(){			feedbackElements.feedback.classList.remove('enable');	}
	function View_disableElements(){			for(let field in inputElements){inputElements[field].disabled=true;}
												View_disableSubmission();}
	function View_enableSubmission(){			submitElement.disabled=false;	}
	function View_enableFeedback(){				feedbackElements.feedback.classList.add('enable');	}
	function View_enableElements(){				for(let field in inputElements){inputElements[field].disabled=false;}
												View_enableSubmission();}
	function View_feedbackText(msg){			feedbackElements.text.textContent=msg;				}

	function Ctrl_formSubmit(token){
		var FD=new FormData(formElement);
		FD.append('token',token);
		View_hideSuccess();
		View_clearValidationElements();
		View_disableElements();
		View_feedbackText('');
		View_enableFeedback();
		Data_send(FD);
	}
	function Ctrl_stateChange(){
		if(this.readyState==XMLHttpRequest.OPENED			){View_feedbackText('Your request is being sent to BSP'	);	return;}
		if(this.readyState==XMLHttpRequest.HEADERS_RECEIVED	){View_feedbackText('BSP has received your request'		);	return;}
		if(this.readyState==XMLHttpRequest.LOADING			){View_feedbackText('BSP is processing your request'	);	return;}
		if(this.readyState!=XMLHttpRequest.DONE){
/* @todo fulvio do something */
			return;
		}
		View_disableFeedback();
		View_enableElements();
		var success=this.responseText.trim()==='Success';
		if(this.status==200&&success){
			View_displaySuccess();
			View_clearInputElements();
			return;
		}
		if(this.status!=400){
			View_displayError('form','Could not process request. Please try again later.');
			return;
		}
		var res=JSON.parse(this.responseText);
		if(res===false){
			View_displayError('form','Invalid response format from the server.');
			return;
		}
		for(let field in res){
			View_displayError(field,res[field]);
		}
	}
	function Data_send(FD){
		var xhr=new XMLHttpRequest();
		xhr.onreadystatechange=Ctrl_stateChange;
		xhr.open('POST',window.location.href,true);
		xhr.send(FD);
	}

	enquiryElement.addEventListener('change',function(e){
		if(e.currentTarget.value===''){
			e.currentTarget.classList.remove('selected');
			return;
		}
		e.currentTarget.classList.add('selected');
	});
	formElement.addEventListener('submit',function(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);
			});
		});
	});
}
