document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM content loaded');
    
    // Create a MutationObserver to watch for changes to the DOM
    const observer = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
            if (mutation.type === 'childList') {
                const caseList = document.getElementById('caseList');
                if (caseList) {
                    console.log('Case list element found');
                    observer.disconnect(); // Stop observing once we've found the element
                    fetchAndPopulateCaseList(caseList);
                }
            }
        });
    });

    // Start observing the document with the configured parameters
    observer.observe(document.body, { childList: true, subtree: true });
});

function fetchAndPopulateCaseList(caseList) {
    fetch('api/get_case_data.php')
        .then(response => {
            console.log('Response received:', response);
            return response.json();
        })
        .then(data => {
            console.log('Parsed JSON data:', data);
            
            if (!data || typeof data !== 'object') {
                console.error('Invalid case data received.');
                return;
            }
            
            window.CaseData = data;
            console.log('CaseData assigned:', window.CaseData);

            populateCaseList(caseList, data);
        })
        .catch(error => {
            console.error('Error loading or parsing case data:', error);
        });
}

function populateCaseList(selectElement, cases) {
    console.log('Populating case list');
    selectElement.innerHTML = '<option value="defaultCase">Select a Case to Start</option>';

    for (const [id, caseData] of Object.entries(cases)) {
        console.log(`Case ${id}:`, {
            title: caseData.title,
            isAccessible: caseData.isAccessible,
            requiresUpgrade: caseData.requiresUpgrade
        });
        
        const option = document.createElement('option');
        option.value = id;
        option.textContent = caseData.title;
        if (!caseData.isAccessible) {
            option.disabled = true;
        }
        selectElement.appendChild(option);
    }
}

function handleCaseSelection() {
    if (this.value !== 'defaultCase') {
        const selectedCase = window.CaseData[this.value];
        if (selectedCase) {
            if (selectedCase.requiresProUpgrade) {
                showUpgradeModal();
            } else if (selectedCase.requiresUpgrade) {
                showDemoUpgradeModal();
            } else if (selectedCase.isAccessible) {
                fetch('api/save_current_case.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'case=' + encodeURIComponent(this.value)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        window.location.reload();
                    } else {
                        console.error('Error setting case:', data.message || 'Unknown error');
                    }
                })
                .catch(error => {
                    console.error('Error saving case data:', error);
                });
            }
        }
    }
}

   function showUpgradeModal() {
       const modal = document.getElementById('upgradeModal');
       if (modal) {
           modal.style.display = 'block';

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

           if (upgradeYes) {
               upgradeYes.onclick = function() {
                   // Implement upgrade logic here
                   modal.style.display = 'none';
               }
           }

           if (upgradeNo) {
               upgradeNo.onclick = function() {
                   modal.style.display = 'none';
               }
           }
       } else {
           console.error('Upgrade modal not found');
       }
   }
   
   function showDemoUpgradeModal() {
		const modal = document.getElementById('demoUpgradeModal');
		if (modal) {
			modal.style.display = 'block';
			const upgradeYes = modal.querySelector('.upgradeYes');
			const upgradeNo = modal.querySelector('.upgradeNo');

			if (upgradeYes) {
				upgradeYes.onclick = () => {
					window.location.href = '/upgrade-from-demo';
					modal.style.display = 'none';
				};
			}

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