// add the cases button when going to start a case
// remove the cases button when go back to home by clicking it

(function() {
    const mainContentSection = document.querySelector('.mainContentSection');
    const originalButton = document.getElementById('showCasesList');
    const headerButton = document.querySelector('.showCasesList');
    let savedCaseContent = null;
    let isOnHomePage = true;

    function updateHeaderButton(text, iconClass) {
        if (headerButton) {
            const iconElement = headerButton.querySelector('i');
            if (iconElement) {
                iconElement.className = iconClass;
            }
            const textNode = headerButton.childNodes[headerButton.childNodes.length - 1];
            if (textNode && textNode.nodeType === Node.TEXT_NODE) {
                textNode.textContent = ` ${text}`;
            } else {
                headerButton.appendChild(document.createTextNode(` ${text}`));
            }
            headerButton.style.display = 'inline-flex';
        }
    }

    function updateOriginalButton(text, iconClass) {
        if (originalButton) {
            originalButton.innerHTML = `<i class="${iconClass}"></i> ${text}`;
            originalButton.style.display = 'block';
        }
    }

    function addDisplayCaseActive() {
        if (mainContentSection) {
            mainContentSection.classList.add('displayCaseActive');
        }
        updateHeaderButton('View Cases', 'fas fa-folder');
        updateOriginalButton('', 'fas fa-arrow-circle-left');
        savedCaseContent = $("divDisplayContent").innerHTML;
        isOnHomePage = false;
    }

    function removeDisplayCaseActiveAndRebuildHomePage() {
        if (mainContentSection) {
            mainContentSection.classList.remove('displayCaseActive');
        }
        
        $("divDisplayContent").innerHTML = "";

        var selectcase = document.createElement("div");
        selectcase.setAttribute("id", "selectcase");
        $("divDisplayContent").appendChild(selectcase);

        var fieldset = document.createElement("fieldset");
        fieldset.setAttribute("id", "fieldsetCase");
        selectcase.appendChild(fieldset);

        var legend = document.createElement("legend");
        legend.innerHTML = "Case Library:";
        legend.setAttribute("id", "legendCase");
        fieldset.appendChild(legend);

        var caseList = document.createElement("select");
        caseList.setAttribute("id", "caseList");
        caseList.setAttribute("name", "caseList");
        fieldset.appendChild(caseList);

        var defaultOption = document.createElement("option");
        defaultOption.setAttribute("value", "defaultCase");
        defaultOption.innerHTML = "Select a Case to Start";
        caseList.appendChild(defaultOption);

        var numCasesPlus1 = (VersionStr == "demo") ? 2 : CaseData.length;
        for (var i = 1; i < numCasesPlus1; i++) {
            var option = document.createElement("option");
            option.innerHTML = CaseData[i].title;
            option.setAttribute("value", i);
            caseList.appendChild(option);
        }

        var splashImage = document.createElement("img");
        splashImage.setAttribute("id", "imgSplash");
        splashImage.src = "app/images/anesthSplash.jpg";
        $("divDisplayContent").appendChild(splashImage);

        $("caseList").observe("change", checkDemoRestrictions);

        updateHeaderButton('Back to Case', 'fas fa-arrow-left');
        updateOriginalButton('', 'fas fa-arrow-circle-right');
        isOnHomePage = true;
    }

    function switchToSavedCase() {
        if (savedCaseContent) {
            $("divDisplayContent").innerHTML = savedCaseContent;
            if (mainContentSection) {
                mainContentSection.classList.add('displayCaseActive');
            }
            updateHeaderButton('View Cases', 'fas fa-folder');
            updateOriginalButton('', 'fas fa-arrow-circle-left');
            isOnHomePage = false;
        }
    }

    function checkDemoRestrictions(event) {
        let selectedValue = event.target.value;
        if (selectedValue !== "defaultCase") {
            const selectedCase = CaseData[selectedValue];
            if (selectedCase) {
                if (VersionStr === "demo" && selectedValue != 1) {
                    window.showDemoModal();
                    event.target.value = "defaultCase";
                } else if (selectedCase.isPro && !window.isPro) {
                    window.showUpgradeModal();
                    event.target.value = "defaultCase";
                } else {
                    SetCurrentCase(event);
                    addDisplayCaseActive();
                }
            }
        }
    }

    document.addEventListener('change', (event) => {
        if (event.target.id === 'caseList' && event.target.value !== "defaultCase") {
            addDisplayCaseActive();
        }
    });

    if (originalButton) {
        originalButton.addEventListener('click', () => {
            if (isOnHomePage) {
                switchToSavedCase();
            } else {
                removeDisplayCaseActiveAndRebuildHomePage();
            }
        });
    }

    if (headerButton) {
        headerButton.addEventListener('click', () => {
            if (isOnHomePage) {
                switchToSavedCase();
            } else {
                removeDisplayCaseActiveAndRebuildHomePage();
            }
        });
    }
})();

/* format the content systematically instead of plain text */
/* the same header names of each section must be present for it to work */
// Define the formatPreopMessage function outside of any event listener
// so it's available globally
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 function to use formatPreopMessage
function ShowPreopScreen() {
    UserShowingWhatNowFlag = false;
    $("divDisplayContent").innerHTML = "";
    $("divDisplayContent").style.height = MyContentHeight + "px";
    $("divCaseLog2").hide();
    var divWrapper = document.createElement("div");
    divWrapper.setAttribute("id", "divPreopWrapper");
    $("divDisplayContent").appendChild(divWrapper);
    var divScroll = document.createElement("div");
    divScroll.setAttribute("id", "preopScroller");
    $("divPreopWrapper").appendChild(divScroll);
    
    // Create a div instead of a pre element
    var preopDiv = document.createElement("div");
    // Use the formatPreopMessage function here
    preopDiv.innerHTML = formatPreopMessage(CurrentCase.preopMsg);
    $("preopScroller").appendChild(preopDiv);
    CreateScroller("preopScroller");
}