const convertPath = (path, toSlash = true) =>
		path.replaceAll(toSlash ? '---' : '/', toSlash ? '/' : '---');
		
		const transitionsEnabled = (element) => {
		const { transitionDuration, transitionDelay } = window.getComputedStyle(element);
		
		const parseTime = (timeString) => {
		const value = parseFloat(timeString);
		if (isNaN(value)) return 0;
		return timeString.includes('ms') ? value : value * 1000;
		};
		
		const durations = transitionDuration.split(',').map((s) => parseTime(s.trim()));
		const delays = transitionDelay.split(',').map((s) => parseTime(s.trim()));
		const totalDurations = durations.map(
		(duration, i) => duration + (delays[i % delays.length] || 0)
		);
		return totalDurations.some((total) => total > 0);
		};
		
		// Read and parse the sections JSON
		let sections = {};
		const sectionsDataScript = document.getElementById('dr-headerfooter');
		if (sectionsDataScript) {
		try {
		sections = JSON.parse(sectionsDataScript.textContent);
		console.log('Header/Footer configuration loaded:', sections);
		} catch (error) {
		console.error('Error parsing sections JSON:', error);
		}
		} else {
		console.warn('No dr-headerfooter script found. Using default settings.');
		}
		
		// Function to manage header and footer visibility based on section settings
		const manageHeaderFooterVisibility = (sectionId) => {
		const header = document.getElementById('header');
		const footer = document.getElementById('footer');
		
		if (!header || !footer) {
		console.warn('Header or footer element not found.');
		return;
		}
		
		// Retrieve settings for the current section, default to false if not defined
		const sectionSettings = sections[sectionId] || { hideHeader: false, hideFooter: false };
		
		if (sectionSettings.hideHeader) {
		header.classList.add('hidden');
		header.style.display = 'none';
		} else {
		header.classList.remove('hidden');
		header.style.display = '';
		}
		
		if (sectionSettings.hideFooter) {
		footer.classList.add('hidden');
		footer.style.display = 'none';
		} else {
		footer.classList.remove('hidden');
		footer.style.display = '';
		}
		};
		
		// Function to activate a target section
		const myActivateSection = async (target) => {
		const activeSection = document.querySelector('section.active');
		if (activeSection && activeSection !== target) {
		const transitionsActive = transitionsEnabled(activeSection);
		if (transitionsActive) {
		activeSection.classList.add('inactive');
		activeSection.classList.remove('active');
		
		await new Promise((resolve) => {
		const handleTransitionEnd = (event) => {
		if (event.propertyName === 'opacity') {
		activeSection.style.display = 'none';
		activeSection.removeEventListener('transitionend', handleTransitionEnd);
		resolve();
		}
		};
		activeSection.addEventListener('transitionend', handleTransitionEnd);
		});
		
		activateTargetSection(target);
		} else {
		activeSection.style.display = 'none';
		activeSection.classList.remove('active');
		activateTargetSection(target, false);
		}
		} else if (!activeSection) {
		activateTargetSection(target, false);
		} else if (activeSection === target) {
		target.style.display = '';
		}
		};
		
		// Function to activate the target section and manage header/footer
		const activateTargetSection = (target, useTransitions = true) => {
		if (useTransitions && transitionsEnabled(target)) {
		target.classList.add('inactive');
		target.style.display = '';
		target.offsetHeight;
		
		target.classList.add('active');
		target.classList.remove('inactive');
		
		const { scrollHeight, scrollWidth } = target;
		Object.assign(target.style, {
		minHeight: `${scrollHeight}px`,
		maxHeight: `${scrollHeight}px`,
		minWidth: `${scrollWidth}px`,
		maxWidth: `${scrollWidth}px`,
		});
		
		target.addEventListener(
		'transitionend',
		function targetTransitionEnd(event) {
		if (event.propertyName === 'opacity') {
		Object.assign(target.style, {
		minHeight: '',
		maxHeight: '',
		minWidth: '',
		maxWidth: '',
		});
		target.removeEventListener('transitionend', targetTransitionEnd);
		}
		}
		);
		} else {
		target.style.display = '';
		target.classList.add('active');
		}
		
		// After activating the section, manage header and footer visibility
		const sectionId = target.id.replace('-section', '');
		manageHeaderFooterVisibility(sectionId);
		};
		
		// Function to navigate to a specific section
		const navigateToSection = (path, replaceState = false) => {
		const cleanPath = convertPath(path),
		sectionId = ['', 'home'].includes(cleanPath.replace(/^\//, ''))
		? 'home'
		: convertPath(cleanPath.replace(/^\//, ''), false),
		targetSection = document.getElementById(`${sectionId}-section`);
		
		console.log(`navigateToSection called with path: ${path}`);
		console.log(`Clean Path: ${cleanPath}`);
		console.log(`Derived Section ID: ${sectionId}`);
		console.log(`Target Section:`, targetSection);
		
		if (targetSection) {
		myActivateSection(targetSection);
		if (!replaceState) {
		history.pushState(null, '', cleanPath);
		}
		// Manage header and footer visibility
		manageHeaderFooterVisibility(sectionId);
		} else {
		console.warn(`Section with ID '${sectionId}-section' not found.`);
		// Removed the force redirection to '/home'
		}
		};
		
		// Function to scroll to a specific point
		const scrollToPoint = (element, path) => {
		if (element) {
		element.scrollIntoView({ behavior: 'smooth', block: 'start' });
		history.replaceState(null, '', path);
		}
		};
		
		// Function to handle URL changes
		const handleURL = () => {
		const { pathname, hash } = window.location;
		
		if (hash) {
		const scrollElement = document.querySelector(`[data-scroll-id="${hash.substring(1)}"]`);
		if (scrollElement) {
		scrollToPoint(scrollElement, pathname);
		} else {
		const cleanPath = pathname + hash.replace('#', '');
		history.replaceState(null, '', cleanPath);
		navigateToSection(cleanPath, true);
		}
		} else {
		navigateToSection(window.location.pathname, true);
		}
		
		forceConvertHyphens();
		};
		
		// Event listener for click events on anchor tags with href starting with '#'
		document.addEventListener('click', (event) => {
		const link = event.target.closest('a[href^="#"]');
		if (link) {
		event.preventDefault();
		const hash = link.getAttribute('href').substring(1);
		const scrollElement = document.querySelector(`[data-scroll-id="${hash}"]`);
		if (scrollElement) {
		scrollToPoint(scrollElement, window.location.pathname);
		} else {
		navigateToSection('/' + hash);
		}
		}
		});
		
		// Function to convert hyphens in the path
		const forceConvertHyphens = () => {
		const path = window.location.pathname;
		if (path.includes('---')) {
		const newPath = convertPath(path);
		history.replaceState(null, '', newPath);
		}
		};
		
		// Initialize after DOM is loaded
		forceConvertHyphens();
		window.addEventListener('popstate', handleURL);
		window.addEventListener('hashchange', handleURL); // Handle hash changes as well
		handleURL();