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


CBNavigationSecondary = new function () {
    this.init = function () {
        let els = document.querySelectorAll('section[rel="CBNavigationSecondary"] ul');
        els.forEach(el => {
            if (!el.classList.contains('loaded')) {
                el.addEventListener('wheel', function (event) {
                    if (event.deltaY !== 0) {
                        this.scrollBy({
                            left: event.deltaY,
                            behavior: 'smooth'
                        });
                        event.preventDefault();
                    }
                });
                el.classList.add('loaded');
            }
        });
    }
}

const CBFiguresCalloutMultiRow = function (element) {
	const counters = element.querySelectorAll('[rel="counter"]');
	if (!counters.length) return;

	function parseTarget(el) {
		const raw = (el.getAttribute('data-target') || el.textContent || '').trim();
		const cleaned = raw.replace(/[^0-9.\-]/g, '');
		const num = Number(cleaned);
		return Number.isFinite(num) ? num : 0;
	}

	function getDecimalsFromOriginal(el) {
		const raw = (el.getAttribute('data-target') || el.textContent || '').trim();
		const match = raw.match(/\.(\d+)/);
		return match ? match[1].length : 0;
	}

	function animateCount(el, durationMs = 1200) {
		if (el.dataset.counted === '1') return;
		el.dataset.counted = '1';

		const target = parseTarget(el);
		const decimals = getDecimalsFromOriginal(el);

		el.textContent = (0).toFixed(decimals);

		const start = performance.now();

		function tick(now) {
			const t = Math.min((now - start) / durationMs, 1);
			const eased = 1 - Math.pow(1 - t, 3);

			const current = target * eased;
			el.textContent = current.toFixed(decimals);

			if (t < 1) requestAnimationFrame(tick);
			else el.textContent = target.toFixed(decimals);
		}

		requestAnimationFrame(tick);
	}

	const observer = new IntersectionObserver((entries) => {
		for (const entry of entries) {
			if (entry.isIntersecting) {
				entry.target.dataset.counted = '0';
				animateCount(entry.target);
			} else {
				entry.target.dataset.counted = '0';
			}
		}
	}, {
		threshold: 0.35
	});

	counters.forEach(el => observer.observe(el));
}