var items = [];
var selectedWorkItems = [];
var selectedDocId = "";
var selectedReleaseName = "";
var selectedMonitoringTypeFilter = [];
var manualProgress = [];
var allDocuments;
var allDocumentsCurrentPage;
var currentReleasePage;
var filteredDocuments;
var filter = [];
var releaseNameFilter = "";
var allWorkItemTypes = [];
var expandedReleaseWorkItems = [];
var expandedReleaseWorkItemsCurrentPageNumbers = [];
var userguidelink = "";
var userhelplink = "";
let sortAsc = false;
var sortCol;
var pageSize = 50;
var azureAuthenticationHeader = ''
var releaseHealth = [];
var baseAPIUrl = '';
var publisherId = '';
var extensionId = '';
var licensedUserType = '';
const fieldName = "rmUserType";

function showReleaseTrialPill(message) {
    $("#releaseTrialPillText").text(message);
    $("#releaseTrialPill").show();
    $("#startTrialMessage").hide();
}

function hideReleaseTrialPill() {
    $("#releaseTrialPill").hide();
}

$(".grid-container").show();
$("#noReleaseMessage").hide();

function setNewReleaseButtonState(isEnabled) {
    const btn = document.getElementById("newReleaseBtn");
    if (!btn) return;

    // Never enable the button if the user is not a manager
    if (isEnabled && licensedUserType === "0") return;

    btn.disabled = !isEnabled;
    btn.style.opacity = isEnabled ? '1' : '0.5';
    btn.style.cursor = isEnabled ? 'pointer' : 'not-allowed';
}

async function MarkProgress(release) {
    selectedDocId = $(release).attr("data-doc-id");
    var currentProgress = manualProgress.find(o => o.DocumentId == selectedDocId);
    const { value: updatedProgress } = await Swal.fire({
        title: '',
        input: 'text',
        inputLabel: 'Progress percentage',
        inputValue: currentProgress.Progress,
        showCancelButton: true,
        inputValidator: (value) => {
            if (!value) {
                return 'Progress cannot be empty'
            }
        }
    })
    if (updatedProgress) {
        let manualProgressObj = manualProgress.find((o, i) => {
            if (o.DocumentId == selectedDocId) {
                manualProgress[i] = { DocumentId: selectedDocId, Progress: updatedProgress };
                return true;
            }
        })
        manualProgress.find(o => o.DocumentId == selectedDocId).ManualProgress = updatedProgress;
        await IndexLibrary.PostRequest({
            endpoint: '/api/Release/UpdateProgress',
            body: {
                releaseId: selectedDocId,
                progress: updatedProgress
            }
        });

        const Toast = Swal.mixin({
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000,
            didOpen: (toast) => {
                toast.addEventListener('mouseenter', Swal.stopTimer)
                toast.addEventListener('mouseleave', Swal.resumeTimer)
            }
        });

        Toast.fire({
            icon: 'success',
            title: 'Release progress updated successfully.'
        });

        $("#manualProgressBar_" + selectedDocId).attr('style', 'background-color: #0078D4;border-radius:0;width: ' + updatedProgress + '%');
        $("#manualProgressBar_" + selectedDocId).attr('aria-valuenow', updatedProgress + '%');
        $("#manualProgressBar_" + selectedDocId).text(updatedProgress + '%');

    }
}
async function GenerateReleaseNotes(el) {
    const releaseId = el.dataset.docId;
    const releaseName = el.dataset.releaseName;
    window.location.href = 'release-notes.html?rId=' + releaseId + '&rName=' + releaseName;
}

async function PopulateReleaseListTable() {
    var html = '';
    $("#loadingSpinner").show();
    var sortIndicator = (col) => sortCol === col ? (sortAsc ? " <i class='bi bi-caret-up-fill' style='pointer-events:none'></i>" : " <i class='bi bi-caret-down-fill' style='pointer-events:none'></i>") : "";
    html = html + "<table id='releaseListTable' style='width:100%'><thead><tr><th></th><th data-sort='releaseName'>Release Name" + sortIndicator('releaseName') + "</th><th data-sort='releaseStartDate'>Start Date" + sortIndicator('releaseStartDate') + "</th><th data-sort='releaseEndDate'>End Date" + sortIndicator('releaseEndDate') + "</th><th style='width:150px;' data-sort='monitoringType'>Monitoring Type" + sortIndicator('monitoringType') + "</th><th style='width:200px;'>Progress</th><th>Health</th></tr></thead>";
    html = html + "<tbody>"
    var filteredReleasesByMonitoringType = allDocuments.filter((row, index) => {
        if (selectedMonitoringTypeFilter.length > 0) {
            if (selectedMonitoringTypeFilter.includes((allDocuments[index].monitoringType == 0 ? "Automatic" : "Manual"))) {
                return true;
            }
        } else {
            return true;
        }

    });

    var filteredReleases = filteredReleasesByMonitoringType.filter((row, index) => {
        if (releaseNameFilter !== "") {
            if (filteredReleasesByMonitoringType[index].releaseName.toLowerCase().includes(releaseNameFilter.toLocaleLowerCase())) {
                return true;
            }
        } else {
            return true;
        }
    });

    filteredReleases.filter((row, index) => {
        let start = (currentReleasePage - 1) * pageSize;
        let end = currentReleasePage * pageSize;
        if (index >= start && index < end) return true;
    }).forEach(element => {
        var progress = element.automaticCompletionPercentage;
        console.log(progress + "%");
        var sDate = new Date(element.releaseStartDate);
        var eDate = new Date(element.releaseEndDate);
        // Expand/show-workitems button hidden for a while, will re-enable in future
        // html = html + "<tr><td><a href=\"#/\" onclick='ShowReleaseWorkItems(this, \"" + element.releaseId + "\")'><i class=\"bi bi-plus-lg\"></i></a></td><td><div class=\"row-action\"><a href='#' onclick='NavgiateToReleaseDetails(\"" + element.releaseId + "\")'>" + element.releaseName + "</a>" +
        html = html + "<tr><td></td><td><div class=\"row-action\"><a href='#' onclick='NavgiateToReleaseDetails(\"" + element.releaseId + "\")'>" + element.releaseName + "</a>" +

            "<span class=\"float-end hidden-menu\">" +
            //"<button class=\"btn btn-secondary dropdown-toggle caret-off\" type=\"button\" data-bs-toggle=\"dropdown\" aria-expanded=\"false\" style=\"border-radius: 0; background-color: #f0f0f0; color: #757575; border: 0; font-size: 14px;\"></button>" :
            "<div class=\"dropdown\">" +
            "<button class=\"btn btn-secondary dropdown-toggle caret-off\" type=\"button\" data-bs-toggle=\"dropdown\" aria-expanded=\"false\" style=\"border-radius: 0; background-color: var(--da-surface-alt); color: var(--da-text-secondary); border: 0; font-size: 14px;\">...</button>" +
            "<div class=\"dropdown-menu\" style=\"padding-left:8px; border-radius:0\" aria-labelledby=\"dropdownWorkItemTypeFilter\" >" +
            "<span style=\"cursor: pointer; display: flex;align-items: center;font-size:12px\" onclick=\"GenerateReleaseNotes(this)\" data-release-name=\"" + element.releaseName + "\" data-doc-id=\"" + element.releaseId + "\">" +
            "<i class=\"bi bi-file-text-fill\"></i>" +
            "<span class=\"dropdown-item\" style=\"cursor:pointer\">Generate Release Notes</span>" +
            "</span>" +
            (element.monitoringType == 0 ? "" : "<span style=\"cursor: pointer; display: flex;align-items: center;font-size:12px\" onclick=\"MarkProgress(this)\" data-release-name=\"" + element.releaseName + "\" data-doc-id=\"" + element.releaseId + "\">" +
                "<i class=\"bi bi-bar-chart-steps\"></i>" +
                "<span class=\"dropdown-item\" style=\"cursor:pointer\">Mark Progress</span>" +
                "</span>" +
                "</div>" +
                "</div>") +
            "</span></div></td>" +
            "<td>" + sDate.toLocaleDateString("en-US") + "</td>" +
            "<td>" + eDate.toLocaleDateString("en-US") + "</td>" +
            "<td>" + (element.monitoringType == 0 ? "Automatic" : "Manual") + "</td>";
        if (element.monitoringType == 0) {
            html = html + "<td><div class='progress' style='border-radius:0'><div class='progress-bar' role='progressbar' style='background-color: #0078D4;border-radius:0;width: " + progress + "%;' aria-valuenow='" + progress + "' aria-valuemin='0' aria-valuemax='100'>" + progress + "%</div></div></td>";
        } else {
            manualProgress.push({ DocumentId: element.releaseId, Progress: element.manualProgress });
            html = html + "<td><div class='progress' style='border-radius:0;height:20px'><div id='manualProgressBar_" + element.releaseId + "' class='progress-bar' role='progressbar' style='background-color: #0078D4;border-radius:0;width: " + element.manualProgress + "%;' aria-valuenow='" + element.manualProgress + "' aria-valuemin='0' aria-valuemax='100'>" + element.manualProgress + "%</div></div></td>";
        }
        var cachedReleaseHealth = releaseHealth.find(x => x.releaseId == element.releaseId);
        if (cachedReleaseHealth !== undefined) {
            var releaseHealthStatusText = GetHealthStatusText(cachedReleaseHealth.releaseHealth);
            var releaseHealthColor = GetHealthStatusColor(releaseHealthStatusText);
            html = html + "<td style='background-color: " + releaseHealthColor + "' id='releaseHealth_" + element.releaseId + "'>" + releaseHealthStatusText + "</td>"
        } else {
            html = html + "<td id='releaseHealth_" + element.releaseId + "'>Calculating...</td>"
        }
        html = html + "</tr>"
    });

    html = html + "</tbody></table>"
    $(".grid-container").html(html);
    var releasePagesCount = Math.ceil(allDocuments.length / pageSize);
    if (releasePagesCount > 1) {
        var releasePagingHtml = '';
        releasePagingHtml = releasePagingHtml + "<button class=\"pagination-button\" onclick='GoBackReleasePaging()' id='releasePaging'><</button>";
        for (var i = 1; i <= releasePagesCount; i++) {
            releasePagingHtml = releasePagingHtml + "<button class=\"pagination-button\" onclick='GotoReleasePage(\"" + i + "\")'>" + i + "</button>";
        }
        releasePagingHtml = releasePagingHtml + "<button class=\"pagination-button\" onclick='GoForwardReleasePaging()' id='releasePaging_forward'>></button>";
        $("#releaseGridPaging").html(releasePagingHtml);
    }


    $("#newReleaseBtn").show();
    $("#loadingSpinner").hide();
    $("#releaseListTable").resizableColumns();

    document.querySelectorAll('#releaseListTable thead tr th').forEach(t => {
        t.addEventListener('click', sort, false);
    });
}

function GoBackReleasePaging() {
    if (currentReleasePage > 1) {
        currentReleasePage--;
        $("#releaseListTable").remove();
        PopulateReleaseListTable();
    }
}

function GoForwardReleasePaging() {
    var totalReleasePages = Math.ceil(allDocuments.length / pageSize);
    if ((parseInt(currentReleasePage) + 1) > totalReleasePages)
        return true;

    currentReleasePage++;
    $("#releaseListTable").remove();
    PopulateReleaseListTable();
}

function GotoReleasePage(pageIndex) {
    currentReleasePage = pageIndex;
    $("#releaseListTable").remove();
    PopulateReleaseListTable();
}


async function CreateTrialLicense() {

    await IndexLibrary.AutoCreateTrialLicense(true);
}


function GetHealthStatusColor(workItemHealthStatusText) {
    switch (workItemHealthStatusText) {
        case "On Track":
            return "green"
        case "On Track (Overridden)":
            return "green"
        case "At Risk":
            return "yellow"
        case "Off Track":
            return "red"
        case "Undetermined":
            return "whitesmoke"
    }
}

async function CheckMappingConfiguration() {
    const response = await IndexLibrary.GetRequest({
        endpoint: '/api/Settings/GeReleasetWorkItemFieldMappings'
    });
    const workItemFieldsMap = await response.json();
    var startDateMappedField = workItemFieldsMap.find(x => x.fieldName == 'StartDate').mappedField;
    var endDateMappedField = workItemFieldsMap.find(x => x.fieldName == 'EndDate').mappedField;
    var effortMappedField = workItemFieldsMap.find(x => x.fieldName == 'Effort').mappedField;
    if (startDateMappedField == 'None' || endDateMappedField == 'None' || effortMappedField == 'None') {
        $("#missingFieldMappingsMsg").show();
    }
}

function GetHealthStatusText(status) {
    switch (status) {
        case 0:
            return "On Track"
        case 1:
            return "On Track (Overridden)"
        case 2:
            return "At Risk"
        case 3:
            return "Off Track"
        case 4:
            return "Undetermined"
        case 5:
            return "Undetermined"
    }
}

const RELEASE_LIST_SORT_STORAGE_KEY = "releaseListSort";

function SaveReleaseListSort() {
    try {
        if (sortCol === undefined) return;
        localStorage.setItem(RELEASE_LIST_SORT_STORAGE_KEY, JSON.stringify({ sortCol: sortCol, sortAsc: sortAsc }));
    } catch (err) {
        console.error("Failed to persist release list sort:", err);
    }
}

function LoadReleaseListSort() {
    try {
        var saved = localStorage.getItem(RELEASE_LIST_SORT_STORAGE_KEY);
        if (!saved) return;
        var parsed = JSON.parse(saved);
        if (parsed && parsed.sortCol) {
            sortCol = parsed.sortCol;
            sortAsc = !!parsed.sortAsc;
        }
    } catch (err) {
        console.error("Failed to load release list sort:", err);
    }
}

function ApplyReleaseListSort() {
    if (!sortCol || !Array.isArray(allDocuments)) return;
    allDocuments.sort((a, b) => {
        if (a[sortCol] < b[sortCol]) return sortAsc ? 1 : -1;
        if (a[sortCol] > b[sortCol]) return sortAsc ? -1 : 1;
        return 0;
    });
}

function sort(e) {
    let thisSort = e.target.dataset.sort;
    if (sortCol === thisSort) sortAsc = !sortAsc;
    sortCol = thisSort;
    if ($(e.target).closest('table').attr('id') == "releaseListTable") {
        ApplyReleaseListSort();
        SaveReleaseListSort();
        PopulateReleaseListTable();
    } else if ($(e.target).closest('table').attr('id').startsWith('selectedWorkItemsTable')) {
        var releaseId = $(e.target).closest('table').attr('id').split('_')[1];
        var index = expandedReleaseWorkItems.findIndex(x => x.releaseId == releaseId);
        var releaseRow = document.getElementById("selectedWorkItemsTableRow_" + releaseId).previousElementSibling
        expandedReleaseWorkItems[index].workItems.sort((a, b) => {
            if (a.fields[sortCol] < b.fields[sortCol]) return sortAsc ? 1 : -1;
            if (a.fields[sortCol] > b.fields[sortCol]) return sortAsc ? -1 : 1;
            return 0;
        });
        $("#selectedWorkItemsTableRow_" + releaseId).remove();
        CreateShellWorkItemsTable(releaseRow, releaseId);
        PopulateReleaseWorkItems(releaseId);
    }
}

async function NavigateToCreateRelease() {
    var orgName = await IndexLibrary.GetAccountNameAsync();
    var projectName = await IndexLibrary.GetCurrentProjectName();

    var newUrl = "https://dev.azure.com/" + orgName + "/" + projectName + "/_apps/hub/" + publisherId + "." + extensionId + ".release-groups-hub-group.create-release";

    IndexLibrary.NavigateToUrl(newUrl);
}
async function NavgiateToReleaseDetails(releaseId) {
    var orgName = await IndexLibrary.GetAccountNameAsync();
    var projectName = await IndexLibrary.GetCurrentProjectName();

    var newUrl = "https://dev.azure.com/" + orgName + "/" + projectName + "/_apps/hub/" + publisherId + "." + extensionId + ".release-groups-hub-group.create-release?rId=" + releaseId;

    IndexLibrary.NavigateToUrl(newUrl);
}

async function GetWorkItemRowHtml(workitemId, workitemTitle, workitemType, workitemProject, workitemState, releaseId, startDate, endDate) {
    var rowId = workitemId + "_" + workitemProject;
    var deleteButtonId = "delete_" + rowId;
    var releaseHealthObj = releaseHealth.find(x => x.releaseId == releaseId);
    var workItemHealthObj = releaseHealthObj.workItemsHealth.find(x => x.workItemId == workitemId);
    var workItemHealthStatusText = GetHealthStatusText(workItemHealthObj.workItemTrackingHealth);
    var workItemHealthStatusColor = GetHealthStatusColor(workItemHealthStatusText);
    var sDate = new Date(startDate);
    var eDate = new Date(endDate);
    var currentProjectName = await IndexLibrary.GetCurrentProjectName();
    var workItemUrl = "https://dev.azure.com/" + await IndexLibrary.GetAccountNameAsync() + "/" + currentProjectName + "/_workitems/edit/" + workitemId + "/";
    return "<tr id='" + rowId + "' class='workItemRow' data-delete-button-id='" + deleteButtonId + "'>" + "<td style='vertical-align:top'>" + "<a href='" + workItemUrl + "' target='_blank' style='color:#0078d4; text-decoration:underline;'>" + workitemId + "</a>" + "</td>" +
        "<td style='padding-bottom: 10px; width:42%'>" + "<a href='" + workItemUrl + "' target='_blank' style='color:#0078d4; text-decoration:underline;'>" + workitemTitle + "</a>" + "</td>" +
        "<td>" + "<img class='suggestion' src='" + allWorkItemTypes.find(x => x.name == workitemType).iconUrl + "' style='width: 14px;min-width: 14px;height: 14px;' />" + "<span style='padding-left:5px'>" + workitemType + "</span>" + "</td>" +
        "<td>" + formatDateAsDevOpsDate(startDate) + "</td>" +
        "<td>" + formatDateAsDevOpsDate(endDate) + "</td>" +
        "<td>" + workitemProject + "</td>" +
        "<td>" + workitemState + "</td>" +
        "<td style='background-color: " + workItemHealthStatusColor + "'>" + workItemHealthStatusText + "</td>" + "</tr>";
}
function formatDateAsDevOpsDate(dateString) {
    if (!dateString) return "Unavailable";
    const parts = dateString.substring(0, 10).split("-");
    const year = parts[0];
    const month = parseInt(parts[1], 10);
    const day = parseInt(parts[2], 10);
    return month + "/" + day + "/" + year;
}


function OpenWorkItemDialog(workItemId) {
    IndexLibrary.Navigate(workItemId);
}

function PreviousWorkItemPage(releaseId) {
    var expandedRowIndex = expandedReleaseWorkItemsCurrentPageNumbers.findIndex(x => x.releaseId == releaseId);
    var currentPage = expandedReleaseWorkItemsCurrentPageNumbers[expandedRowIndex].pageNumber;

    if (currentPage > 1) expandedReleaseWorkItemsCurrentPageNumbers[expandedRowIndex].pageNumber--;

    var releaseRow = document.getElementById("selectedWorkItemsTableRow_" + releaseId).previousElementSibling;
    $("#selectedWorkItemsTableRow_" + releaseId).remove();
    CreateShellWorkItemsTable(releaseRow, releaseId);
    PopulateReleaseWorkItems(releaseId);

}

function NextWorkItemPage(releaseId) {
    var expandedRowIndex = expandedReleaseWorkItemsCurrentPageNumbers.findIndex(x => x.releaseId == releaseId);
    var currentPage = expandedReleaseWorkItemsCurrentPageNumbers[expandedRowIndex].pageNumber;
    var releaseWorkItemsIndex = expandedReleaseWorkItems.findIndex(e => e.releaseId === releaseId);

    if ((currentPage * pageSize) < expandedReleaseWorkItems[releaseWorkItemsIndex].workItems.length) expandedReleaseWorkItemsCurrentPageNumbers[expandedRowIndex].pageNumber++;

    var releaseRow = document.getElementById("selectedWorkItemsTableRow_" + releaseId).previousElementSibling;
    $("#selectedWorkItemsTableRow_" + releaseId).remove();
    CreateShellWorkItemsTable(releaseRow, releaseId);
    PopulateReleaseWorkItems(releaseId);

}

function GotoWorkItemPage(pageNumber, releaseId) {
    var expandedRowIndex = expandedReleaseWorkItemsCurrentPageNumbers.findIndex(x => x.releaseId == releaseId);
    var releaseRow = document.getElementById("selectedWorkItemsTableRow_" + releaseId).previousElementSibling;
    expandedReleaseWorkItemsCurrentPageNumbers[expandedRowIndex].pageNumber = pageNumber;
    $("#selectedWorkItemsTableRow_" + releaseId).remove();
    CreateShellWorkItemsTable(releaseRow, releaseId);
    PopulateReleaseWorkItems(releaseId);
}

async function PopulateReleaseWorkItems(releaseId) {
    var releaseWorkItemsIndex = expandedReleaseWorkItems.findIndex(e => e.releaseId === releaseId);
    releaseWorkItems = expandedReleaseWorkItems[releaseWorkItemsIndex].workItems;
    var totalWorkItems = expandedReleaseWorkItems[releaseWorkItemsIndex].workItems.length;
    var numberOfPages = Math.ceil(totalWorkItems / pageSize);
    if (totalWorkItems === 0) {
        $("#paginationFooter_" + releaseId).hide();
        $("#loadingSpinner_" + releaseId).hide();
        return;
    }

    if (numberOfPages > 1) {
        var paginationHtml = '';
        for (var pageNumber = 1; pageNumber <= numberOfPages; pageNumber++) {
            paginationHtml = paginationHtml + "<button class='pagination-button' onclick=\"GotoWorkItemPage('" + pageNumber + "','" + releaseId + "')\" id='page_" + releaseId + "_" + pageNumber + "'>" + pageNumber + "</button>";
        }
        $("#pagination_" + releaseId).html(paginationHtml);
        $("#paginationFooter_" + releaseId).show();
    } else {
        $("#paginationFooter_" + releaseId).hide();
    }
    releaseWorkItems.filter((row, index) => {
        var expandedRowIndex = expandedReleaseWorkItemsCurrentPageNumbers.findIndex(x => x.releaseId == releaseId);
        var currentPage = expandedReleaseWorkItemsCurrentPageNumbers[expandedRowIndex].pageNumber;
        let start = (currentPage - 1) * pageSize;
        let end = currentPage * pageSize;
        if (index >= start && index < end) return true;
    }).forEach(async c => {
        var rowHtml = await GetWorkItemRowHtml(c.id, c.title, c.type, c.project, c.state, releaseId, c.startDate, c.endDate);
        selectedWorkItems.push(parseInt(c.id));
        $('#selectedWorkItemsTable_' + releaseId + ' tr:last').after(rowHtml);

    });

    $("#loadingSpinner_" + releaseId).hide();
}

function CreateShellWorkItemsTable(row, releaseId) {
    var html = '';
    var tableId = 'selectedWorkItemsTable_' + releaseId;
    html = html + "<table id='" + tableId + "' style='width:100%'><thead><tr><th data-sort='Id'>Id</th><th data-sort='Title'>Title</th><th data-sort='Type'>Type</th><th data-sort='StartDate'>Start Date</th><th data-sort='EndDate'>End Date</th><th data-sort='Project' style='width:150px;'>Project</th><th data-sort='State'>State</th><th style='width:109.953px'>Health</th></tr></thead>";
    html = html + "<tbody>"
    html = html + "<tr><td colspan='6'><div style='display:flex;justify-content: center;'><div id='loadingSpinner_" + releaseId + "' class='spinner-border' style='width: 3rem; height: 3rem;' role='status'><span class='sr-only'></span></div></div></td>" +
        "</tbody></table>";
    html = html + "<span id='paginationFooter_" + releaseId + "' style='float: right; display:none;padding-top:10px;padding-bottom:10px'><button onclick=\"PreviousWorkItemPage('" + releaseId + "')\" id=\"prevButton_" + releaseId + "\"><</button><span id='pagination_" + releaseId + "'></span><button onclick=\"NextWorkItemPage('" + releaseId + "')\" id=\"nextButton_" + releaseId + "\">></button></span>"
    $(row).closest('tr').after('<tr id="selectedWorkItemsTableRow_' + releaseId + '"><td><td colspan="6">' + html + '</td></tr>');
    document.querySelectorAll('#' + tableId + ' thead tr th').forEach(t => {
        t.addEventListener('click', sort, false);
    });
}
async function ShowReleaseWorkItems(row, releaseId) {
    if (row.children[0].classList.contains('bi-plus-lg')) {
        row.children[0].classList.remove('bi-plus-lg');
        row.children[0].classList.add('bi-dash-lg');
    } else {
        row.children[0].classList.remove('bi-dash-lg');
        row.children[0].classList.add('bi-plus-lg');
        $("#selectedWorkItemsTableRow_" + releaseId).remove();
        var expandedReleaseWorkItemsRowIndex = expandedReleaseWorkItems.findIndex(x => x.releaseId == releaseId);
        if (expandedReleaseWorkItemsRowIndex > -1) {
            expandedReleaseWorkItems.splice(expandedReleaseWorkItemsRowIndex, 1);
        }
        return true;
    }

    CreateShellWorkItemsTable(row, releaseId);
    $("#loadingSpinner_" + releaseId).show();
    const releaseResponse = await IndexLibrary.GetRequest({
        endpoint: `/api/Release/Get/${releaseId}`
    });
    const releaseData = await releaseResponse.json();

    if (releaseData.workItems == '') {
        $('#selectedWorkItemsTable_' + releaseId + ' tbody').html('<tr>' + '<td colspan="8" style="text-align:center; padding:12px; background:var(--da-surface);color:var(--da-text);">' + 'No workitems defined for this release' + '</td>' + '</tr>');
        $("#loadingSpinner_" + releaseId).hide();
        return;
    }

    const releaseWorkItemsResponse = await IndexLibrary.PostRequest({
        endpoint: `/api/AzureDevOps/GetReleaseWorkItemsByIds`,
        body: { workItemIds: releaseData.workItems }
    });
    const releaseWorkItems = await releaseWorkItemsResponse.json();
    if (releaseWorkItems.length == 0) {
        $('#selectedWorkItemsTable_' + releaseId + ' tbody').html('<tr>' + '<td colspan="8" style="text-align:center; padding:12px; background:var(--da-surface);color:var(--da-text);">' + 'No workitems defined for this release' + '</td>' + '</tr>');
        $("#loadingSpinner_" + releaseId).hide();
    } else {
        if (!expandedReleaseWorkItems.find(x => x.releaseId == releaseId)) {
            var expandedReleaseWorkItemsObj = {};
            expandedReleaseWorkItemsObj.releaseId = releaseId;
            expandedReleaseWorkItemsObj.workItems = releaseWorkItems;
            expandedReleaseWorkItems.push(expandedReleaseWorkItemsObj);
        }
        if (!expandedReleaseWorkItemsCurrentPageNumbers.find(x => x.releaseId == releaseId)) {
            var expandedReleaseWorkItemsCurrentPageNumbersObj = {};
            expandedReleaseWorkItemsCurrentPageNumbersObj.releaseId = releaseId;
            expandedReleaseWorkItemsCurrentPageNumbersObj.pageNumber = 1;
            expandedReleaseWorkItemsCurrentPageNumbers.push(expandedReleaseWorkItemsCurrentPageNumbersObj);
        }
        PopulateReleaseWorkItems(releaseId);
    }


}

$(document).ready(async function () {
    await applyNewReleaseUserPermission()
    $("#missingFieldMappingsMsg").hide();
    const organizationName = await IndexLibrary.GetAccountNameAsync();
    const projectName = await IndexLibrary.GetCurrentProjectName();
    let data = { organizationName: organizationName };
    try {
        const config = await IndexLibrary.GetExtensionConfig();
        baseAPIUrl = config.apiBaseUrl;
        publisherId = config.publisherId;
        extensionId = config.extensionId;
        userguidelink = config.userguidelink;
        userhelplink = config.userhelplink;

        const settingsPromise = IndexLibrary.GetRequest({
            endpoint: '/api/Settings/Get'
        });
        const releasesPromise = IndexLibrary.GetRequest({
            endpoint: `/api/Release/GetReleases/${projectName}`
        });

        const getLicenseResponse = await IndexLibrary.PostRequest({
            endpoint: '/api/License/GetLicense',
            body: data
        });

        if (getLicenseResponse.status == 404) {
            hideReleaseTrialPill();
            $("#startTrialMessage").show();
            CreateTrialLicense();
            setNewReleaseButtonState(false);
        } else {
            const licenseData = await getLicenseResponse.json();
            if (licenseData.status !== undefined && licenseData.status == 404) {
                hideReleaseTrialPill();
                $("#startTrialMessage").show();
                CreateTrialLicense();
                setNewReleaseButtonState(false);
            } else {
                const userLicenseResponse = await IndexLibrary.GetRequest({
                    endpoint: `/api/License/IsUserLicensed?organizationName=${organizationName}&email=${IndexLibrary.GetUserEmail()}&moduleUserType=devOpsAssist`
                });
                const isUserLicensed = await userLicenseResponse.text();

                if (isUserLicensed.toLowerCase() == 'false') {
                    hideReleaseTrialPill();
                    setNewReleaseButtonState(false);
                    $("#authorizationErrorMessage").show();
                    $("#authorizationErrorMessage").text("You are not authorized to perform this action. Please contact your organization administrator.");
                    $("#startTrialMessage").hide();
                    $("#loadingSpinner").hide();
                    $("#releaseListBody").hide();
                    $("#noReleaseMessage").hide();
                    return;
                } else {
                    if (licenseData.licenseType == 0) {
                        var licenseExpiryDate = new Date(licenseData.expiryDateTimeUtc);
                        if (licenseExpiryDate < new Date()) {
                            hideReleaseTrialPill();
                            $("#startTrialMessage").show();
                            setNewReleaseButtonState(false);
                            $("#startTrialMessage").text("Your license is invalid or expired. Please contact your organization administrator.");
                        } else {
                            showReleaseTrialPill(`Trial until ${licenseExpiryDate.toLocaleDateString("en-US")}`);
                            setNewReleaseButtonState(true);
                        }
                    } else {
                        hideReleaseTrialPill();
                        $("#startTrialMessage").hide();
                        setNewReleaseButtonState(true);
                    }
                }
                await CheckMappingConfiguration();
            }
        }

        const settingsResponse = await settingsPromise;
        const settingsData = await settingsResponse.json();
        pageSize = settingsData.pageSizeForTables;

        const releasesResponse = await releasesPromise;
        allDocuments = await releasesResponse.json();
        LoadReleaseListSort();
        ApplyReleaseListSort();
        currentReleasePage = 1;
        await PopulateReleaseListTable();
        //$("#loadingSpinner").hide();
        $("#releaseListBody").show();
        $("#noReleaseMessage").hide();

        allDocuments.forEach(async element => {
            const healthResponse = await IndexLibrary.GetRequest({
                endpoint: `/api/Release/GetReleaseHealth?releaseId=${element.releaseId}`
            });
            const releaseHealthResponse = await healthResponse.json();
            releaseHealth.push(releaseHealthResponse);
            var healthStatusText = GetHealthStatusText(releaseHealthResponse.releaseHealth);
            $("#releaseHealth_" + element.releaseId).text(healthStatusText);
            $("#releaseHealth_" + element.releaseId).attr('style', 'background-color: ' + GetHealthStatusColor(healthStatusText));
        });
    } catch (error) {
        $("#startTrialMessage").show();
        setNewReleaseButtonState(false);
    }

    $("#txtReleaseNameFilter").keyup(function () {
        // $("#loadingSpinner").show();
        releaseNameFilter = $("#txtReleaseNameFilter").val();
        PopulateReleaseListTable();
    });
    $("#chkAutomaticFilter").click(function () {
        // $("#loadingSpinner").show();
        if ($(this).is(":checked")) {
            selectedMonitoringTypeFilter.push("Automatic");
        } else {
            var itemIndex = selectedMonitoringTypeFilter.indexOf("Automatic");
            if (itemIndex > -1) {
                selectedMonitoringTypeFilter.splice(itemIndex, 1);
            }
        }
        if (selectedMonitoringTypeFilter.length == 0) {
            $("#dropdownMonitoringTypeFilter").text("Monitoring Type");
            $("#dropdownMonitoringTypeFilter").css("font-weight", "normal");
            $("#dropdownMonitoringTypeFilter").css("color", "#757575");
        } else {
            $("#dropdownMonitoringTypeFilter").text(selectedMonitoringTypeFilter[0] + (selectedMonitoringTypeFilter.length > 1 ? "(+1)" : ""));
            $("#dropdownMonitoringTypeFilter").css("font-weight", "bold");
            $("#dropdownMonitoringTypeFilter").css("color", "black");
        }
        PopulateReleaseListTable();
    });
    $("#chkManualFilter").click(function () {
        //$("#loadingSpinner").show();
        if ($(this).is(":checked")) {
            selectedMonitoringTypeFilter.push("Manual");
        } else {
            var itemIndex = selectedMonitoringTypeFilter.indexOf("Manual");
            if (itemIndex > -1) {
                selectedMonitoringTypeFilter.splice(itemIndex, 1);
            }
        }
        if (selectedMonitoringTypeFilter.length == 0) {
            $("#dropdownMonitoringTypeFilter").text("Monitoring Type");
            $("#dropdownMonitoringTypeFilter").css("font-weight", "normal");
            $("#dropdownMonitoringTypeFilter").css("color", "#757575");
        } else {
            $("#dropdownMonitoringTypeFilter").text(selectedMonitoringTypeFilter[0] + (selectedMonitoringTypeFilter.length > 1 ? "(+1)" : ""));
            $("#dropdownMonitoringTypeFilter").css("font-weight", "bold");
            $("#dropdownMonitoringTypeFilter").css("color", "black");
        }
        PopulateReleaseListTable();
    });

});
async function applyNewReleaseUserPermission() {
    const newReleaseBtn = document.getElementById("newReleaseBtn");
    if (!newReleaseBtn) return;

    try {
        licensedUserType = await IndexLibrary.GetUserLicensesType(fieldName);
        if (licensedUserType === "0") {
            newReleaseBtn.disabled = true;
            newReleaseBtn.classList.add("disabled");
            newReleaseBtn.style.opacity = '0.5';
            newReleaseBtn.style.cursor = 'not-allowed';
            newReleaseBtn.title = "Only Manager can create new release";
        }

    } catch (err) {
        console.error("Failed to apply New Release permission:", err);
        newReleaseBtn.disabled = true;
    }
}
function openUserGuideLink() {
    IndexLibrary.openInNewTab(userguidelink);
}

function openUserHelpLink() {
    IndexLibrary.openInNewTab(userhelplink);
}