/* scripts_app.js */
function formatPreopMessage(preopMsg) {
  const sections = [
    { name: 'title', icon: 'fa-user-md', class: 'preop-main-title' },
    { name: 'History of Present Illness', icon: 'fa-clock', class: 'preop-title-history' },
    { name: 'Past Medical History', icon: 'fa-notes-medical', class: 'preop-title-medical' },
    { name: 'Family History', icon: 'fa-users', class: 'preop-title-family' },
    { name: 'Physical Exam', icon: 'fa-stethoscope', class: 'preop-title-physical' },
    { name: 'Labs', icon: 'fa-vial', class: 'preop-title-labs' },
    { name: 'NPO Status', icon: 'fa-utensils', class: 'preop-title-status' },
    { name: 'Patient and Surgeon Requests', icon: 'fa-user-md', class: 'preop-title-surgeon' }
  ];

  let formattedMsg = '';
  let lines = preopMsg.trim().split('\n');
  let currentSection = null;

  function formatContent(content) {
    return content.replace(/^(.+):\s*/gm, '<b>$1:</b> ');
  }

  lines.forEach((line, index) => {
    const trimmedLine = line.trim();
    const matchedSection = sections.find(section => 
      trimmedLine.toLowerCase() === section.name.toLowerCase() || 
      (index === 0 && section.name === 'title')
    );

    if (matchedSection) {
      if (currentSection) {
        formattedMsg += '</span>\n\n';
      }
      currentSection = matchedSection;
      formattedMsg += `<i class="fas ${matchedSection.icon}"></i><span class="${matchedSection.class}">${trimmedLine}</span>\n\n<span class="preop-content">`;
    } else if (trimmedLine) {
      formattedMsg += formatContent(trimmedLine) + '<br>';
    }
  });

  if (currentSection) {
    formattedMsg += '</span>';
  }

  return formattedMsg;
}

// Modify the ShowPreopScreen use formatPreopMessage
window.ShowPreopScreen = function() {
    UserShowingWhatNowFlag = false;

    var displayContent = $("divDisplayContent");
    if (displayContent) {
        displayContent.innerHTML = "";
        displayContent.style.height = MyContentHeight + "px";
    }

    var caseLog = $("divCaseLog2");
    if (caseLog && typeof caseLog.hide === "function") {
        caseLog.hide();
    }

    var divWrapper = document.createElement("div");
    divWrapper.setAttribute("id", "divPreopWrapper");
    if (displayContent) {
        displayContent.appendChild(divWrapper);
    }

    var divScroll = document.createElement("div");
    divScroll.setAttribute("id", "preopScroller");
    divWrapper.appendChild(divScroll);

    var preopDiv = document.createElement("div");

    if (CurrentCase && CurrentCase.preopMsg) {
        try {
            preopDiv.innerHTML = formatPreopMessage(CurrentCase.preopMsg);
        } catch (error) {
            preopDiv.textContent = CurrentCase.preopMsg;
        }
    }

    divScroll.appendChild(preopDiv);

    if (typeof CreateScroller === "function") {
        CreateScroller("preopScroller");
    }
};

// Call the function
ShowPreopScreen();

function handleButtonClick(action) {
    if (typeof CurrentCase !== 'undefined' && CurrentCase) {
        // Case is running
        switch(action) {
            case 'preop':
                ShowPreopScreen();
                break;
            case 'case-help':
                ShowCaseHelpScreen();
                break;
            case 'case-log':
                ShowCaseLogScreen();
                break;
            case 'new-case':
                ShowNewCaseScreen();
                break;
            default:
                console.warn('Unknown action:', action);
        }
    } else if (action === 'new-case') {
        var caseList = document.getElementById('caseList');
        var selectedCase = caseList ? caseList.value : null;
        if (!selectedCase || selectedCase === 'defaultCase') {
            window.location.href = '/';
            return false;
        }

        var caseAccess = checkCaseAccess(selectedCase);
        if (!caseAccess.isAccessible) {
            UserCaseRunning = false;
            if (typeof MyTimeout !== 'undefined') {
                clearTimeout(MyTimeout);
            }
            switch(caseAccess.reason) {
                case 'subscription-expired':
                    alert('Your subscription has expired. Please renew to access this case.');
                    break;
                case 'requires-pro':
                    alert('This case requires a Pro subscription.');
                    break;
                case 'invalid-case':
                    alert('Invalid case selected.');
                    break;
            }
            ShowNewCaseScreen();
            return false;
        }
        window.location.href = '/';
    }
}

function checkCaseAccess(caseId) {
    if (!window.CaseData || !window.CaseData[caseId]) {
        return { isAccessible: false, reason: 'invalid-case' };
    }
    
    var requiresPro = window.CaseData[caseId] && window.CaseData[caseId].requiresPro || false;
    var userHasPro = window.userStatus === 'Pro';
    var userExpiration = window.userExpiration ? new Date(window.userExpiration) : null;
    var isExpired = userExpiration && userExpiration < new Date();
    
    if (isExpired) {
        return { isAccessible: !requiresPro, reason: 'subscription-expired' };
    }
    
    if (requiresPro && !userHasPro) {
        return { isAccessible: false, reason: 'requires-pro' };
    }
    
    return { isAccessible: true };
}

// exit case popup functionality
const exitWarningModal = document.getElementById('exitWarningModal');
let pendingNavigationUrl = null;

// Add target tab handling
window.handleSettingsNavigation = function(e, type) {
    if (typeof CurrentCase !== 'undefined' && CurrentCase) {
        e.preventDefault();
        e.stopPropagation();
        
        // Store which tab to show
        if (type === 'cases') {
            sessionStorage.setItem('showCases', 'true');
        } else if (type === 'details') {
            sessionStorage.setItem('showDetails', 'true');
        } else if (type === 'change') {
            sessionStorage.setItem('showChangeSettings', 'true');
        }
        
        pendingNavigationUrl = '/settings';
        if (exitWarningModal) {
            exitWarningModal.style.display = 'block';
            setupModalButtons();
        }
        return true;
    }
    return false;
};

function handleExitWarning(e) {
    /* // console.log('Exit warning handler triggered', {
        target: e.target,
        currentCase: typeof CurrentCase !== 'undefined' ? CurrentCase : 'undefined',
        modal: exitWarningModal ? 'exists' : 'missing'
    }); */
	
    // Check specifically for these buttons first
    if (e.target.closest('.view-my-cases') || e.target.closest('.view-my-settings') || e.target.closest('.change-my-settings')) {
        if (typeof CurrentCase !== 'undefined' && CurrentCase) {
            e.preventDefault();
            e.stopPropagation();
            
            if (e.target.closest('.view-my-cases')) {
                pendingNavigationUrl = '/cases';
            } else {
                pendingNavigationUrl = '/profile';
            }
            
            if (exitWarningModal) {
                exitWarningModal.style.display = 'block';
                setupModalButtons();
            }
        }
        return;
    }
    
    const trigger = e.target.closest([
        '.my-account',
        '.logo a', 
        '.footer-menu a',
        'button.logout',
        'a.logout',
        '.view-cases',
        '.view-settings',
        '.settings-active',
        '.change-settings',
        '.settings-switch div',
        '.super-admin-link',
        '.site-tag a',
        '.dev-tag a',
		'.action-button.new-case',
        '.my-settings-btn'
    ].join(','));

    if (!trigger) {
        return;
    }
    
    // Special handling for new case button
	if (trigger.classList.contains('new-case') || trigger.id === 'btnNewCase') {
		pendingNavigationUrl = 'new-case';
	}

    // Special handling for home link
    if (trigger.classList.contains('home-link') || trigger.closest('.logo')) {
        trigger.target = '_self';
    }
    
    if (typeof CurrentCase !== 'undefined' && CurrentCase) {
        e.preventDefault();
        e.stopPropagation();
        
        // Get the URL more safely
        let targetUrl = null;
        if (trigger.href) {
            targetUrl = trigger.href;
        } else if (trigger.querySelector('a')) {
            targetUrl = trigger.querySelector('a').href;
        } else if (trigger.classList.contains('view-cases')) {
            targetUrl = '/cases';
        } else if (trigger.classList.contains('view-settings') || trigger.classList.contains('change-settings')) {
            targetUrl = '/profile';
        }
        
        pendingNavigationUrl = targetUrl;
        
        if (exitWarningModal) {
            exitWarningModal.style.display = 'block';
            setupModalButtons();
        }
    }
}

function setupModalButtons() {
    const btns = {
        save: document.getElementById('saveAndExitBtn'),
        continue: document.getElementById('exitWithoutSaveBtn'),
        cancel: document.getElementById('cancelExitBtn')
    };

    if (btns.save) {
        btns.save.onclick = function() {
            // First show case log screen to generate the log content
            ShowCaseLogScreen();
            
            // Now try to save
            if (typeof saveCaseData === 'function') {
                try {
                    saveCaseData(function() {
						handleExit();
					});
                } catch (error) {
                    // console.error('Error saving case:', error);
                }
            }
        };
    }

    if (btns.continue) {
        btns.continue.onclick = function() {
            handleExit();
        };
    }

    if (btns.cancel) {
        btns.cancel.onclick = function() {
            exitWarningModal.style.display = 'none';
            pendingNavigationUrl = null;
        };
    }
}

document.addEventListener('DOMContentLoaded', function() {
    // Add click handler to entire document
    document.addEventListener('click', handleExitWarning);

    // Add beforeunload handler
    window.onbeforeunload = function(e) {
        // Only show browser alert if NOT triggered by our exit handler
        if (typeof CurrentCase !== 'undefined' && CurrentCase && !pendingNavigationUrl) {
            e.preventDefault();
            e.returnValue = '';
        }
    };
});

function handleExit() {
    clearTimeout(MyTimeout);
    CurrentCase = null;
    exitWarningModal.style.display = 'none';
    if (pendingNavigationUrl) {
        window.location.href = pendingNavigationUrl;
    } else {
        ShowNewCaseScreen();
    }
}

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

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