/* settings.js */
document.addEventListener('DOMContentLoaded', () => {
    const viewSettingsButton = document.querySelector('.view-settings');
    const changeSettingsButton = document.querySelector('.change-settings');
    const viewCasesButton = document.querySelector('.view-cases');
    const userSettings = document.querySelector('.user-settings');
    const userSettingsBottom = document.querySelector('.user-settings-bottom');
    const userCases = document.querySelector('.user-cases');
    const dynamicBreadcrumb = document.getElementById('dynamic-breadcrumb');
    const caseBreadcrumb = document.getElementById('case-breadcrumb');

    function updateBreadcrumbs(tabName, caseNumber = null) {
        dynamicBreadcrumb.textContent = tabName;
        if (caseNumber) {
            caseBreadcrumb.textContent = `Case ${caseNumber}`;
            caseBreadcrumb.style.display = 'inline';
        } else {
            caseBreadcrumb.style.display = 'none';
        }
    }

    function showViewSettings() {
        userSettings.style.display = 'block';
        userSettingsBottom.style.display = 'none';
        userCases.style.display = 'none';
        viewSettingsButton.classList.add('settings-active');
        changeSettingsButton.classList.remove('settings-active');
        viewCasesButton.classList.remove('settings-active');
        updateBreadcrumbs('View Details');
    }

    function showChangeSettings() {
        userSettings.style.display = 'none';
        userSettingsBottom.style.display = 'block';
        userCases.style.display = 'none';
        changeSettingsButton.classList.add('settings-active');
        viewSettingsButton.classList.remove('settings-active');
        viewCasesButton.classList.remove('settings-active');
        updateBreadcrumbs('Change Settings');
    }

    function showViewCases() {
        userSettings.style.display = 'none';
        userSettingsBottom.style.display = 'none';
        userCases.style.display = 'block';
        viewCasesButton.classList.add('settings-active');
        viewSettingsButton.classList.remove('settings-active');
        changeSettingsButton.classList.remove('settings-active');
        updateBreadcrumbs('View Cases');
        loadCases();
    }
	
	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() {
		// Get checkbox state if it exists
		const showHiddenToggle = document.getElementById('showHiddenToggle');
		const showHidden = showHiddenToggle?.checked || false;
		
		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();
				
				// Only add toggle listener if element exists and doesn't already have one
				const newToggle = document.getElementById('showHiddenToggle');
				if (newToggle && !newToggle.hasListener) {
					newToggle.addEventListener('change', loadCases);
					newToggle.hasListener = true;
				}
			})
			.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';
                updateBreadcrumbs('View Cases', caseId);
            })
            .catch(error => {
                // console.error('Error loading case details:', error);
                document.getElementById('case-details').innerHTML = '<p>Error loading case details. Please try again later.</p>';
            });
    }

    if (viewSettingsButton && changeSettingsButton && viewCasesButton) {
        viewSettingsButton.addEventListener('click', showViewSettings);
        changeSettingsButton.addEventListener('click', showChangeSettings);
        viewCasesButton.addEventListener('click', showViewCases);
        
        // Initialize view based on sessionStorage
        if (sessionStorage.getItem('showCases') === 'true') {
            showViewCases();
            sessionStorage.removeItem('showCases');
        } else if (sessionStorage.getItem('showChangeSettings') === 'true') {
            showChangeSettings();
            sessionStorage.removeItem('showChangeSettings');
        } else if (sessionStorage.getItem('showDetails') === 'true') {
            showViewSettings();
            sessionStorage.removeItem('showDetails');
        } else {
            showViewSettings();
        }
    }

    // Add this to prevent settings.js from interfering with remove button
    const removeButton = document.getElementById('removeProfilePicture');
    if (removeButton) {
        removeButton.addEventListener('click', (event) => {
            event.stopPropagation();
        });
    }

    // 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') {
            showViewCases();
        }
    });
});
