// Language detection and redirect system
(function() {
	const SUPPORTED_LANGUAGES = {
		'en': { file: 'index.html', name: '🇬🇧 English' },
		'fr': { file: 'index-fr.html', name: '🇫🇷 Français' },
		'de': { file: 'index-de.html', name: '🇩🇪 Deutsch' },
		'it': { file: 'index-it.html', name: '🇮🇹 Italiano' },
	};
    
	function getCurrentLanguage() {
		const currentPath = window.location.pathname;
		const currentFile = currentPath.split('/').pop() || 'index.html';
        
		for (const [langCode, langData] of Object.entries(SUPPORTED_LANGUAGES)) {
			if (langData.file === currentFile) return langCode;
		}
		return 'en'; // default to English
	}
    
	function getBestLanguageMatch(userLangs, supportedLangs) {
		for (const lang of userLangs) {
			const code = lang.split('-')[0].toLowerCase();
			if (supportedLangs[code]) return supportedLangs[code].file;
		}
		return null;
	}
    
	function createLanguageSelect() {
		const currentLang = getCurrentLanguage();
		const selectHTML = `
		<select id="languageSelect">
		${Object.entries(SUPPORTED_LANGUAGES).map(([code, data]) => 
			`<option value="${code}" ${code === currentLang ? 'selected' : ''}>${data.name}</option>`
		).join('')}
		</select>
		`;
        
		const container = document.getElementById('languageSelectContainer');
		if (container) container.innerHTML = selectHTML;
	}
    
	function handleLanguageChange() {
		const select = document.getElementById('languageSelect');
		if (select) {
			select.addEventListener('change', function() {
				const selectedLang = this.value;
				const targetFile = SUPPORTED_LANGUAGES[selectedLang].file;
                
				// Disable auto-redirect when user makes manual selection
				sessionStorage.setItem('autoRedirectDisabled', 'true');
                
				// Navigate to selected language
				window.location.href = targetFile;
			});
		}
	}
    
	function performAutoRedirect() {
		// Only do auto-redirect on index.html and if user hasn't disabled it
		const currentPath = window.location.pathname;
		const currentFile = currentPath.split('/').pop() || 'index.html';
        
		if (currentFile === 'index.html') {
			const autoRedirectDisabled = sessionStorage.getItem('autoRedirectDisabled');
			const hasRedirected = sessionStorage.getItem('langRedirectChecked');
            
			if (!autoRedirectDisabled && !hasRedirected) {
				const userLangs = navigator.languages || [navigator.language || navigator.userLanguage];
				const targetFile = getBestLanguageMatch(userLangs, SUPPORTED_LANGUAGES);
                
				if (targetFile && targetFile !== 'index.html') {
					sessionStorage.setItem('langRedirectChecked', 'true');
					window.location.replace(targetFile);
					return true; // Redirect occurred
				}
			}
            
			sessionStorage.setItem('langRedirectChecked', 'true');
		}
		return false; // No redirect
	}
    
	// Initialize when page loads
	document.addEventListener('DOMContentLoaded', function() {
		// Don't create select if redirect is happening
		if (!performAutoRedirect()) {
			createLanguageSelect();
			handleLanguageChange();
		}
	});
    
	// For backwards compatibility, also try to initialize immediately if DOM is already ready
	if (document.readyState === 'loading') {
		// DOM is still loading, event listener above will handle it
	} else {
		// DOM is already loaded
		if (!performAutoRedirect()) {
			createLanguageSelect();
			handleLanguageChange();
		}
	}
})();
