/* scripts.js */
let savedSession;

document.addEventListener('DOMContentLoaded', () => {
    const myAccount = document.getElementById('my-account');
    const myAccountMenu = document.getElementById('my-account-menu');
    const mySettings = document.getElementById('my-settings');
    const mySettingsMenu = document.getElementById('my-settings-menu');
    const toggleSidebar = document.getElementById('toggle-sidebar');
    const sidebar = document.getElementById('sidebar');
    const content = document.querySelector('.mainContentSection');
    const themeToggle = document.getElementById('theme-toggle');
    const soundToggle = document.getElementById('sound-toggle');
    const sessionToggle = document.getElementById('session-toggle');
	const viewMyCasesBtn = document.querySelector('.view-my-cases');
	const viewMySettingsBtn = document.querySelector('.view-my-settings');
	const changeMySettingsBtn = document.querySelector('.change-my-settings');
    const html = document.documentElement;

    function setCookie(name, value, days) {
        let expires = "";
        if (days) {
            const date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + (value || "") + expires + "; path=/";
    }

    function getCookie(name) {
        const nameEQ = name + "=";
        const ca = document.cookie.split(';');
        for(let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }
	
	function toggleMenu(menuElement) {
        if (menuElement) {
            menuElement.style.display = menuElement.style.display === 'block' ? 'none' : 'block';
        }
    }

    /* hamburger.addEventListener('click', (e) => {
        e.stopPropagation();
        hamburger.classList.toggle('change');
        toggleMenu(menu);
        if (myAccountMenu) myAccountMenu.style.display = 'none';
    }); 
	*/

    myAccount.addEventListener('click', (e) => {
		e.stopPropagation();
		toggleMenu(myAccountMenu);
	});

    mySettings.addEventListener('click', (e) => {
		e.stopPropagation();
		toggleMenu(mySettingsMenu);
	});

	// Sidebar toggle
	toggleSidebar.addEventListener('click', () => {
		sidebar.classList.toggle('collapsed');
		content.classList.toggle('sidebar-collapsed');
		document.body.classList.toggle('sidebar-collapsed');
		setCookie('sidebar', sidebar.classList.contains('collapsed') ? 'collapsed' : 'expanded', 30);
	});
	
	// disable sidebar if nothing is selected
	function toggleSidebarVisibility(enabled) {
		const sidebarButtons = document.querySelectorAll('.sidebar-button');
		sidebarButtons.forEach(button => {
			button.classList.toggle('disabled', !enabled);
			button.style.pointerEvents = enabled ? 'auto' : 'none';
		});
	}

// Initialize global variables if they don't exist
	if (typeof UserSoundFlag === 'undefined') window.UserSoundFlag = true;
	if (typeof UserImageStr === 'undefined') window.UserImageStr = "photo";
	if (typeof UserGasColorStr === 'undefined') window.UserGasColorStr = "US";

	// Theme toggle - click entire bar to switch
	if (themeToggle) {
		themeToggle.addEventListener('click', () => {
			html.classList.toggle('light-theme');
			const options = themeToggle.querySelectorAll('.toggle-option');
			
			if (html.classList.contains('light-theme')) {
				options.forEach(opt => opt.classList.remove('active'));
				themeToggle.querySelector('[data-value="light"]').classList.add('active');
				setCookie('theme', 'light', 30);
			} else {
				options.forEach(opt => opt.classList.remove('active'));
				themeToggle.querySelector('[data-value="dark"]').classList.add('active');
				setCookie('theme', 'dark', 30);
			}
		});
	}
	
	// Photo toggle - click entire bar to switch
	const photoToggle = document.getElementById('photo-toggle');
	if (photoToggle) {
		photoToggle.addEventListener('click', () => {
			const options = photoToggle.querySelectorAll('.toggle-option');
			const currentActive = photoToggle.querySelector('.toggle-option.active');
			const currentValue = currentActive ? currentActive.getAttribute('data-value') : 'photo';
			const newValue = currentValue === 'photo' ? 'gallery' : 'photo';
			
			options.forEach(opt => opt.classList.remove('active'));
			photoToggle.querySelector(`[data-value="${newValue}"]`).classList.add('active');
			
			// Update global variable and save
			window.UserImageStr = newValue === 'gallery' ? 'styled' : 'photo';
			setCookie('images', newValue, 30);
			if (typeof SetPatientImage === 'function') {
				SetPatientImage();
			}
		});
	}
	
	// Colors toggle - click entire bar to switch
	const colorsToggle = document.getElementById('colors-toggle');
	if (colorsToggle) {
		colorsToggle.addEventListener('click', () => {
			const usColorSpan = colorsToggle.querySelector('.us-color');
			const isoColorSpan = colorsToggle.querySelector('.iso-color');
			
			// Check current active state by background color
			const usActive = usColorSpan.style.backgroundColor === 'rgb(62, 190, 116)';
			
			if (usActive) {
				// Switch to ISO
				usColorSpan.style.backgroundColor = '';
				usColorSpan.style.borderRadius = '';
				usColorSpan.style.padding = '';
				isoColorSpan.style.backgroundColor = '#3ebe74';
				isoColorSpan.style.borderRadius = '5px';
				isoColorSpan.style.padding = '2px 10px';
				
				// Update global variable and call function
				window.UserGasColorStr = "ISO";
				setCookie('colors', 'iso', 30);
				if (typeof SetGasColors === 'function') {
					SetGasColors();
				}
			} else {
				// Switch to US
				isoColorSpan.style.backgroundColor = '';
				isoColorSpan.style.borderRadius = '';
				isoColorSpan.style.padding = '';
				usColorSpan.style.backgroundColor = '#3ebe74';
				usColorSpan.style.borderRadius = '5px';
				usColorSpan.style.padding = '2px 10px';
				
				// Update global variable and call function
				window.UserGasColorStr = "US";
				setCookie('colors', 'us', 30);
				if (typeof SetGasColors === 'function') {
					SetGasColors();
				}
			}
		});
	}
	
	// Sound toggle - click entire bar to switch
	if (soundToggle) {
		soundToggle.addEventListener('click', (e) => {
			// Don't trigger if clicking directly on the switch container
			if (e.target.closest('.sound-toggle-switch')) return;
			
			const checkbox = soundToggle.querySelector('.sound-toggle-switch input');
			const statusText = soundToggle.querySelector('.status-text');
			
			if (checkbox && statusText) {
				checkbox.checked = !checkbox.checked;
				const isOn = checkbox.checked;
				statusText.textContent = isOn ? 'On' : 'Off';
				
				// Update global variable and save
				window.UserSoundFlag = isOn;
				setCookie('sound', isOn ? 'on' : 'off', 30);
			}
		});
		
		// Also listen for direct checkbox changes
		const checkbox = soundToggle.querySelector('.sound-toggle-switch input');
		const statusText = soundToggle.querySelector('.status-text');
		if (checkbox && statusText) {
			checkbox.addEventListener('change', () => {
				const isOn = checkbox.checked;
				statusText.textContent = isOn ? 'On' : 'Off';
				window.UserSoundFlag = isOn;
				setCookie('sound', isOn ? 'on' : 'off', 30);
			});
		}
	}

	// Load preferences with proper defaults
	function loadNewControlPreferences() {
		// Load theme preference
		const savedTheme = getCookie('theme');
		if (savedTheme && themeToggle) {
			const options = themeToggle.querySelectorAll('.toggle-option');
			options.forEach(opt => opt.classList.remove('active'));
			const targetOption = themeToggle.querySelector(`[data-value="${savedTheme}"]`);
			if (targetOption) targetOption.classList.add('active');
		}
		
		// Load images preference (default to photo)
		const savedImages = getCookie('images') || 'photo';
		if (photoToggle) {
			const options = photoToggle.querySelectorAll('.toggle-option');
			options.forEach(opt => opt.classList.remove('active'));
			const targetOption = photoToggle.querySelector(`[data-value="${savedImages}"]`);
			if (targetOption) targetOption.classList.add('active');
			
			// Set global variable
			window.UserImageStr = savedImages === 'gallery' ? 'styled' : 'photo';
		}
		
		// Load colors preference (DEFAULT TO US)
		const savedColors = getCookie('colors') || 'us';
		if (colorsToggle) {
			const usColorSpan = colorsToggle.querySelector('.us-color');
			const isoColorSpan = colorsToggle.querySelector('.iso-color');
			
			if (savedColors === 'us' && usColorSpan) {
				usColorSpan.style.backgroundColor = '#3ebe74';
				usColorSpan.style.borderRadius = '5px';
				usColorSpan.style.padding = '2px 10px';
				window.UserGasColorStr = "US";
			} else if (savedColors === 'iso' && isoColorSpan) {
				isoColorSpan.style.backgroundColor = '#3ebe74';
				isoColorSpan.style.borderRadius = '5px';
				isoColorSpan.style.padding = '2px 10px';
				window.UserGasColorStr = "ISO";
			}
			
			// Call SetGasColors if it exists
			if (typeof SetGasColors === 'function') {
				SetGasColors();
			}
		}
		
		// Load sound preference (default to on/true)
		const savedSound = getCookie('sound') || 'on';
		if (soundToggle) {
			const checkbox = soundToggle.querySelector('.sound-toggle-switch input');
			const statusText = soundToggle.querySelector('.status-text');
			
			if (checkbox && statusText) {
				const isOn = savedSound === 'on';
				checkbox.checked = isOn;
				statusText.textContent = isOn ? 'On' : 'Off';
				
				// Set global variable
				window.UserSoundFlag = isOn;
			}
		}
	}
	
	// Call the preferences loader
	loadNewControlPreferences();
	
	// Session toggle
	// check state
	if (sessionToggle) {
		savedSession = getCookie('session');
		if (savedSession === 'off') {
			html.classList.add('session-off');
			sessionToggle.querySelector('i').classList.replace('fa-play', 'fa-pause');
			sessionToggle.querySelector('.session-text').textContent = 'Off';
		}
	}
	// click handler
	if (sessionToggle) {  
		sessionToggle.addEventListener('click', () => {
			html.classList.toggle('session-off');
			const icon = sessionToggle.querySelector('i');
			const text = sessionToggle.querySelector('.session-text');
			
			if (html.classList.contains('session-off')) {
				icon.classList.replace('fa-play', 'fa-pause');
				text.textContent = 'Off';
				setCookie('session', 'off', 30);
			} else {
				icon.classList.replace('fa-pause', 'fa-play');
				text.textContent = 'On';
				setCookie('session', 'on', 30);
			}
		});
	}
	
	// Country dropdown
	const countrySelect = document.getElementById('country');

	if (countrySelect) {  // Only add listener if element exists
		countrySelect.addEventListener('change', () => {
			const selectedValue = countrySelect.value;
			
			// Remove any existing location classes
			html.classList.remove('loc-united-states', 'loc-europe', 'loc-global');
			
			// Add new class based on selection
			if (selectedValue !== 'united-states') {
				html.classList.add(`loc-${selectedValue}`);
			}
			
			// Save to cookie
			setCookie('country', selectedValue, 30);
		});

		// Load saved country setting
		const savedCountry = getCookie('country');
		if (savedCountry) {
			countrySelect.value = savedCountry;
			if (savedCountry !== 'united-states') {
				html.classList.add(`loc-${savedCountry}`);
			}
		}
	}
	
    // Close menu when clicking outside
    document.addEventListener('click', (event) => {
        if (!myAccount.contains(event.target) && !myAccountMenu.contains(event.target)) {
            myAccountMenu.style.display = 'none';
        }
	});
    document.addEventListener('click', (event) => {
        if (!mySettings.contains(event.target) && !mySettingsMenu.contains(event.target)) {
            mySettingsMenu.style.display = 'none';
        }
	});

	// Close settings menu when clicking on account
	myAccount.addEventListener('click', (event) => {
		mySettingsMenu.style.display = 'none';
	});
	
	// Close account menu when clicking on settings
	mySettings.addEventListener('click', (event) => {
		myAccountMenu.style.display = 'none';
	});

	/* save cookies for user toggles */
	const savedTheme = getCookie('theme');
	if (savedTheme === 'light') {
		html.classList.add('light-theme');
		themeToggle.querySelector('i').classList.replace('fa-moon', 'fa-sun');
		themeToggle.querySelector('span').textContent = 'Light';
	}
	
	const savedSound = getCookie('sound');
	if (savedSound === 'on') {
		html.classList.add('sound-on');
		soundToggle.querySelector('i').classList.replace('fa-volume-mute', 'fa-volume-up');
		soundToggle.querySelector('.status-text').textContent = 'On';
	}
	
	if (sessionToggle) {
		savedSession = getCookie('session');
		// console.log('Session value (in scope):', savedSession);
		if (savedSession === 'off') {
			html.classList.add('session-off');
			sessionToggle.querySelector('i').classList.replace('fa-play', 'fa-pause');
			sessionToggle.querySelector('.session-text').textContent = 'Off';
		}
	}

	const savedSidebar = getCookie('sidebar');
	if (savedSidebar === 'collapsed') {
		sidebar.classList.add('collapsed');
		content.classList.add('sidebar-collapsed');
		document.body.classList.add('sidebar-collapsed');
	}

	/* profile picture change */
    const modal = document.getElementById('profilePictureModal');
    const changeProfilePictureTriggers = document.querySelectorAll('.change-profile-picture, #changeProfilePicture');
    const closeButton = modal.querySelector('.close');
    const form = document.getElementById('profilePictureForm');
    const uploadStatus = document.getElementById('uploadStatus');
    const removeProfilePictureButton = document.getElementById('removeProfilePicture');

    changeProfilePictureTriggers.forEach(trigger => {
        trigger.addEventListener('click', openModal);
    });

    closeButton.addEventListener('click', closeModal);

    window.addEventListener('click', function(event) {
        if (event.target == modal) {
            closeModal();
        }
    });

	form.addEventListener('submit', function(e) {
		e.preventDefault();
		const formData = new FormData(this);
		
		fetch('includes/upload_profile_picture.php', {
			method: 'POST',
			body: formData
		})
		.then(response => response.json())
		.then(data => {
			if (uploadStatus) {
				uploadStatus.textContent = data.message;
			}
			if (data.success) {
				updateProfilePicture(data.newImageUrl);
				setTimeout(closeModal, 2000);
			}
		})
		.catch(error => {
			// console.error('Error:', error);
			if (uploadStatus) {
				uploadStatus.textContent = 'An error occurred. Please try again.';
			}
		});
	});

	// remove the profile picture
	function removeProfilePicture(event) {
		event.preventDefault();
		event.stopPropagation();  // Add this line to stop event propagation
		
		if (confirm('Are you sure you want to remove your profile picture?')) {
			fetch('/includes/remove_profile_picture.php', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
				},
			})
			.then(response => {
				if (!response.ok) {
					throw new Error('Network response was not ok');
				}
				return response.json();
			})
			.then(data => {
				if (data.success) {
					alert(data.message);
					location.reload();
				} else {
					alert('Error: ' + data.message);
				}
			})
			.catch(error => {
				// console.error('Error:', error);
				alert('An error occurred. Please try again.');
			});
		}
	}


	function updateProfilePicture(newImageUrl) {
		const profilePictureContainers = document.querySelectorAll('.profile-picture-container, .user-settings img');
		profilePictureContainers.forEach(container => {
			if (container.tagName.toLowerCase() === 'img') {
				container.src = newImageUrl;
			} else {
				container.innerHTML = `<img src="${newImageUrl}" alt="Profile Picture" class="profile-picture">`;
			}
		});

		// Toggle visibility of remove button
		if (removeProfilePictureButton) {
			removeProfilePictureButton.style.display = newImageUrl ? 'block' : 'none';
		}
	}
	
    function openModal() {
        modal.style.display = 'block';
    }

    function closeModal() {
		modal.style.display = 'none';
		form.reset();
		if (uploadStatus) {
			uploadStatus.textContent = '';
		}
	}
	
	if (removeProfilePictureButton) {
        removeProfilePictureButton.addEventListener('click', removeProfilePicture);
    }
	
});

function handleSidebarClick(action) {
    if (typeof CurrentCase !== 'undefined' && CurrentCase) {
        // Case is running
        switch(action) {
            case 'patient':
                break;
            case 'monitors':
                break;
            case 'airway':
                break;
            case 'breathing':
                break;
            case 'drugs':
                break;
            case 'fluids':
                break;
            case 'labs':
                break;
            case 'surgeon':
                break;
            case 'resuscitate':
                break;
        }
    }
    // Do nothing if no case is selected
}

// pro upgrade modal
document.addEventListener('DOMContentLoaded', function() {
    // console.log('DOM fully loaded');
    var proButton = document.querySelector('.pro-button a');
    
    if (proButton) {
        proButton.addEventListener('click', function(e) {
            e.preventDefault();
            var proStatus = this.getAttribute('data-status') || 'Upgrade';
            var proExpirationDate = this.getAttribute('data-expiration') || '';
            // console.log('Calling showProModal with:', proStatus, proExpirationDate);
            showProModal(proStatus, proExpirationDate);
        });
    }
});

async function showProModal(status, expirationDate) {
    // console.log('showProModal called with status:', status, 'and expirationDate:', expirationDate);
    var modal = document.getElementById('proStatusModal');
    if (!modal) {
        // console.error('Pro Status Modal not found');
        return;
    }

    const modalContent = await getStatusInfo();

    // Fetch user group information
    fetch('/api/get_pro_group.php')
        .then(response => response.json())
        .then(groupData => {
            setupProModal(status, expirationDate, groupData.isIndividual, modal, modalContent);
        })
        .catch(error => {
            // console.error('Error fetching user group:', error);
            // Fallback to regular modal if fetch fails
            setupProModal(status, expirationDate, true, modal, modalContent);
        });
}

// get the json for replaceable data
async function getStatusInfo() {
	try {
		const response = await fetch('/app/modal_data/modal-content.json');
		const data = await response.json();
		return data.proModal;
	} catch (error) {
		return {
			statusText: {
				'Pro': 'Pro Active',
				'Renew': 'Pro Active, Expiring Soon', 
				'Expired': 'Pro Expired',
				'Upgrade': 'Upgrade to Pro',
				'Super': 'Upgrade 44444444445555555to Pro',
				'No': 'Upgrade to Pro'
			},
			features: {
				'Pro': ['More Cases Unlocked', 'Advanced Analytics', 'User Case History View', 'Priority Support Active'],
				'Upgrade': ['Unlock More Cases', 'Unlock Advanced Analytics', 'View User Case History', 'Receive Priority Support']
			},
			buttons: {
				proActive: 'Pro Active',
				upgrade: 'Yes, Upgrade'
			}
		};
	}
}

function setupProModal(status, expirationDate, isIndividual, modal, modalContent) {
    var statusEl = modal.querySelector('#proStatus');
    var expirationEl = modal.querySelector('#proExpiration');
    var featuresEl = modal.querySelector('#proFeatures');
    var upgradeYesBtn2 = modal.querySelector('.upgradeYes');
    var upgradeNoBtn2 = modal.querySelector('.upgradeNo');

    if (!statusEl || !expirationEl || !featuresEl || !upgradeYesBtn2 || !upgradeNoBtn2) {
        // console.error('One or more elements not found in Pro Status Modal');
        return;
    }

    var info = {
		icon: status === 'Pro' ? 'fa-check-circle' : status === 'Renew' ? 'fa-exclamation-circle' : status === 'Expired' ? 'fa-times-circle' : 'fa-rocket',
		buttonClass: (status === 'Pro' || status === 'Renew') ? 'status-pro' : 'status-expired'
	};

    // Update button text based on Pro status
    if (status === 'Pro') {
        upgradeYesBtn2.innerHTML = 'Pro Active';
        upgradeYesBtn2.classList.add('disabled');
        upgradeYesBtn2.style.pointerEvents = 'none';
    } else {
        upgradeYesBtn2.innerHTML = 'Yes, Upgrade';
        upgradeYesBtn2.classList.remove('disabled');
        upgradeYesBtn2.style.pointerEvents = 'auto';
    }

    statusEl.innerHTML = `<i class="fas ${info.icon}"></i> ${modalContent.statusText[status]}`;
	featuresEl.innerHTML = modalContent.features[status].map(feature => `<li>${feature}</li>`).join('');
    expirationEl.textContent = status !== 'Upgrade' && status !== 'No' ? 'Expiration Date: ' + expirationDate : '';
    featuresEl.innerHTML = modalContent.features[status].map(feature => `<li>${feature}</li>`).join('');

	// get the json for replaceable data
	async function getStatusInfo() {
		try {
			const response = await fetch('/app/modal_data/modal-content.json');
			const data = await response.json();
			return data.proModal;
		} catch (error) {
			return {
				statusText: {
					'Pro': 'Pro Active',
					'Renew': 'Pro Active, Expiring Soon', 
					'Expired': 'Pro Expired',
					'Upgrade': 'Upgrade to Pro',
					'Super': 'Upgrade to Pro',
					'No': 'Upgrade to Pro'
				},
				features: {
					'Pro': ['More Cases Unlocked', 'Advanced Analytics', 'User Case History View', 'Priority Support Active'],
					'Upgrade': ['Unlock More Cases', 'Unlock Advanced Analytics', 'View User Case History', 'Receive Priority Support']
				},
				buttons: {
					proActive: 'Pro Active',
					upgrade: 'Yes, Upgrade'
				}
			};
		}
	}

    upgradeYesBtn2.onclick = function() {
        // Only handle pause if there's an active case
        if (UserCaseRunning && typeof CurrentCase !== 'undefined' && CurrentCase !== null) {
            try {
                if (typeof CaseLogStr2 === 'undefined') {
                    window.CaseLogStr2 = "";
                }
                ClickBtnTime();
            } catch (error) {
                // console.error('Error in upgrade process:', error);
            }
        }
        
        modal.style.display = 'none';

        if (status !== 'Pro') {
            if (!isIndividual) {
                // Show departmental upgrade message
                window.open(mainUrl + '/upgrade-dept', '_blank');
            } else {
                // Regular upgrade process
                window.open(proStatusUrls[status] || proStatusUrls['Upgrade'], '_blank');
            }
        }
    };

    upgradeNoBtn2.onclick = function() {
        modal.style.display = 'none';
    };

    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = 'none';
        }
    };

    modal.style.display = 'block';
    // console.log('Modal display style:', modal.style.display);
}

const proStatusUrls = {
    'Pro': mainUrl + '/pro-upgrade',
    'Renew': mainUrl + '/pro-upgrade',
    'Expired': mainUrl + '/pro-upgrade',
    'Upgrade': mainUrl + '/pro-upgrade',
    'No': mainUrl + '/pro-upgrade'
};

// Close modal functionality
document.querySelectorAll('.modal .close').forEach(function(closeBtn) {
    closeBtn.addEventListener('click', function() {
        this.closest('.modal').style.display = 'none';
    });
});


// demo modal
function showDemoModal() {
    const modal = document.getElementById('demoModal');
    if (modal) {
        modal.style.display = 'block';

        const upgradeYes = document.getElementById('upgradeYes');
        const upgradeNo = document.getElementById('upgradeNo');

        if (upgradeYes) {
            upgradeYes.onclick = function() {
                window.location.href = '/upgrade.php';
            }
        }

        if (upgradeNo) {
            upgradeNo.onclick = function() {
                modal.style.display = 'none';
            }
        }

        // Close the modal when clicking outside of it
        window.onclick = function(event) {
            if (event.target == modal) {
                modal.style.display = 'none';
            }
        }
    } else {
        // console.error('Demo modal not found');
    }
}

/******************************************************************
***  session handler  ***
******************************************************************/


// Global flag to track settings navigation
document.addEventListener('DOMContentLoaded', function() {
    // Clear flag only if we're not on settings page
    if (!window.location.pathname.includes('/settings')) {
        sessionStorage.removeItem('navigatingToSettings');
    }
    if (!window.location.pathname.includes('/cases')) {
        sessionStorage.removeItem('navigatingToCases');
    }
    if (!window.location.pathname.includes('/profile')) {
        sessionStorage.removeItem('navigatingToProfile');
    }
    
    // Settings link detection
    function addSettingsListeners() {
        const settingsElements = document.querySelectorAll(`
            a[href*="settings"],
            .view-settings, 
            .view-cases,
            .change-settings,
            .settings-switch div,
            [onclick*="settings"],
            [data-href*="settings"],
            .view-my-cases,
            .view-my-settings,
            .change-my-settings
        `);

        settingsElements.forEach(element => {
            element.addEventListener('click', () => {
                sessionStorage.setItem('navigatingToSettings', 'true');
            }, true);
        });

        settingsElements.forEach(element => {
            element.addEventListener('click', () => {
                sessionStorage.setItem('navigatingToCases', 'true');
            }, true);
        });

        settingsElements.forEach(element => {
            element.addEventListener('click', () => {
                sessionStorage.setItem('navigatingToProfile', 'true');
            }, true);
        });
    }

    // Initial setup
    addSettingsListeners();

    // Settings elements selector - must be defined before observer
    const SETTINGS_SELECTOR = `
        a[href*="settings"],
        .view-settings, 
        .view-cases,
        .change-settings,
        .settings-switch div,
        [onclick*="settings"],
        [data-href*="settings"],
        .view-my-cases,
        .view-my-settings,
        .change-my-settings
    `;

	// Throttle to limit how often callback is executed
    function throttle(func, limit) {
        let inThrottle;
        let lastRan;
        return function(...args) {
            if (!inThrottle) {
                func.apply(this, args);
                lastRan = Date.now();
                inThrottle = true;
                setTimeout(() => {
                    if (Date.now() - lastRan >= limit) {
                        func.apply(this, args);
                        inThrottle = false;
                    }
                }, limit);
            }
        };
    }

    // Debounce to wait until changes stop
    function debounce(func, wait) {
        let timeout;
        return function(...args) {
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(this, args), wait);
        };
    }

    // Create throttled version of addSettingsListeners
    const throttledAddListeners = throttle((root) => {
        addSettingsListeners(root);
    }, 1000); // Only run at most once per second

    // Create debounced version for batch processing
    const debouncedProcessMutations = debounce(() => {
        addSettingsListeners();
    }, 250); // Wait for 250ms of no changes before processing

    // Configure the observer
    const observerConfig = {
        childList: true,
        subtree: true,
        attributes: false // We don't need to watch attributes
    };

    // Create optimized observer
    const observer = new MutationObserver((mutations) => {
        let shouldProcess = false;
        
        // Check if any mutations added nodes we care about
        for (const mutation of mutations) {
            if (mutation.addedNodes.length) {
                for (const node of mutation.addedNodes) {
                    if (node.nodeType === 1 && // Element node
                        (node.matches?.(SETTINGS_SELECTOR) || 
                         node.querySelector?.(SETTINGS_SELECTOR))) {
                        shouldProcess = true;
                        break;
                    }
                }
            }
            if (shouldProcess) break;
        }

        // Only process if relevant nodes are found
        if (shouldProcess) {
            debouncedProcessMutations();
        }
    });

    // Start observing with optimized config
    observer.observe(document.body, observerConfig);

    // Cleanup function
    function cleanup() {
        observer.disconnect();
    }

    // Clean up
    window.addEventListener('pagehide', cleanup);
});

// Global click handler as backup
document.addEventListener('click', (e) => {
    const settingsElement = e.target.closest(`
        a[href*="settings"],
        .view-settings, 
        .view-cases,
        .change-settings,
        .settings-switch div,
        [onclick*="settings"],
        [data-href*="settings"],
        .view-my-cases,
        .view-my-settings,
        .change-my-settings
    `);

    if (settingsElement) {
        sessionStorage.setItem('navigatingToSettings', 'true');
    }
}, true);

// Session termination handler
window.addEventListener('pagehide', function(e) {
    const isSettingsPage = window.location.pathname.includes('/settings');
    const isCasesPage = window.location.pathname.includes('/cases');
    const isProfilePage = window.location.pathname.includes('/profile');
    const goingToSettings = sessionStorage.getItem('navigatingToSettings') === 'true';
    const goingToCases = sessionStorage.getItem('navigatingToCases') === 'true';
    const goingToProfile = sessionStorage.getItem('navigatingToProfile') === 'true';
    const sessionCookie = document.cookie.split(';')
        .find(c => c.trim().startsWith('session='));
    const sessionValue = sessionCookie ? sessionCookie.split('=')[1].trim() : 'on';

    // Don't terminate if:
    // 1. On settings page
    // 2. Going to settings pages
    // 3. Session is set to off for super
	// 4. Is a page refresh
    if (isSettingsPage || 
		isCasesPage || 
		isProfilePage || 
        goingToSettings || 
        goingToCases ||
        goingToProfile ||
        sessionValue === 'off' || 
        performance.navigation.type === 1) {
        return;
    }

    // Proceed with termination
    if (navigator.sendBeacon) {
        navigator.sendBeacon('/api/terminate_session.php');
    } else {
        fetch('/api/terminate_session.php', {
            method: 'POST',
            keepalive: true
        });
    }
});


/* email text overflow functions */

document.querySelectorAll('.inner-text').forEach(element => {
    element.setAttribute('data-text', element.textContent);
    
    if (element.scrollWidth > element.offsetWidth) {
        element.classList.add('overflow');
    } else {
        element.classList.remove('overflow');
    }
});

window.addEventListener('resize', () => {
    document.querySelectorAll('.inner-text').forEach(element => {
        if (element.scrollWidth > element.offsetWidth) {
            element.classList.add('overflow');
        } else {
            element.classList.remove('overflow');
        }
    });
});

// copy email icons

document.querySelectorAll('.copy-icon').forEach(icon => {
    icon.addEventListener('click', function() {
        let email;
        
        // For the main menu version
        if (this.closest('.just-info')) {
            email = this.previousElementSibling.querySelector('.inner-text').textContent;
        }
        
        if (email) {
            navigator.clipboard.writeText(email.trim()).then(() => {
                // Visual feedback
                this.classList.remove('fa-copy');
                this.classList.add('fa-check');
                
                setTimeout(() => {
                    this.classList.remove('fa-check');
                    this.classList.add('fa-copy');
                }, 1000);
            });
        }
    });
});

/* hide copy icon when no overflow */
window.addEventListener('load', () => {
    document.querySelectorAll('.copy-icon').forEach(icon => {
        const textEl = icon.previousElementSibling.querySelector('.inner-text');
        if (textEl.scrollWidth <= textEl.offsetWidth) {
            icon.style.display = 'none';
        } else {
            icon.style.removeProperty('display');
        }
    });
}); 


// Debug Logging Toggle
const debugLoggingToggle = document.getElementById('debug-logging-toggle');
if (debugLoggingToggle) {
    const debugButtons = debugLoggingToggle.querySelectorAll('.toggle-option');
    debugButtons.forEach(button => {
        button.addEventListener('click', function() {
            const mode = this.getAttribute('data-value');
            
            fetch('/api/toggle_debug_mode.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'mode=' + mode
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    debugButtons.forEach(btn => btn.classList.remove('active'));
                    this.classList.add('active');
                    console.log('Debug mode set to:', mode);
                } else {
                    console.error('Failed to toggle debug mode:', data.message);
                }
            })
            .catch(error => console.error('Error:', error));
        });
    });
}


// ================================================================
// SESSION KEEPALIVE FOR LONG-RUNNING SIMULATIONS
// ================================================================

let sessionKeepaliveInterval = null;

function startSessionKeepalive() {
    if (sessionKeepaliveInterval) {
        console.log("Session keepalive already running");
        return;
    }
    console.log("Starting session keepalive (pings every 5 minutes)");
    sessionKeepaliveInterval = setInterval(() => {
        fetch('/api/keepalive.php', {method: 'POST'})
            .then(r => r.json())
            .then(d => console.log('Session keepalive ping:', d))
            .catch(e => console.error('Keepalive error:', e));
    }, 300000);
}

function stopSessionKeepalive() {
    if (sessionKeepaliveInterval) {
        console.log("Stopping session keepalive");
        clearInterval(sessionKeepaliveInterval);
        sessionKeepaliveInterval = null;
    }
}
