var allWorkItemTypes = [];
var selectedWorkItemTypesFilter = [];
var selectedWorkItemStatesFilter = [];
var selectedWorkItems = [];
var selectedWorkItemDetails = {};
var editMode = false;
var editReleaseId = '';
var organizationId = '';
var organizationName = '';
var optimalRolloutSettings = '';
var userguidelink = "";
var userhelplink = "";
var pageSize = 50;
var workItemsSuggestionsTimer;
var publisherId = "";
var extensionId = "";
const moduleName = "rmUserType";

function escapeHtml(value) {
    if (typeof IndexLibrary !== 'undefined' && IndexLibrary.escapeHtml) {
        return IndexLibrary.escapeHtml(value);
    }

    return String(value == null ? "" : value)
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#39;");
}

function sanitizeImageUrl(url) {
    var value = String(url == null ? "" : url).trim();
    return /^(https?:\/\/|\/)/i.test(value) ? value : "";
}

function isReleaseSelected() {
    return !!editReleaseId;
}

function showReleaseActionButtons() {
    $("#btnDeleteRelease").show();
    $("#btnReleaseNotes").show();

    if (typeof window.ShowPlanningView === 'function') {
        setTimeout(function () { window.ShowPlanningView(); }, 0);
    }
}

function applyMonitoringMode(isAutomatic) {
    $("#automaticMonitoringCheck").prop("checked", isAutomatic);
    $("#manualMonitoringCheck").prop("checked", !isAutomatic);
    $(".completionPercentage").css("visibility", isAutomatic ? "hidden" : "visible");
    $(".releaseHealth").prop("disabled", isAutomatic);
}

async function Save() {
    if (!MandatoryFieldsFilled()) {
        return;
    }

    $("#msg").hide();

    if (selectedWorkItems.length === 0) {
        const confirmed = await IndexLibrary.showConfirmDialog({
            text: "No work items have been selected. Do you want to continue saving ?"
        });

        if (!confirmed) {
            return;
        }
    }

    await SaveRelease(selectedWorkItems);
}

function WorkItemFilterKeyUp() {
    if ($("#txtFilter").val() == "") {
        $("#taskSuggestions").html("");
        $("#taskSuggestions").hide();
    } else {

        workItemsSuggestionsTimer = window.setTimeout(GetWorkItemSuggestions, 300);
    }
}
function WorkItemFilterKeyDown() {
    window.clearTimeout(workItemsSuggestionsTimer);
}

$(document).on('click', '.chkWorkItemFilter', function () {
    const type = $(this).data("work-item-type");

    if (this.checked) {
        selectedWorkItemTypesFilter.push(type);
    } else {
        selectedWorkItemTypesFilter =
            selectedWorkItemTypesFilter.filter(x => x !== type);
    }
});

$(document).on('click', '.chkWorkItemStateFilter', function () {
    const state = $(this).data("work-item-state");

    if (this.checked) {
        selectedWorkItemStatesFilter.push(state);
    } else {
        selectedWorkItemStatesFilter =
            selectedWorkItemStatesFilter.filter(x => x !== state);
    }
});


async function ShowEditMode() {
    await applyNewReleaseUserPermission();
    showReleaseActionButtons();

    try {
        const response = await IndexLibrary.GetRequest({
            endpoint: `/api/Release/Get/${editReleaseId}`
        });

        if (!response.ok) {
            if (response.status === 404) {
                await IndexLibrary.ShowToast('error', `Release with ID ${editReleaseId} not found.`);
                await NavigateToCreateRelease();
                return;
            } else {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
        }

        const releaseData = await response.json();
        await handleShowEditModeData(releaseData);
    } catch (error) {
        console.error("Error loading release:", error);
        await IndexLibrary.ShowToast('error', "Failed to load release");
    }
}

async function handleShowEditModeData(releaseData) {
    var sDate = new Date(releaseData.releaseStartDate);
    var eDate = new Date(releaseData.releaseEndDate);
    organizationId = releaseData.organizationId;
    organizationName = releaseData.organizationName;
    $("#releaseName").val(releaseData.releaseName);
    $("#releaseStartDate").val(sDate.toLocaleDateString("en-US"));
    $("#releaseEndDate").val(eDate.toLocaleDateString("en-US"));
    $("#heading").text(releaseData.releaseName);
    updateKebabDropdownState();
    $("#completionPercentageValue").val(releaseData.manualProgress);
    $("#releaseState").text(releaseData.releaseState);
    $("#ddlReleaseHealth").val(releaseData.releaseHealth);
    applyMonitoringMode(releaseData.monitoringType == 0);

    try {
        const response = await IndexLibrary.PostRequest({
            endpoint: `/api/AzureDevOps/GetReleaseWorkItemsByIds`,
            body: { workItemIds: releaseData.workItems }
        });

        if (!response.ok) {
            throw new Error("Failed to load work items");
        }

        const editWorkItems = await response.json();
        selectedWorkItems = editWorkItems.map(wi => parseInt(wi.id));
        $("#loadingSpinner").hide();
    } catch (error) {
        console.error("Error loading work items:", error);
        await IndexLibrary.ShowToast('error', "Failed to load work items");
    }
}

async function AddOrRemoveWorkItem(item) {
    var id = parseInt(item.dataset['workitemId']);
    var itemIndex = selectedWorkItems.indexOf(id);
    if (itemIndex == -1) {
        selectedWorkItems.push(id);
        selectedWorkItemDetails[id] = {
            id: id,
            title: item.dataset['workitemTitle'],
            type: item.dataset['workitemType'],
            state: item.dataset['workitemState'],
            start: item.dataset['workitemStartDate'],
            end: item.dataset['workitemEndDate'],
            project: item.dataset['workitemProject']
        };
    } else {
        selectedWorkItems.splice(itemIndex, 1);
        delete selectedWorkItemDetails[id];
    }
    if (typeof window.RefreshPlanningView === 'function') {
        window.RefreshPlanningView();
    }
    SaveRelease(selectedWorkItems);
}

function MandatoryFieldsFilled() {
    var message = '';
    for (var i = 0; i < $(".required").length; i++) {
        if ($(".required")[i].value.trim() == '') {
            if (message == '')
                message = message + "<span>" + $(".required")[i].dataset.msg;
            else {
                message = message + ' , ' + $(".required")[i].dataset.msg;
            }
        }
    }
    if (message != '') {
        message = message + " cannot be empty. </span>";
    }
    var sDate = Date.parse($("#releaseStartDate").val());
    var eDate = Date.parse($("#releaseEndDate").val());
    if (sDate > eDate)
        message = message + "<br /><span>Release end date cannot be less than start date.</span>"

    if (message != '') {
        $("#msg").addClass("alert");
        $("#msg").addClass("alert-danger");
        $("#msg").attr('role', 'alert');
        $("#msg").html(message);
        $("#msg").show();
        return false;
    }


    return true;
}

async function buildReleasePayload(selectedWorkItems, overrides = {}) {
    const currentProjectName = await IndexLibrary.GetCurrentProjectName();
    return {
        releaseName: $("#releaseName").val(),
        releaseStartDate: $("#releaseStartDate").val(),
        releaseEndDate: $("#releaseEndDate").val(),
        monitoringType: $("#automaticMonitoringCheck").is(':checked') ? 0 : 1,
        manualProgress: $("#automaticMonitoringCheck").is(':checked') ? 0 : ($("#completionPercentageValue").val().trim() == "" ? 0 : $("#completionPercentageValue").val()),
        releaseStatus: 0,
        organizationName: organizationName,
        organizationId: organizationId,
        workItems: selectedWorkItems.toString(),
        releaseHealth: $("#automaticMonitoringCheck").is(':checked') ? 5 : parseInt($("#ddlReleaseHealth").val()),
        projectName: currentProjectName,
        ...overrides
    };
}

async function handleSaveReleaseSuccess(json, isCreate) {
    await IndexLibrary.ShowToast('success', isCreate ? 'Release created successfully.' : 'Release updated successfully.');
    editMode = true;
    editReleaseId = json.releaseId ?? json.id ?? editReleaseId;
    updateKebabDropdownState();
    $("#heading").text($("#releaseName").val());
    showReleaseActionButtons();
}

async function SaveRelease(selectedWorkItems) {
    try {
        const payload = await buildReleasePayload(selectedWorkItems, editMode ? { releaseId: editReleaseId } : {});
        const endpoint = editMode ? "/api/Release/Update" : "/api/Release/Create";

        const response = await IndexLibrary.PostRequest({
            endpoint: endpoint,
            headers: { "UserEmail": IndexLibrary.GetUserEmail() },
            body: payload
        });

        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(errorText || 'Failed to save release');
        }

        const json = await response.json();
        await handleSaveReleaseSuccess(json, !editMode);
    } catch (error) {
        console.error('Error saving release:', error);
        await IndexLibrary.ShowToast('error', error?.message || 'Failed to save release');
    }
}

function updateKebabDropdownState() {
    const isReleaseSaved = isReleaseSelected();
    const renameBtn = document.querySelector('.header-kebab .rename-project');
    const deleteBtn = document.querySelector('.header-kebab .delete-project');

    if (renameBtn) {
        renameBtn.disabled = !isReleaseSaved;
        renameBtn.style.opacity = isReleaseSaved ? '1' : '0.5';
        renameBtn.style.cursor = isReleaseSaved ? 'pointer' : 'not-allowed';
    }

    if (deleteBtn) {
        deleteBtn.disabled = !isReleaseSaved;
        deleteBtn.style.opacity = isReleaseSaved ? '1' : '0.5';
        deleteBtn.style.cursor = isReleaseSaved ? 'pointer' : 'not-allowed';
    }
}

async function OpenRenameReleaseModal() {
    if (!isReleaseSelected()) {
        await IndexLibrary.ShowToast('error', "No release selected!");
        return;
    }

    const currentName = $("#releaseName").val() || "";

    const newName = await IndexLibrary.showInputDialog({
        title: "Rename Release",
        inputLabel: "Release Name",
        inputValue: currentName,
        confirmButtonText: "Save",
        cancelButtonText: "Cancel",
        validator: (value) => {
            if (!value.trim()) return "Release name cannot be empty!";
            const regex = /^[a-zA-Z0-9 _-]+$/;
            if (!regex.test(value.trim()))
                return "Release name can only contain letters, numbers, spaces, hyphens, and underscores!";
            return null;
        },
    });

    if (newName && newName.trim() !== "") {
        $("#releaseName").val(newName.trim());
        $("#heading").text(newName.trim());

        if (editReleaseId) {
            try {
                const response = await IndexLibrary.PutRequest({
                    endpoint: `/api/Release/UpdateName`,
                    body: {
                        releaseId: editReleaseId,
                        releaseName: newName.trim(),
                    }
                });

                if (response.ok) {
                    await IndexLibrary.ShowToast('success', "Release name updated successfully!");
                } else {
                    const errorText = await response.text();
                    await IndexLibrary.ShowToast('error', "Failed to rename release: " + errorText);
                }
            } catch (error) {
                console.error("Error updating release name:", error);
                await IndexLibrary.ShowToast('error', "Failed to update release name");
            }
        } else {
            await IndexLibrary.ShowToast('success', "Release name updated!");
        }
    }
}

async function DeleteRelease() {
    if (!isReleaseSelected()) {
        await IndexLibrary.ShowToast('error', "No release selected!");
        return;
    }
    const confirmed = await IndexLibrary.showConfirmDialog({
        text: "This action will permanently delete the release. Do you want to continue ?"
    });
    if (confirmed) {
        try {
            const response = await IndexLibrary.PutRequest({
                endpoint: `/api/Release/Delete/${editReleaseId}`,
                headers: { "UserEmail": IndexLibrary.GetUserEmail() }
            });
            if (response.ok) {
                await NavigateToReleaseList();
            } else {
                await IndexLibrary.ShowToast('error', "Failed to delete release");
            }
        } catch (error) {
            console.error("Error deleting release:", error);
            await IndexLibrary.ShowToast('error', "Failed to delete release");
        }
    }
}

async function NavigateToReleaseList() {
    try {
        var orgName = await IndexLibrary.GetAccountNameAsync();
        var projectName = await IndexLibrary.GetCurrentProjectName();
        const config = await IndexLibrary.GetExtensionConfig();

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

        IndexLibrary.NavigateToUrl(newUrl);
    } catch (error) {
        console.error("Error navigating to release list:", error);
        await IndexLibrary.ShowToast('error', "Failed to navigate to release list");
    }
}

async function GetWorkItemSuggestions() {
    var currentProjectName = await IndexLibrary.GetCurrentProjectName();
    var currentProject = optimalRolloutSettings.projectScope == 1 ? currentProjectName : "";

    try {
        const response = await IndexLibrary.GetRequest({
            endpoint: `/api/AzureDevops/GetFilteredWorkItemsRelease?filter=${$("#txtFilter").val()}&workItemtypes=${selectedWorkItemTypesFilter}&teamProject=${currentProject}&workItemStates=${selectedWorkItemStatesFilter}`
        });

        if (!response.ok) {
            throw new Error("Failed to load work item suggestions");
        }

        const items = await response.json();
        let suggestionsHtml = '';

        if (items == null) {
            suggestionsHtml = '<span><i>No matching work items found</i></span>'
        } else {
            suggestionsHtml = "<table style='width:100%'><thead><th></th><th>Id</th><th>Title</th><th>Type</th><th>Start Date</th><th>End Date</th><th>Project</th><th>State</th></thead><tbody>";
            for (var suggestedItemIndex = 0; suggestedItemIndex < items.length; suggestedItemIndex++) {
                var sDate = new Date(items[suggestedItemIndex].startDate);
                var eDate = new Date(items[suggestedItemIndex].endDate)
                var rowId = items[suggestedItemIndex].id + "_" + items[suggestedItemIndex].project;
                var startDateText = items[suggestedItemIndex].startDate == null ? "Unavailable" : sDate.toLocaleDateString("en-US");
                var endDateText = items[suggestedItemIndex].endDate == null ? "Unavailable" : eDate.toLocaleDateString("en-US");
                var typeIconUrl = allWorkItemTypes.find(x => x.name == items[suggestedItemIndex].type).iconUrl;

                suggestionsHtml = suggestionsHtml + "<tr><td class='suggestion'><input type='checkbox' onclick='AddOrRemoveWorkItem(this)' class='suggestion workItemCheckBox'" +
                    " data-workitem-id='" + escapeHtml(items[suggestedItemIndex].id) + "' " + (selectedWorkItems.includes(parseInt(items[suggestedItemIndex].id)) ? "checked" : "") +
                    " data-workitem-title='" + escapeHtml(items[suggestedItemIndex].title) + "'" +
                    " data-workitem-type='" + escapeHtml(items[suggestedItemIndex].type) + "'" +
                    " data-workitem-start-date='" + escapeHtml(startDateText) + "'" +
                    " data-workitem-end-date='" + escapeHtml(endDateText) + "'" +
                    " data-workitem-project='" + escapeHtml(items[suggestedItemIndex].project) + "'" +
                    " data-workitem-state='" + escapeHtml(items[suggestedItemIndex].state) + "'" +
                    " data-row-id='" + escapeHtml(rowId) + "'" +
                    " /></td>";
                suggestionsHtml = suggestionsHtml + "<td class='suggestion'>" + escapeHtml(items[suggestedItemIndex].id) + "</td>";
                suggestionsHtml = suggestionsHtml + "<td class='suggestion'>" + escapeHtml(items[suggestedItemIndex].title) + "</td>";
                suggestionsHtml = suggestionsHtml + "<td class='suggestion'><img class='suggestion' src='" + escapeHtml(sanitizeImageUrl(typeIconUrl)) + "' style='width: 14px;min-width: 14px;height: 14px;' /><span style='padding-left:5px'>" + escapeHtml(items[suggestedItemIndex].type) + "</span></td>";
                suggestionsHtml = suggestionsHtml + "<td class='suggestion'>" + escapeHtml(startDateText) + "</td>";
                suggestionsHtml = suggestionsHtml + "<td class='suggestion'>" + escapeHtml(endDateText) + "</td>";
                suggestionsHtml = suggestionsHtml + "<td class='suggestion'>" + escapeHtml(items[suggestedItemIndex].project) + "</td>";
                suggestionsHtml = suggestionsHtml + "<td class='suggestion'>" + escapeHtml(items[suggestedItemIndex].state) + "</td></tr>";
            }
            suggestionsHtml = suggestionsHtml + "</tbody></table>"
        }
        $("#taskSuggestions").html(suggestionsHtml);
        $("#taskSuggestions").show();
    } catch (error) {
        console.error("Error loading work item suggestions:", error);
        $("#taskSuggestions").html('<span><i>Error loading suggestions</i></span>');
        $("#taskSuggestions").show();
    }
}

$(document).ready(async function () {

    const urlParams = new URLSearchParams(window.location.search);
    editReleaseId = urlParams.get('rId');
    updateKebabDropdownState();

    await IndexLibrary.InitializeSDK();
    [organizationName, organizationId] = await Promise.all([
        IndexLibrary.GetAccountNameAsync(),
        IndexLibrary.GetAccountId()
    ]);

    try {
        const config = await IndexLibrary.GetExtensionConfig();
        publisherId = config.publisherId;
        extensionId = config.extensionId;
        userguidelink = config.userguidelink;
        userhelplink = config.userhelplink;

        // Check user license
        const userLicenseResponse = await IndexLibrary.GetRequest({
            endpoint: `/api/License/IsUserLicensed?organizationName=${organizationName}&email=${IndexLibrary.GetUserEmail()}&moduleUserType=devOpsAssist`
        });
        const userLicensed = (await userLicenseResponse.text()).toLowerCase() === 'true';

        if (!userLicensed) {
            $("#main").hide();
            $("#licenseExpired").hide();
            $("#unauthorized").show();
        } else {
            // Check org license
            const orgLicenseResponse = await IndexLibrary.GetRequest({
                endpoint: `/api/License/IsOrgLicenseValid?organizationName=${organizationName}`
            });
            const orgLicensed = (await orgLicenseResponse.text()).toLowerCase() === 'true';

            if (!orgLicensed) {
                $("#main").hide();
                $("#unauthorized").hide();
                $("#licenseExpired").show();
                $("#loadingSpinner").hide();
            } else {
                $("#main").show();
                $("#unauthorized").hide();
                $("#licenseExpired").hide();

                // Load settings and work item types in parallel
                const [settingsResponse, workItemTypesResponse] = await Promise.all([
                    IndexLibrary.GetRequest({ endpoint: `/api/Settings/Get` }),
                    IndexLibrary.GetRequest({ endpoint: `/api/AzureDevOps/GetAllWorkItemTypes` })
                ]);

                if (settingsResponse.ok && workItemTypesResponse.ok) {
                    const [settingsData, workItemTypesData] = await Promise.all([
                        settingsResponse.json(),
                        workItemTypesResponse.json()
                    ]);

                    optimalRolloutSettings = settingsData;
                    pageSize = optimalRolloutSettings.pageSizeForTables;

                    allWorkItemTypes = workItemTypesData;
                    var workItemTypeFilterHtml = "";
                    var workItemStateFilterHtml = "";
                    var alreadyPopulatedWorkItems = [];
                    allWorkItemTypes.forEach(element => {
                        workItemTypeFilterHtml = workItemTypeFilterHtml + "<div class='form-check'><input class='form-check-input chkWorkItemFilter' type='checkbox' id='chkWorkItemFilter' data-work-item-type='" + element.name + "'>";
                        workItemTypeFilterHtml = workItemTypeFilterHtml + "<img src='" + element.iconUrl + "' style=' width: 14px;min-width: 14px;height: 14px;' />"
                        workItemTypeFilterHtml = workItemTypeFilterHtml + "<label class='form-check-label' for='chkWorkItemFilter' style='font-size:14px; padding-left:5px'>";
                        workItemTypeFilterHtml = workItemTypeFilterHtml + element.name;
                        workItemTypeFilterHtml = workItemTypeFilterHtml + "</label></div>";
                        element.states.forEach(stateElement => {
                            if (!(alreadyPopulatedWorkItems.includes(stateElement.name))) {
                                workItemStateFilterHtml = workItemStateFilterHtml + "<div class='form-check'><input class='form-check-input chkWorkItemStateFilter' type='checkbox' id='chkWorkItemStateFilter' data-work-item-state='" + stateElement.name + "'>";
                                workItemStateFilterHtml = workItemStateFilterHtml + "<label class='form-check-label' for='chkWorkItemStateFilter' style='font-size:14px; padding-left:5px'>";
                                workItemStateFilterHtml = workItemStateFilterHtml + stateElement.name;
                                workItemStateFilterHtml = workItemStateFilterHtml + "</label></div>";
                                alreadyPopulatedWorkItems.push(stateElement.name);
                            }
                        })
                    });
                    $("#ddlWorkItemTypeFilter").html(workItemTypeFilterHtml);
                    $("#ddlWorkItemStatusFilter").html(workItemStateFilterHtml);
                    $("#taskSuggestions").hide();
                    if (editReleaseId !== null && editReleaseId !== undefined) {
                        editMode = true;
                        ShowEditMode();
                    } else {
                        $("#loadingSpinner").hide();
                    }
                }
            }
        }
    } catch (error) {
        console.error("Error initializing release page:", error);
        await IndexLibrary.ShowToast('error', "Failed to initialize release page");
        $("#loadingSpinner").hide();
    }


    $("#releaseStartDate").datepicker();
    $("#releaseEndDate").datepicker();
    $("#msg").hide();
    $("#unauthorized").hide();
    $("#licenseExpired").hide();
    $("#btnReleaseNotes").hide();
    $(".completionPercentage").css('visibility', 'hidden');

    $('#automaticMonitoringCheck').on('click', function () {
        const isAutomatic = $(this).is(":checked");
        applyMonitoringMode(isAutomatic);

        if (isAutomatic) {
            $("#ddlReleaseHealth").val("5");
        } else {
            $("#completionPercentageValue").val("");
        }
    });

    $('#manualMonitoringCheck').on('click', function () {
        const isAutomatic = !$(this).is(":checked");
        applyMonitoringMode(isAutomatic);

        if (!isAutomatic) {
            $("#completionPercentageValue").val("");
        }
    });

    $(document).on('click', function (e) {
        if (!e.target.classList.contains('suggestion') && e.target.id !== 'txtFilter') {
            $("#taskSuggestions").hide();
        }
    });

});

// Add event listeners for rename and delete buttons
$(document).on('click', '.rename-project', function (event) {
    if ($(this).is(':disabled') || $(this).prop('disabled')) {
        event.preventDefault();
        event.stopPropagation();
        return false;
    }
    event.preventDefault();
    event.stopPropagation();
    OpenRenameReleaseModal();
    $(this).closest('.dropdown').removeClass('show');
    $(this).closest('.dropdown-menu').removeClass('show');
    return false;
});

$(document).on('click', '.delete-project', async function (event) {
    if ($(this).is(':disabled') || $(this).prop('disabled')) {
        event.preventDefault();
        event.stopPropagation();
        return false;
    }
    event.preventDefault();
    event.stopPropagation();
    $(this).closest('.dropdown').removeClass('show');
    $(this).closest('.dropdown-menu').removeClass('show');
    await DeleteRelease();
    return false;
});

async function GenerateReleaseNotes() {
    window.location.href = 'release-notes.html?rId=' + editReleaseId + '&rName=' + $("#releaseName").val();
}


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

if (typeof window !== 'undefined') {
    window.OpenRenameReleaseModal = OpenRenameReleaseModal;
    window.DeleteRelease = DeleteRelease;
}

async function applyNewReleaseUserPermission() {

    const section = document.getElementById("releaseFormSection");

    const buttonSection = document.getElementById("releasebuttonsection");
    if (!section || !buttonSection) return;

    try {
        const licensedUserType = await IndexLibrary.GetUserLicensesType(moduleName);


        const formElements = section.querySelectorAll("input, select, textarea, button");

        const buttonElements = buttonSection.querySelectorAll("button");

        if (licensedUserType === "0") {

            formElements.forEach(el => {
                el.disabled = true;
                el.classList.add("disabled");
            });


            buttonElements.forEach(el => {
                el.disabled = true;
                el.classList.add("disabled");

                if (el.id === "btnDeleteRelease") {
                    el.title = "Only Manager can delete release";
                } else if (el.id === "btnCreateRelease") {
                    el.title = "Only Manager can save release";
                } else if (el.id === "btnCreateNewRelease") {
                    el.title = "Only Manager can create new release";
                } else {
                    el.title = "";
                }
            });
        } else {

            formElements.forEach(el => {
                el.disabled = false;
                el.classList.remove("disabled");
            });


            buttonElements.forEach(el => {
                el.disabled = false;
                el.classList.remove("disabled");
                el.title = "";
            });
        }

    } catch (err) {
        console.error("Failed to apply release form permission:", err);


    }
}

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

function openUserGuideLink() {
    IndexLibrary.openInNewTab(userguidelink);
}

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