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 CBCardsGrid(cardsGrid, data, iconNextEntities, iconPreEntities) {
    const iconNext = decodeHTMLEntities(iconNextEntities);
    const iconPre = decodeHTMLEntities(iconPreEntities);
    let jsonData = Array.isArray(data) ? data : [];
    const itemsPerPage = 6;
    let currentPage = 1;
    let totalPages = Math.ceil(jsonData.length / itemsPerPage);

    const container = cardsGrid.querySelector("article");
    const paginationContainer = cardsGrid.querySelector("ul");
    const template = document.querySelector('script[rel="CBCardsGrid_template"]').textContent;

    function renderItems() {
        container.innerHTML = "";
        const start = (currentPage - 1) * itemsPerPage;
        const paginatedItems = jsonData.slice(start, start + itemsPerPage);

        for (let i = 0; i < paginatedItems.length; i++) {
            const item = paginatedItems[i];
            let itemHTML = template
                .replace(/{link}/g, item.link)
                .replace('{image_url}', item.image ? item.image.url.replace(/\\/g, "/") : "")
                .replace('{image_alt}', item.image ? item.image.alt || "" : "")
                .replace('{image_width}', item.image ? item.image.width || 0 : 0)
                .replace('{image_height}', item.image ? item.image.height || 0 : 0)
                .replace('{title}', item.title)
                .replace('{post_date}', item.post_date)
                .replace('{label}', item.label);
            container.innerHTML += itemHTML;
        }
    }

    function createPageItem(label, page, isDisabled = false, isActive = false, isIcon = false) {
        const li = document.createElement("li");
        const button = document.createElement("button");
        button.innerHTML = isIcon ? label : label;
        if (isDisabled) button.classList.add("disabled");
        if (isActive) button.classList.add("active");
        if (!isDisabled) {
            button.dataset.page = page;
            button.addEventListener("click", function (e) {
                e.preventDefault();
                if (button.classList.contains("disabled")) return;
                currentPage = page;
                renderItems();
                renderPagination();
            });
        }
        li.appendChild(button);
        return li;
    }

    function renderPagination() {
        paginationContainer.innerHTML = "";
        if (totalPages <= 1) return;

        paginationContainer.appendChild(createPageItem(iconPre, currentPage - 1, currentPage == 1, false, true));

        let pages = [];
        switch (true) {
            case totalPages <= 4:
                for (let i = 1; i <= totalPages; i++) pages.push(i);
                break;
            case currentPage <= 2:
                pages = [1, 2, 3, "...", totalPages];
                break;
            case currentPage >= totalPages - 1:
                pages = [1, "...", totalPages - 2, totalPages - 1, totalPages];
                break;
            default:
                pages = [1, "...", currentPage - 1, currentPage, currentPage + 1, "...", totalPages];
                break;
        }

        for (let j = 0; j < pages.length; j++) {
            let page = pages[j];
            if (page == "...") {
                const li = document.createElement("li");
                li.innerHTML = "&#9679;&#9679;&#9679;";
                li.style.opacity = "0.1";
                paginationContainer.appendChild(li);
            } else {
                paginationContainer.appendChild(createPageItem(page, page, false, page == currentPage));
            }
        }

        paginationContainer.appendChild(createPageItem(iconNext, currentPage + 1, currentPage == totalPages, false, true));
    }

    function decodeHTMLEntities(text) {
        const doc = new DOMParser().parseFromString(text, "text/html");
        return doc.documentElement.textContent;
    }

    if (!container || !paginationContainer || !template) {
        return;
    }
    renderItems();
    renderPagination();

    function resetPagination() {
        currentPage = 1;
        renderItems();
        renderPagination();
    }

    this.updateData = function (newData) {
        if (!Array.isArray(newData)) {
            return;
        }
        jsonData = [...newData];
        totalPages = Math.ceil(jsonData.length / itemsPerPage);
        resetPagination();
    };

    this.refreshGrid = function () {
        renderItems();
        renderPagination();
    };

    this.goToPage = function (page) {
        if (typeof page !== "number" || page < 1 || page > totalPages) {
            return;
        }
        currentPage = page;
        renderItems();
        renderPagination();
    };

    this.getCurrentPage = function () {
        return currentPage;
    };

    this.getTotalPages = function () {
        return totalPages;
    };

    this.isFirstPage = function () {
        return currentPage == 1;
    };

    this.isLastPage = function () {
        return currentPage == totalPages;
    };
}
