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


class CBJobsList {
    constructor({ locationFilter, departmentFilter, jobList, paginationList, data }) {
        this.locationFilter = locationFilter;
        this.departmentFilter = departmentFilter;
        this.jobList = jobList;
        this.paginationList = paginationList;
        this.data = Array.isArray(data) ? data : [];
        this.page = 1;
        this.filteredData = [];
        this.init();
        this.filterChange();
    }

    init() {
        if (!(this.locationFilter instanceof HTMLElement)) return;
        if (!(this.departmentFilter instanceof HTMLElement)) return;

        this.locationFilter.addEventListener('change', () => {
            this.page = 1;
            this.filterChange();
        });

        this.departmentFilter.addEventListener('change', () => {
            this.page = 1;
            this.filterChange();
        });
    }

    filterChange() {
        const location = String(this.locationFilter?.value || '');
        const department = String(this.departmentFilter?.value || '');
        const job_tpl = document.querySelector('script[rel="CBJobList_template"]')?.textContent;

        if (!job_tpl) return;

        this.filteredData = this.data.filter((el) =>
            (el.location == location || location == '') &&
            (el.department == department || department == '')
        );

        const max_page = Math.ceil(this.filteredData.length / 3);
        if (this.page > max_page) {
            this.page = max_page > 0 ? max_page : 1;
        }

        this.renderJobs();
        this.renderPagination();
    }

    renderJobs() {
        const job_tpl = document.querySelector('script[rel="CBJobList_template"]')?.textContent;
        if (!job_tpl) return;

        const start = (this.page - 1) * 3;
        const end = start + 3;
        const jobs = this.filteredData.slice(start, end);

        if (jobs.length == 0) {
            this.jobList.innerHTML = '<li>No jobs found.</li>';
            return;
        }

        this.jobList.innerHTML = jobs
            .map((el) =>
                job_tpl
                    .replace('{title}', el.title || '')
                    .replace('{department}', el.department || '')
                    .replace('{excerpt}', el.excerpt || '')
                    .replace('{post_date}', el.post_date || '')
                    .replace('{location}', el.location || '')
                    .replace('{details}', el.details || '')
                    .replace('{reference}', el.reference || '')
            )
            .join('');
    }

    renderPagination() {
        const count = this.filteredData.length;
        const max_page = Math.ceil(count / 3);

        if (max_page <= 1) {
            this.paginationList.style.display = 'none';
            return;
        }
        this.paginationList.style.display = 'flex';

        const pagination_tpl = document.querySelector('script[rel="CBJobList_pagination"]')?.textContent;
        if (!pagination_tpl) return;

        this.paginationList.innerHTML = pagination_tpl.replace('{pagination}', this.getPaginationHtml(max_page));

        const prevBtn = this.paginationList.querySelector('.prev');
        const nextBtn = this.paginationList.querySelector('.next');

        if (prevBtn) prevBtn.disabled = this.page == 1;
        if (nextBtn) nextBtn.disabled = this.page == max_page;

        prevBtn?.addEventListener('click', (e) => {
            e.preventDefault();
            if (this.page > 1) {
                this.page--;
                this.renderJobs();
                this.renderPagination();
            }
        });

        nextBtn?.addEventListener('click', (e) => {
            e.preventDefault();
            if (this.page < max_page) {
                this.page++;
                this.renderJobs();
                this.renderPagination();
            }
        });

        this.paginationList.querySelectorAll('button[data-page]').forEach((el) => {
            el.addEventListener('click', (e) => {
                e.preventDefault();
                const newPage = parseInt(el.dataset.page, 10);
                if (!isNaN(newPage) && newPage >= 1 && newPage <= max_page) {
                    this.page = newPage;
                    this.renderJobs();
                    this.renderPagination();
                }
            });
        });
    }

    getPaginationHtml(max_page) {
        let pages = [];

        if (max_page <= 5) {
            for (let i = 1; i <= max_page; i++) pages.push(i);
        } else {
            if (this.page == 1) {
                pages = [1, 2, 3, '...', max_page];
            } else if (this.page == 2) {
                pages = [1, 2, 3, 4, '...', max_page];
            } else if (this.page == 3) {
                pages = [1, '...', 2, 3, 4, '...', max_page];
            } else if (this.page == max_page - 2) {
                pages = [1, '...', this.page - 1, this.page, this.page + 1, max_page];
            } else if (this.page == max_page - 1) {
                pages = [1, '...', max_page - 2, max_page - 1, max_page];
            } else if (this.page == max_page) {
                pages = [1, '...', max_page - 2, max_page - 1, max_page];
            } else {
                pages = [1, '...', this.page - 1, this.page, this.page + 1, '...', max_page];
            }
        }

        return pages
            .map((page) =>
                page == '...'
                    ? '<li><span style="opacity: 0.2">●●●</span></li>'
                    : `<li><button data-page="${page}" ${page == this.page ? 'class="active"' : ''}>${page}</button></li>`
            )
            .join('');
    }
}
