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 CBPromoCarousel(carousel, prevButton, nextButton, ulSlide, slides, navItems, transition_time) {
    if (!slides.length) return;

    // Clone first and last slides for infinite looping
    const firstSlideClone = slides[0].cloneNode(true);
    firstSlideClone.classList.add('first-slide-clone');
    const lastSlideClone = slides[slides.length - 1].cloneNode(true);
    lastSlideClone.classList.add('last-slide-clone');

    ulSlide.appendChild(firstSlideClone);
    ulSlide.insertBefore(lastSlideClone, slides[0]);

    let currentIndex = 1;
    let autoSlideInterval;
    let autoSliding = true;

    function getSlideWidth() {
        return carousel.offsetWidth; // Keep slides full width
    }

    function setUlSlideDimensions() {
        const slideWidth = carousel.offsetWidth;
        const gap = parseFloat(getComputedStyle(ulSlide).gap) || 0;
        const totalSlides = ulSlide.querySelectorAll('li');

        totalSlides.forEach(slide => {
            if (!slide.classList.contains('slide-item')) return;
            slide.style.width = `${slideWidth}px`; // Maintain full width
        });

        // Properly calculate ulSlide width, including gaps
        ulSlide.style.width = `${(totalSlides.length * slideWidth) + ((totalSlides.length - 1) * gap)}px`;
        ulSlide.style.transform = `translate3d(${-currentIndex * (slideWidth + gap)}px, 0, 0)`; // Fix alignment on load
    }

    function updateCarousel() {
        const slideWidth = getSlideWidth();
        const gap = parseFloat(getComputedStyle(ulSlide).gap) || 0;

        // Fix floating precision errors by rounding
        const translateX = Math.round(-(currentIndex * (slideWidth + gap)));

        ulSlide.style.transition = 'transform 0.7s ease-in-out';
        ulSlide.style.transform = `translate3d(${translateX}px, 0, 0)`;

        navItems.forEach(nav => nav.classList.remove('active'));
        slides.forEach(slide => slide.classList.remove('active'));

        if (currentIndex === 0) {
            setTimeout(() => {
                ulSlide.style.transition = 'none';
                currentIndex = slides.length;
                ulSlide.style.transform = `translate3d(${Math.round(-currentIndex * (slideWidth + gap))}px, 0, 0)`;
            }, 700);
            navItems[navItems.length - 1]?.classList.add('active');
        } else if (currentIndex === slides.length + 1) {
            setTimeout(() => {
                ulSlide.style.transition = 'none';
                currentIndex = 1;
                ulSlide.style.transform = `translate3d(${Math.round(-currentIndex * (slideWidth + gap))}px, 0, 0)`;
            }, 700);
            navItems[0]?.classList.add('active');
        } else {
            slides[currentIndex - 1]?.classList.add('active');
            navItems[currentIndex - 1]?.classList.add('active');
        }
    }

    function nextSlide() {
        currentIndex++;
        updateCarousel();
    }

    function prevSlide() {
        currentIndex--;
        updateCarousel();
    }

    function startAutoSlide() {
        if (autoSliding && slides.length > 1 && !autoSlideInterval) {
            autoSlideInterval = setInterval(nextSlide, transition_time);
        }
    }

    function stopAutoSlide() {
        clearInterval(autoSlideInterval);
        autoSlideInterval = undefined;
    }

    prevButton.forEach(el => {
        el.addEventListener('click', () => {
            stopAutoSlide();
            autoSliding = false;
            prevSlide();
        });
    });

    nextButton.forEach(el => {
        el.addEventListener('click', () => {
            stopAutoSlide();
            autoSliding = false;
            nextSlide();
        });
    });

    if (navItems.length > 1) {
        navItems.forEach((dot, index) => {
            dot.addEventListener('click', () => {
                stopAutoSlide();
                autoSliding = false;
                currentIndex = index + 1;
                updateCarousel();
            });
        });
    }

    carousel.addEventListener('mouseover', stopAutoSlide);
    carousel.addEventListener('mouseout', () => {
        if (autoSliding) startAutoSlide();
    });

    let touchStartX = 0;
    let touchEndX = 0;
    if (slides.length > 1) {
        carousel.addEventListener('touchstart', e => {
            stopAutoSlide();
            touchStartX = e.changedTouches[0].screenX;
        });
        carousel.addEventListener('touchend', e => {
            touchEndX = e.changedTouches[0].screenX;
            if (touchStartX - touchEndX > 50) {
                nextSlide();
            } else if (touchEndX - touchStartX > 50) {
                prevSlide();
            }
            autoSliding = false;
            startAutoSlide();
        });
    }

    setTimeout(() => {
        setUlSlideDimensions();
        updateCarousel();
        startAutoSlide();
    }, 100);

    window.addEventListener('resize', () => {
        setUlSlideDimensions();
        updateCarousel();
    });
}
