function showCasesList() {
    document.getElementById('cases-list').style.display = 'block';
    document.getElementById('case-details').style.display = 'none';
}

function attachCaseViewListeners() {
	const caseLinks = document.querySelectorAll('.view-case-link');
	caseLinks.forEach(link => {
		link.addEventListener('click', function(e) {
			e.preventDefault();
			const caseId = this.getAttribute('data-case-id');
			loadCaseDetails(caseId);
		});
	});
}

function loadCases() {
	// Show loading message
	document.getElementById('cases-list').innerHTML = '<p>Loading cases...</p>';
	
	// Get saved state from localStorage first
	const savedState = localStorage.getItem('showHiddenCases');
	const showHidden = savedState === 'true';
	
	fetch('/api/get_user_cases.php' + (showHidden ? '?show_hidden=1' : ''))
		.then(response => {
			// console.log("Response received:", response.status);
			return response.text();
		})
		.then(data => {
			// console.log("Data received:", data);
			document.getElementById('cases-list').innerHTML = data;
			document.getElementById('cases-list').style.display = 'block';
			document.getElementById('case-details').style.display = 'none';
			attachCaseViewListeners();
			
			// Restore toggle state from localStorage after DOM is populated
			const newToggle = document.getElementById('showHiddenToggle');
			if (newToggle) {
				// Convert checkbox to toggle switch
				const toggleContainer = newToggle.parentElement;
				
				// Create toggle switch HTML
				const toggleSwitch = document.createElement('div');
				toggleSwitch.className = 'toggle-switch';
				
				const savedState = localStorage.getItem('showHiddenCases');
				const isChecked = savedState === 'true';
				
				toggleSwitch.innerHTML = `
					<input type="checkbox" id="showHiddenToggle" ${isChecked ? 'checked' : ''}>
					<span class="toggle-slider"></span>
				`;
				
				// Replace the original checkbox with toggle switch
				toggleContainer.replaceChild(toggleSwitch, newToggle);
				
				// Get the new checkbox reference
				const updatedToggle = document.getElementById('showHiddenToggle');
				
				// Update toggle display state
				const hiddenCasesTable = document.querySelector('.hidden-cases-table');
				if (hiddenCasesTable) {
					hiddenCasesTable.style.display = isChecked ? 'block' : 'none';
				}
				
				// Add toggle listener
				updatedToggle.addEventListener('change', function() {
					localStorage.setItem('showHiddenCases', this.checked);
					
					loadCases();
				});
			}
		})
		.catch(error => {
			// console.error('Error loading cases:', error);
			document.getElementById('cases-list').innerHTML = '<p>Error loading cases. Please try again later.</p>';
		});
}

function attachVisibilityToggleListeners() {
	document.querySelectorAll('.visibility-toggle-btn').forEach(button => {
		button.addEventListener('click', function() {
			const id = this.dataset.id;
			const currentStatus = this.dataset.status;
			
			fetch('/api/toggle_case_visibility.php', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded',
				},
				body: `id=${id}&status=${currentStatus}`
			})
			.then(response => response.json())
			.then(data => {
				if (data.success) {
					loadCases();
				} else {
					alert('Error updating visibility: ' + (data.error || 'Unknown error'));
				}
			})
			.catch(error => {
				// console.error('Error:', error);
				alert('Error communicating with server');
			});
		});
	});
}

function loadCaseDetails(caseId) {
    fetch(`/api/view_case.php?id=${caseId}`)
        .then(response => response.text())
        .then(data => {
            document.getElementById('case-details').innerHTML = data;
            document.getElementById('cases-list').style.display = 'none';
            document.getElementById('case-details').style.display = 'block';
        })
        .catch(error => {
            // console.error('Error loading case details:', error);
            document.getElementById('case-details').innerHTML = '<p>Error loading case details. Please try again later.</p>';
        });
}

// Main initialization and event handlers
document.addEventListener('DOMContentLoaded', function() {
	// Load cases immediately when page loads
	loadCases();

	// Add event listener for the "Back to Cases List" button
	document.addEventListener('click', function(e) {
		if (e.target && e.target.matches('button') && e.target.textContent === 'Back to Cases List') {
			showCasesList();
		}
	});
});

// hide/show function
document.addEventListener('DOMContentLoaded', function() {
	document.addEventListener('click', function(e) {
		if (e.target && e.target.matches('.visibility-toggle-btn')) {
			const button = e.target;
			const id = button.dataset.id;
			const currentStatus = button.dataset.status;
			const row = button.closest('tr');
			
			fetch('/api/toggle_case_visibility.php', { 
				method: 'POST',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded',
				},
				body: `id=${id}&status=${currentStatus}`
			})
			.then(response => response.json())
			.then(data => {
				if (data.success) {
					if (currentStatus === 'visible') {
						// HIDING: remove from visible table
						row.remove();
						
						// Only move to hidden table if it exists and is visible
						const hiddenTable = document.querySelector('.hidden-cases-table');
						if (hiddenTable && hiddenTable.style.display !== 'none') {
							const tbody = hiddenTable.querySelector('tbody');
							if (tbody) {
								const newRow = row.cloneNode(true);
								const newRowButton = newRow.querySelector('.visibility-toggle-btn');
								if (newRowButton) {
									newRowButton.textContent = 'Show';
									newRowButton.dataset.status = 'hidden';
								}
								tbody.appendChild(newRow);
							}
						}
					} else {
						// SHOWING: move from hidden to visible table
						const allTables = document.querySelectorAll('.home-table');
						const yourCasesTable = allTables[1];
						const newRow = row.cloneNode(true);
						const newButton = newRow.querySelector('.visibility-toggle-btn');
						if (newButton) {
							newButton.textContent = 'Hide';
							newButton.dataset.status = 'visible';
						}
						
						row.remove();
						const headerRow = yourCasesTable.querySelector('tr');
						headerRow.parentNode.insertBefore(newRow, headerRow.nextSibling);
					}

					// show popup regardless of toggle state
					const popup = document.createElement('div');
					popup.className = `confirmation-popup ${currentStatus === 'visible' ? 'hide-confirmation' : 'show-confirmation'}`;
					popup.textContent = currentStatus === 'visible' ? 'Case hidden' : 'Case shown';
					document.body.appendChild(popup);
					setTimeout(() => popup.remove(), 2000);
				}
			});
		}
	});
});