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 CBTableWithLinks(listElement, filterElement, navElement, rowTemplate, navTemplate, navItemTemplate, data, pageLength) {
    function sprintf(template, ...args) {
        return template.replace(/%\$(\d+)s/g, function (_, index) { return args[index - 1] || ""; });
    }

    function attachNavClickHandlers(data) {
        var buttons = navElement.querySelectorAll('button');
        for (var i = 0; i < buttons.length; i++) {
            try {
                buttons[i].addEventListener('click', function (e) {
                    e.preventDefault();
                    var pageNum = parseInt(this.dataset.page, 10);
                    if (!isNaN(pageNum)) {
                        populate(data, pageNum);
                    }
                });
            } catch (error) {

            }
        }
    }

    function generatePagination(currentPage, totalPages) {
        var pages = [];
        pages.push(sprintf(navItemTemplate, 1, currentPage === 1 ? "class=active" : ""));

        if (totalPages <= 4) {
            for (let i = 2; i <= totalPages; i++) {
                pages.push(sprintf(navItemTemplate, i, i === currentPage ? "class=active" : ""));
            }
        } else {
            if (currentPage <= 2) {
                pages.push(sprintf(navItemTemplate, 2, currentPage === 2 ? "class=active" : ""));
                pages.push(sprintf(navItemTemplate, 3, currentPage === 3 ? "class=active" : ""));
                pages.push("<li><span></span><span></span><span></span></li>");
            } else if (currentPage >= totalPages - 1) {
                pages.push("<li><span></span><span></span><span></span></li>");
                pages.push(sprintf(navItemTemplate, totalPages - 2, currentPage === totalPages - 2 ? "class=active" : ""));
                pages.push(sprintf(navItemTemplate, totalPages - 1, currentPage === totalPages - 1 ? "class=active" : ""));
            } else {
                pages.push("<li><span></span><span></span><span></span></li>");
                pages.push(sprintf(navItemTemplate, currentPage - 1, ""));
                pages.push(sprintf(navItemTemplate, currentPage, "class=active"));
                pages.push(sprintf(navItemTemplate, currentPage + 1, ""));
                pages.push("<li><span></span><span></span><span></span></li>");
            }

            pages.push(sprintf(navItemTemplate, totalPages, currentPage === totalPages ? "class=active" : ""));
        }

        return pages.join("\n");
    }

    function populate(data, currentPage = 1, year = 0) {
        let filteredData = [];
        Object.keys(data).forEach(key => {
            if (data[key].year == year || year == 0)
                filteredData.push(data[key]);
                console.log(data[key]);
        });
        var totalItems = filteredData.length;
        var totalPages = Math.ceil(totalItems / pageLength);
        var startIdx = (currentPage - 1) * pageLength;
        var pagedData = filteredData.slice(startIdx, startIdx + pageLength);

        let contents = pagedData.map(function (item, index) {
            return sprintf(rowTemplate, item[0], item[2], item[1], Math.floor(index / pageLength) + 1);
        }).join("\n");
        listElement.innerHTML = contents;

        if (totalPages > 1) {
            var prevPage = Math.max(1, currentPage - 1);
            var nextPage = Math.min(totalPages, currentPage + 1);
            navElement.innerHTML = sprintf(navTemplate, prevPage, generatePagination(currentPage, totalPages), nextPage);
            attachNavClickHandlers(filteredData);
        } else {
            navElement.innerHTML = "";
        }
    }

    filterElement.addEventListener('change', function () {
        populate(data, 1, filterElement.value);
    });

    populate(data, 1);
}


function CBSubscribeToInsightsModal(
	trigger,
	modal,
	closeButton,
	formElement,
	submitElement,
	inputElements,
	validationElements,
	confirmModal,
	confirmCloseButton,
	recaptchaSiteKey,
	feedbackElement,
) {
	// View functions
	function View_clearValidationElements() {
		if (!validationElements) return;
		for (var i in validationElements) {
			if (validationElements[i]) {
				validationElements[i].innerHTML = '';
			}
		}
	}

	function View_clearInputElements() {
		if (!inputElements) return;
		for (var i in inputElements) {
			if (inputElements[i]) {
				inputElements[i].value = '';
				if (inputElements[i].type === 'checkbox') {
					inputElements[i].checked = false;
				}
			}
		}
	}

	function View_displayError(field, message) {
		if (validationElements && validationElements[field]) {
			validationElements[field].innerHTML = message;
		}
	}

	function View_disableSubmission() {
		if (submitElement) {
			submitElement.disabled = true;
		}
		feedbackElement.style.display = 'flex';
	}

	function View_enableSubmission() {
		if (submitElement) {
			submitElement.disabled = false;
		}
		feedbackElement.style.display = 'none';
	}

	function View_disableElements() {
		if (inputElements) {
			for (var field in inputElements) {
				if (inputElements[field]) {
					inputElements[field].disabled = true;
				}
			}
		}
		View_disableSubmission();
	}

	function View_enableElements() {
		if (inputElements) {
			for (var field in inputElements) {
				if (inputElements[field]) {
					inputElements[field].disabled = false;
				}
			}
		}
		View_enableSubmission();
	}

	function openModal() {
		modal.showModal();
		document.body.style.overflow = 'hidden';
	}

	function closeModal() {
		modal.close();
		document.body.style.overflow = '';
		View_clearValidationElements();
		View_clearInputElements();
	}

	// Controller functions
	function Ctrl_stateChange() {
		if (this.readyState !== XMLHttpRequest.DONE) {
			return;
		}
		View_enableElements();

		var responseText = this.responseText.trim();

		// Success case
		if (this.status === 200 && responseText === 'Success') {
			closeModal();
			if (confirmModal) {
				confirmModal.removeAttribute('hidden');
				confirmModal.showModal();
			}
			return;
		}

		// Handle validation errors (try to parse JSON)
		try {
			var res = JSON.parse(responseText);
			if (res && typeof res === 'object') {
				for (var field in res) {
					View_displayError(field, res[field]);
				}
				return;
			}
		} catch (e) {
			// Not JSON, show generic error
		}

		View_displayError('form', 'Could not process request. Please try again later.');
	}

	function Ctrl_formSubmit(token) {
		var FD = new FormData(formElement);
		FD.append('token', token);
		View_clearValidationElements();
		View_disableElements();
		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);
	}

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

	// Open modal on trigger click
	trigger.addEventListener('click', function (e) {
		e.preventDefault();
		openModal();
	});

	// Close modal on close button click
	if (closeButton) {
		closeButton.addEventListener('click', closeModal);
	}

	// Close modal when clicking outside (on backdrop)
	modal.addEventListener('cancel', function (event) {
		event.preventDefault();
		closeModal();
	});

	// Additional click handler for backdrop (fallback)
	modal.addEventListener('click', function (event) {
		if (event.target === modal) {
			var formRect = formElement.getBoundingClientRect();
			var clickX = event.clientX;
			var clickY = event.clientY;
			var isOutsideForm = clickX < formRect.left ||
				clickX > formRect.right ||
				clickY < formRect.top ||
				clickY > formRect.bottom;

			if (isOutsideForm) {
				closeModal();
			}
		}
	});

	// Form submit handler
	if (formElement) {
		formElement.addEventListener('submit', handleSubmit);
	}


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

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

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