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


let CBSearch = function (
	formElement,
	inputElement,
	errorElement,
	submitElement,
	autoSuggestionsElement,
	resultsTitleElement,
	categoryFilterElement,
	resultsListElement,
	loadMoreElement,
	arrowRightIcon
) {
	let maxResults = 12;
	let currentPage = 1;
	let maxPages = 0;
	const headerMenu = document.getElementById('menu-header');
	const topLevelItems = Array.from(
		headerMenu.querySelectorAll(':scope > li > a')
	).map(a => ({
		slug: a.getAttribute('href').replace(/\//g, ''),
		label: a.textContent.trim()
	}));
	console.log(topLevelItems);
	function View_clearValidationElements() { errorElement.innerHTML = ''; }
	function View_displayError(message) { errorElement.innerHTML = message; }


	function View_disableElements() {
		formElement.setAttribute('disabled', true);
		inputElement.setAttribute('disabled', true);
		submitElement.setAttribute('disabled', true);
	}

	function View_enableElements() {
		submitElement.removeAttribute('disabled');
		inputElement.removeAttribute('disabled');
		formElement.removeAttribute('disabled');
	}

	function View_displayResults(results) {
		resultsTitleElement.innerHTML = `Search results for <i>"${inputElement.value}"</i>`;
		resultsTitleElement.style.display = '';

		resultsListElement.style.display = 'block';
		resultsListElement.innerHTML = '';
		console.log(results);
		if (Object.keys(results).length === 0) {
			resultsListElement.innerHTML = '<li><h3><a>No results found</a></h3></li>';
			return;
		} else {
			currentPage = 1;
			maxPages = Math.ceil(Object.keys(results).length / maxResults);

			const arr = Object.entries(results);
			for (var i in arr) {
				const url = arr[i][0];
				const title = arr[i][1][0] == null ? "" : arr[i][1][0];
				const description = arr[i][1][1] == null ? "" : arr[i][1][1];
				const flag = arr[i][1][2];
				let heading_html = '';
				let buttons_html = '';
				let category = 'other';
				let category_label = 'Other';

				console.log(title, description, flag);
				switch (flag) {
					case 0:
						category = url.split('/').filter(Boolean)[0];
						if (!topLevelItems.find(item => item.slug === category)) {
							category = 'other';
							category_label = 'Other';
						} else {
							category_label = topLevelItems.find(item => item.slug === category).label;
						}
						heading_html = `<span>${category_label}</span><h3>${title}</h3>`;
						buttons_html =
							`<a href="/${url}">Read More ${arrowRightIcon}</a>`;
						break;
					case 1:
						heading_html = `<span>Other</span><h3>${title}</h3>`;
						buttons_html = `
						<a href="/${url}" download="${title}">Download PDF ${arrowRightIcon}</a>
						<a href="/${url}">View Report ${arrowRightIcon}</a>`;
						break;
					case 2:
						break;
				}

				if (description !== null) {
					heading_html += `<p>${description}</p>`;
				}
				const extra_css = i >= 12 ? 'style="display: none;"' : '';
				resultsListElement.innerHTML +=
					`<li ${extra_css} data-category="${category}">
						${heading_html}
						${buttons_html}
					</li>`;
				if (i >= maxResults) {
					loadMoreElement.style.display = '';
				}
			}

			categoryFilterElement.innerHTML = '<option value="">All</option>';
			for (var item of topLevelItems) {
				categoryFilterElement.innerHTML += `<option value="${item.slug}">${item.label}</option>`;
			}
			categoryFilterElement.innerHTML += `<option value="other">Other</option>`;
			categoryFilterElement.style.display = 'flex';
		}
	}

	function Ctrl_formSubmit() {
		View_clearValidationElements();
		View_disableElements();
		Data_send();
	}
	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) {
			return;
		}

		View_enableElements();
		var success = this.responseText.trim() === 'Success';
		if (this.status == 200 && success) {
			//			View_displaySuccess();
			View_clearInputElements();
			return;
		}
		if (this.status != 200) {
			View_displayError('Could not process request. Please try again later.');
			return;
		}
		var res = JSON.parse(this.responseText);
		if (res === false) {
			View_displayError('Invalid response format from the server.');
			return;
		}
		View_displayResults(res);
	}
	function Data_send() {
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = Ctrl_stateChange;
		xhr.open('POST', window.location.href, true);
		xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xhr.send('k=' + encodeURIComponent(inputElement.value));
	}

	function View_loadMoreResults() {
		const results = resultsListElement.querySelectorAll('li');
		for (var i = currentPage * maxResults; i < (currentPage + 1) * maxResults; i++) {
			if (i >= results.length) {
				break;
			}
			results[i].style.display = '';
		}
		currentPage++;
		console.log(currentPage, maxPages);
		if (currentPage >= maxPages) {
			loadMoreElement.innerHTML = 'End results';
			loadMoreElement.disabled = true;
		}
	}

	function Ctrl_suggestionClick(suggestion) {
		inputElement.value = suggestion;
	}

	function View_loadAutoSuggestions() {
		const dummy_suggestions = [
			'Open a savings account',
			'Report a card lost or stolen',
			'Check your account balance',
			'Make a payment',
			'Transfer money',
			'Find branch or ATM',
			'Foreign Exchange',
			'Send Money Overseas'
		];
		let dummy_suggestions_html = '';
		for (var i = 0; i < dummy_suggestions.length; i++) {
			dummy_suggestions_html += `<li><button onclick="this.parentElement.parentElement.parentElement.querySelector('input').value = '${dummy_suggestions[i]}';this.parentElement.parentElement.parentElement.querySelector('button').click();this.parentElement.parentElement.style.display = 'none';">${dummy_suggestions[i]}</button></li>`;
		}
		autoSuggestionsElement.innerHTML = dummy_suggestions_html;
		autoSuggestionsElement.style.display = 'block';
	}

	function View_filterResults() {
		const selectedCategory = categoryFilterElement.value;
		console.log(selectedCategory);
		const results = resultsListElement.querySelectorAll('li');
		for (var i = 0; i < results.length; i++) {
			if (selectedCategory === '') {
				if (i >= maxResults) {
					results[i].style.display = 'none';
				} else {
					results[i].style.display = '';
				}
			} else {
				if (results[i].dataset.category !== selectedCategory) {
					results[i].style.display = 'none';
				} else {
					results[i].style.display = '';
				}
			}
		}
		loadMoreElement.style.display = selectedCategory === '' ? '' : 'none';
	}

	const params = new URLSearchParams(window.location.search);
	const keyword = params.get('k');
	if (keyword) {
		inputElement.value = keyword;
		Ctrl_formSubmit();
	}

	inputElement.addEventListener('blur', function (e) {
		e.preventDefault();
		e.stopPropagation();
		setTimeout(function () {
			autoSuggestionsElement.style.display = 'none';
		}, 500);
	});

	inputElement.addEventListener('keyup', function (e) {
		e.preventDefault();
		e.stopPropagation();

		const value = inputElement.value;
		if (value.length < 3) {
			autoSuggestionsElement.style.display = 'none';
			return;
		}
		View_loadAutoSuggestions();
	});

	formElement.addEventListener('submit', function (e) {
		e.preventDefault();
		e.stopPropagation();
		Ctrl_formSubmit();
	});

	categoryFilterElement.addEventListener('change', function (e) {
		e.preventDefault();
		e.stopPropagation();
		View_filterResults();
	});


	loadMoreElement.addEventListener('click', function (e) {
		e.preventDefault();
		e.stopPropagation();
		View_loadMoreResults();
	});

}
