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');
            }
        });
    }
}

function CBCarouselNews(
	carousel,
	prevButton,
	nextButton,
	dotsContainer,
	transitionTime
) {
	let carouselIndex = 1;
	const slidesCount = carousel.querySelectorAll('li').length;

	function setupCarousel() {
		// Remove existing clones
		const existingClones = carousel.querySelectorAll('li.clone');
		existingClones.forEach(clone => clone.remove());

		const originalSlides = [...carousel.querySelectorAll('li')];

		const lastSlideClone = originalSlides[slidesCount - 1].cloneNode(true);
		lastSlideClone.classList.add('clone');
		carousel.insertBefore(lastSlideClone, originalSlides[0]);

		const firstSlideClone = originalSlides[0].cloneNode(true);
		firstSlideClone.classList.add('clone');
		carousel.appendChild(firstSlideClone);

		const gap = parseFloat(getComputedStyle(carousel).columnGap) || 0;

		const slideWidth = originalSlides[0].offsetWidth;
		const parentWidth = carousel.parentElement.offsetWidth;

		const offset = (parentWidth - slideWidth) / 2;
		const translateX = -carouselIndex * (slideWidth + gap) + offset;

		carousel.style.transition = 'none';
		carousel.style.transform = `translateX(${translateX}px)`;

		const allSlides = carousel.querySelectorAll('li');
		allSlides.forEach(slide => {
			slide.style.transition = 'opacity 0.5s ease';
		});

		setActiveSlide(carouselIndex);
	}

	function updateCarousel(slideIndex) {
		const parentWidth = carousel.parentElement.offsetWidth;
		const gap = parseFloat(getComputedStyle(carousel).columnGap) || 0;

		const allSlides = carousel.querySelectorAll('li:not(.clone)');
		const slideWidth = allSlides[0] ? allSlides[0].offsetWidth : carousel.querySelectorAll('li')[0].offsetWidth;

		const offset = (parentWidth - slideWidth) / 2;
		let translateX = -slideIndex * (slideWidth + gap) + offset;

		carousel.style.transition = 'transform 0.5s ease';
		carousel.style.transform = `translateX(${translateX}px)`;

		// Set active slide - if clone, set active for both clone and corresponding original
		if (slideIndex == slidesCount + 1) {
			// Clone of first slide - set active for both clone and first slide
			const allSlides = carousel.querySelectorAll('li');
			const originalSlides = carousel.querySelectorAll('li:not(.clone)');

			// Remove active from all slides first
			allSlides.forEach(slide => {
				slide.classList.remove('active');
				slide.style.transition = 'opacity 0.5s ease';
			});

			// Set active for clone (last slide)
			const cloneSlide = allSlides[allSlides.length - 1];
			if (cloneSlide) {
				cloneSlide.classList.add('active');
			}

			// Set active for original first slide
			if (originalSlides[0]) {
				originalSlides[0].classList.add('active');
			}
		} else if (slideIndex == 0) {
			// Clone of last slide - set active for both clone and last slide
			const allSlides = carousel.querySelectorAll('li');
			const originalSlides = carousel.querySelectorAll('li:not(.clone)');

			// Remove active from all slides first
			allSlides.forEach(slide => {
				slide.classList.remove('active');
				slide.style.transition = 'opacity 0.5s ease';
			});

			// Set active for clone (first slide)
			const cloneSlide = allSlides[0];
			if (cloneSlide) {
				cloneSlide.classList.add('active');
			}

			// Set active for original last slide
			if (originalSlides[slidesCount - 1]) {
				originalSlides[slidesCount - 1].classList.add('active');
			}
		} else {
			setActiveSlide(slideIndex);
		}

		carousel.addEventListener('transitionend', function handler(e) {
			if (e.target !== carousel) return;

			if (slideIndex == slidesCount + 1) {
				const allSlides = carousel.querySelectorAll('li');
				const originalSlides = carousel.querySelectorAll('li:not(.clone)');
				const targetSlide = originalSlides[carouselIndex - 1];

				allSlides.forEach(slide => {
					slide.classList.remove('active');
					slide.style.transition = 'none';
					slide.style.opacity = '0';
				});

				if (targetSlide) {
					targetSlide.classList.add('active');
					targetSlide.style.opacity = '1';
				}

				carousel.style.transition = 'none';
				const resetOffset = -1 * (slideWidth + gap) + offset;
				carousel.style.transform = `translateX(${resetOffset}px)`;

				requestAnimationFrame(() => {
					allSlides.forEach(slide => {
						slide.style.transition = '';
						slide.style.opacity = '';
					});
					if (targetSlide) {
						targetSlide.style.opacity = '';
					}
				});
			}
			if (slideIndex == 0) {
				const allSlides = carousel.querySelectorAll('li');
				const originalSlides = carousel.querySelectorAll('li:not(.clone)');
				const targetSlide = originalSlides[carouselIndex - 1];

				allSlides.forEach(slide => {
					slide.classList.remove('active');
					slide.style.transition = 'none';
					slide.style.opacity = '0';
				});

				if (targetSlide) {
					targetSlide.classList.add('active');
					targetSlide.style.opacity = '1';
				}

				carousel.style.transition = 'none';
				const resetOffset = -slidesCount * (slideWidth + gap) + offset;
				carousel.style.transform = `translateX(${resetOffset}px)`;

				requestAnimationFrame(() => {
					allSlides.forEach(slide => {
						slide.style.transition = '';
						slide.style.opacity = '';
					});
					if (targetSlide) {
						targetSlide.style.opacity = '';
					}
				});
			}
			carousel.removeEventListener('transitionend', handler);
		}, { once: true });
	}

	function nextSlide() {
		carouselIndex++;
		updateCarousel(carouselIndex);
		if (carouselIndex == slidesCount + 1)
			carouselIndex = 1;

		setActiveDots(carouselIndex);
	}

	function prevSlide() {
		carouselIndex--;
		updateCarousel(carouselIndex);
		if (carouselIndex == 0)
			carouselIndex = slidesCount;

		setActiveDots(carouselIndex);
	}

	function setActiveSlide(index) {
		const allSlides = carousel.querySelectorAll('li');
		allSlides.forEach(slide => {
			slide.classList.remove('active');
			slide.style.transition = 'opacity 0.5s ease';
		});

		const originalSlides = carousel.querySelectorAll('li:not(.clone)');
		if (originalSlides[index - 1]) {
			originalSlides[index - 1].classList.add('active');
		}
	}

	function setActiveDots(index) {
		const dots = dotsContainer.querySelectorAll('li');
		dots.forEach(el => {
			el.classList.remove('active');
		});

		dots[index - 1].classList.add('active');
	}

	function startAutoSlide() {
		if (slidesCount > 1 && typeof autoSlideInterval === 'undefined') {
			autoSlideInterval = setInterval(nextSlide, transitionTime * 1000);
		}
	}

	function stopAutoSlide() {
		if (typeof autoSlideInterval !== 'undefined') {
			clearInterval(autoSlideInterval);
			autoSlideInterval = undefined;
		}
	}

	prevButton.addEventListener('click', function () {
		prevSlide();
	});

	nextButton.addEventListener('click', function () {
		nextSlide();
	});

	dotsContainer.querySelectorAll('li').forEach((el, index) => {
		el.addEventListener('click', function () {
			carouselIndex = index + 1;
			updateCarousel(carouselIndex);

			this.parentElement.querySelectorAll('li').forEach(li => li.classList.remove('active'));
			this.classList.add('active');
		});
	})

	setupCarousel();
	setActiveDots(carouselIndex);
	setActiveSlide(carouselIndex);
	setTimeout(function () {
		startAutoSlide();
	}, transitionTime * 1000);

	carousel.addEventListener('mouseover', function () {
		stopAutoSlide();
	});

	carousel.addEventListener('mouseout', function () {
		if (typeof autoSlideInterval === 'undefined') {
			startAutoSlide();
		}
	});

	window.addEventListener('resize', function () {
		this.setTimeout(function () {
			setupCarousel();
			updateCarousel(carouselIndex);
		}, 500);
	});
}


let CBKeyDates = function () {
	function formatDateCompact(date) {
		const y = date.getFullYear();
		const m = String(date.getMonth() + 1).padStart(2, "0");
		const d = String(date.getDate()).padStart(2, "0");
		return `${y}${m}${d}`;
	}

	function addDays(date, days) {
		const d = new Date(date);
		d.setDate(d.getDate() + days);
		return d;
	}

	function addGoogleCalendar(title, date) {
		const start = formatDateCompact(date);
		const end = formatDateCompact(addDays(date, 1)); // all-day rule

		const url =
			`https://www.google.com/calendar/render?action=TEMPLATE` +
			`&text=${encodeURIComponent(title)}` +
			`&dates=${start}/${end}`;

		window.open(url, "_blank");
	}

	function addOutlookCalendar(title, date) {
		const start = date.toISOString().split("T")[0];
		const end = addDays(date, 1).toISOString().split("T")[0];

		const url =
			`https://outlook.live.com/calendar/0/deeplink/compose?path=/calendar/action/compose&rru=addevent` +
			`&subject=${encodeURIComponent(title)}` +
			`&startdt=${start}` +
			`&enddt=${end}` +
			`&allday=true`;

		window.open(url, "_blank");
	}

	return {
		addGoogleCalendar,
		addOutlookCalendar,
	}
}();