var selectedWorkItems = [];
var currentPageItems;
var currentEvolveAssistPage = 1;
var allWorkItemTypes = [];
var expandedEvolveAssistWorkItems = [];
var expandedEvolveAssistWorkItemsCurrentPageNumbers = [];
var userguidelink = "";
var userhelplink = "";
var pageSize = 5;
var publisherId = "";
var extensionId = "";
var totalPages = 1;
let currentSortColumn = "ModifiedDate";
let currentSortOrder = "desc"; // "asc" | "desc"

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

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

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

function showMainLoadingSpinner() {
    $("#loadingSpinner").css("display", "flex");
}

function hideMainLoadingSpinner() {
    $("#loadingSpinner").hide();
}

async function LoadPageFromServer() {

    showMainLoadingSpinner();
    const searchTerm = $("#txtEvolveAssistNameFilter").val()?.trim() || "";
    const orgId = IndexLibrary.GetAccountId();

    const params = new URLSearchParams();
    if (searchTerm) {
        params.append("searchTerm", searchTerm);
    }

    if (currentSortColumn) {
        params.append("FilterName", currentSortColumn);
        params.append("SortingOrder", currentSortOrder);
    }
    var currentProjectId = await IndexLibrary.GetCurrentProjectId();
    params.append("DevopsProjectId", currentProjectId);

    const queryString = [...params].length > 0 ? `?${params.toString()}` : '';
    const res = await IndexLibrary.GetRequest({
        endpoint: `/api/EvolveAssist/GetPagedProjects/${orgId}/${currentEvolveAssistPage}${queryString}`,
        headers: {
            userEmail: IndexLibrary.GetUserEmail()
        }
    });

    const data = await res.json();

    currentPageItems = data.items;
    totalCount = data.totalCount;
    totalPages = data.totalPages;
    pageSize = data.pageSize;

    $("#EvolveAssistListTable").remove();
    PopulateEvolveAssistListTable();

    hideMainLoadingSpinner();
    $("#EvolveAssistListBody").show();

}

async function PopulateEvolveAssistListTable() {
    var html = "";
    showMainLoadingSpinner();
    html += `
<div class='evolve-table-scroll'>
<table id='EvolveAssistListTable' style='width:100%'>
    <thead>
    <tr>
        <th class="icon-column"></th>
        <th data-sort="ProjectName" class="chat-header">
            Evolve Chat <span class="sort-icon"><i class="bi bi-caret-down-fill"></i></span>
        </th>
        <th class="workitem-header">
            WorkItem
        </th>
            <th data-sort="CreatedDate">
                Created Date <span class="sort-icon"><i class="bi bi-caret-down-fill"></i></span>
            </th>
            <th data-sort="ModifiedDate">
                Last Update <span class="sort-icon"><i class="bi bi-caret-down-fill"></i></span>
            </th>
            <th data-sort="WorkItemCount">
                AI Assisted Items <span class="sort-icon"><i class="bi bi-caret-down-fill"></i></span>
            </th>
        </tr>
    </thead>
    <tbody>`;

    var paginatedEvolveAssists = currentPageItems;

    for (let i = 0; i < paginatedEvolveAssists.length; i++) {
        const element = paginatedEvolveAssists[i];

        var sDate = new Date(element.createdDate);
        var eDate =
            element.modifiedDate == null
                ? new Date(element.createdDate)
                : new Date(element.modifiedDate);
        const linkedItem = parseLinkedItem(element.linkedItem);

        let linkedItemHtml = "";

        if (linkedItem) {
            const cleanId = linkedItem.id?.toString().replace(/^#/, "");
            const shortTitle = truncateChars(linkedItem.title, 45);

            linkedItemHtml = `
        <a href="#"
           class="workitem-link"
           title="${linkedItem.title}"
           onclick="NavigateToWorkItem('${cleanId}')">
            ${cleanId} - ${shortTitle}
        </a>`;
        }



        html = html +
            "<tr><td></td>" +
            "<td><div class=\"row-action\"><a id='project-link-" + element.projectId + "' href='#' title='" + element.projectName.replace(/'/g, "&#39;") + "' onclick='NavigateToEvolveAssistDetails(\"" + element.projectId + "\")'>" + truncateChars(element.projectName, 40) + "</a>" +
            '<span class="float-end hidden-menu">' +
            '<div class="dropdown">' +
            '<button class="btn btn-secondary dropdown-toggle caret-off ea-row-menu-btn" type="button" data-bs-toggle="dropdown" aria-expanded="false"><i class="bi bi-three-dots"></i></button>' +
            '<div class="dropdown-menu" style="padding-left:8px; border-radius:0" aria-labelledby="dropdownWorkItemTypeFilter">' +
            // Rename / edit block
            '<span class="rename-project" style="cursor: pointer; display: flex; align-items: center; font-size:12px;" ' +
            'data-eaid="' + element.projectId + '">' +
            '<i class="bi bi-pencil"></i>' + // changed icon to pencil/edit
            '<span class="dropdown-item" style="cursor:pointer">Rename Chat</span>' +
            "</span>" +
            // Delete block
            '<span class="delete-project" style="cursor: pointer; display: flex; align-items: center; font-size:12px; margin-top:2px;" ' +
            'data-eaid="' + element.projectId + '" data-eaname="' + element.projectName.replace(/'/g, "\\'") + '">' +
            '<i class="bi bi-trash"></i>' +
            '<span class="dropdown-item" style="cursor:pointer">Delete Chat</span>' +
            "</span>" +
            "</div>" +
            "</div>" +
            "</span></div></td>" +
            "<td>" + linkedItemHtml + "</td>" +
            "<td>" +
            sDate.toLocaleDateString("en-US") +
            "</td>" +
            "<td>" +
            eDate.toLocaleDateString("en-US") +
            "</td>" +
            "<td>" +
            (element.workItemCount ?? 0) +
            "</td>";

        html = html + "</tr>";
    };

    html = html + "</tbody></table></div>";
    $(".grid-container").html(html);

    $(document).on('click', '.rename-project', function () {
        const projectId = $(this).data('eaid');
        const projectName = $("#project-link-" + projectId).attr("title");
        RenameEvolveAssistProject(projectId, projectName);
    });

    $(document).on('click', '.delete-project', async function (event) {
        event.stopPropagation(); // ✅ prevents dropdown from closing before the event fires
        const projectId = $(this).data('eaid');
        const projectName = $(this).data('eaname');

        const confirmResult = await Swal.fire({
            title: "Delete Chat",
            text: `Are you sure you want to delete "${projectName}"? This action cannot be undone.`,
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Delete",
            cancelButtonText: "Cancel",
            confirmButtonColor: "#d33",
        });

        if (confirmResult.isConfirmed) {
            await DeleteEvolveAssistProject(projectId);
        }
    });

    function renderUserCell(userName, avatarLink, email, tooltipText) {
        const tdClass = avatarLink ? "" : "user";

        let html = "<td class='" + tdClass + "' title='" + (tooltipText || "") + "'>";

        if (avatarLink) {
            html += "<img src='" + avatarLink + "' class='avatar-img' alt='Avatar' /> ";
        } else {
            html += "<span class='avatar'>" + IndexLibrary.getInitials(email) + "</span> ";
        }

        html += (userName ?? "") + "</td>";
        return html;
    }

    function parseLinkedItem(linkedItem) {
        if (!linkedItem) return null;
        try {
            return JSON.parse(linkedItem);
        } catch {
            return null;
        }
    }

    function truncateChars(text, maxChars) {
        if (!text) return "";
        return text.length > maxChars ? text.slice(0, maxChars).trim() + "..." : text;
    }

    async function DeleteEvolveAssistProject(projectId) {
        const deletedBy = IndexLibrary.GetUserEmail();
        const organizationId = IndexLibrary.GetAccountId();

        try {
            const response = await IndexLibrary.DeleteRequest({
                endpoint: `/api/EvolveAssist/DeleteEvolveAssistProject`,
                body: JSON.stringify({
                    projectId: projectId,
                    organizationId: organizationId,
                    deletedBy: deletedBy,
                }),
            });

            if (response.ok) {
                // Remove row from the table smoothly
                const row = $(`.delete-project[data-eaid='${projectId}']`).closest("tr");
                row.fadeOut(300, function () {
                    $(this).remove();
                });

                await Swal.fire("Deleted!", "Project has been deleted successfully.", "success");
            } else {
                const errorText = await response.text();
                Swal.fire("Error", "Failed to delete project: " + errorText, "error");
            }
        } catch (error) {
            Swal.fire("Error", "An error occurred: " + error.message, "error");
        }
    }

    async function RenameEvolveAssistProject(editEvolveId, projectName) {
        if (!editEvolveId || !projectName) {
            Swal.fire("Error", "No project selected!", "error");
            return;
        }

        const modifiedBy = IndexLibrary.GetUserEmail();
        const organizationId = IndexLibrary.GetAccountId();

        const { value: newName } = await Swal.fire({
            title: "Rename Chat",
            input: "text",
            inputValue: projectName,
            showCancelButton: true,
            confirmButtonText: "Save",
            cancelButtonText: "Cancel",
            inputValidator: (value) => {
                if (!value.trim()) return "Evolve Chat name cannot be empty!";
                const regex = /^[a-zA-Z0-9 _-]+$/;
                if (!regex.test(value.trim()))
                    return "Evolve Chat name can only contain letters, numbers, spaces, hyphens, and underscores!";
                return null;
            },
        });

        if (newName && newName.trim() !== "") {
            try {
                const response = await IndexLibrary.PutRequest({
                    endpoint: `/api/EvolveAssist/UpdateName`,
                    body: JSON.stringify({
                        id: editEvolveId,
                        organizationId: organizationId,
                        projectName: newName.trim(),
                        modifiedBy: modifiedBy,
                    }),
                });

                if (response.ok) {
                    // ✅ Update in table
                    const link = document.getElementById("project-link-" + editEvolveId);
                    if (link) link.textContent = newName.trim();
                    await Swal.fire("Success", "Evolve Chat name updated successfully!", "success");
                } else {
                    const errorText = await response.text();
                    Swal.fire("Error", "Failed to rename Evolve Chat: " + errorText, "error");
                }
            } catch (error) {
                Swal.fire("Error", "An error occurred: " + error.message, "error");
            }
        }
    }

    // Create pagination container if it doesn't exist
    if ($("#EvolveAssistGridPaging").length === 0) {
        $(".grid-container").after(
            '<div id="EvolveAssistGridPaging" style="text-align: center; margin-top: 10px;"></div>'
        );
    }
    var pagingHtml = "";
    pagingHtml += `<button onclick="GotoEvolveAssistPage(${currentEvolveAssistPage - 1})"
               ${currentEvolveAssistPage <= 1 ? "disabled" : ""}
               class="pagination-button"><i class="bi bi-chevron-left"></i></button>`;

    // PAGE NUMBERS
    for (var i = 1; i <= totalPages; i++) {
        pagingHtml += `<button onclick="GotoEvolveAssistPage(${i})" class="pagination-button ${i === currentEvolveAssistPage ? "active" : ""}">
                     ${i}
                   </button>`;
    }
    // FORWARD BUTTON
    pagingHtml += `<button onclick="GotoEvolveAssistPage(${currentEvolveAssistPage + 1})"
               ${currentEvolveAssistPage >= totalPages ? "disabled" : ""}
             class="pagination-button"><i class="bi bi-chevron-right"></i></button>`;
    $("#EvolveAssistGridPaging").html(pagingHtml);

    updateSortArrows();

    hideMainLoadingSpinner();
    $("#EvolveAssistListTable").resizableColumns();

}

function GotoEvolveAssistPage(pageIndex) {
    currentEvolveAssistPage = parseInt(pageIndex);
    LoadPageFromServer();
}

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

function updateSortArrows() {
    $(".sort-icon").remove();

    if (!currentSortColumn) return;

    const iconClass =
        currentSortOrder === "asc"
            ? "bi-caret-up-fill"
            : "bi-caret-down-fill";

    const $activeHeader = $(
        `#EvolveAssistListTable th[data-sort='${currentSortColumn}']`
    );

    $activeHeader.append(`
        <span class="sort-icon">
            <i class="bi ${iconClass}"></i>
        </span>
    `);
}

async function NavigateToCreateEvolveAssist() {
    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-evolve-assist";

    await IndexLibrary.NavigateToUrl(newUrl);
}
async function NavigateToEvolveAssistDetails(EvolveAssistId) {
    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-evolve-assist?eId=" + EvolveAssistId;

    await IndexLibrary.NavigateToUrl(newUrl);
}

async function GetWorkItemRowHtml(
    workitemId,
    workitemTitle,
    workitemType,
    workitemProject,
    workitemState,
    EvolveAssistId,
    startDate,
    endDate
) {
    var rowId = workitemId + "_" + workitemProject;
    var deleteButtonId = "delete_" + rowId;
    var workItemHealthStatusText = GetHealthStatusText(
        workItemHealthObj.workItemTrackingHealth
    );
    var workItemHealthStatusColor = GetHealthStatusColor(
        workItemHealthStatusText
    );
    var sDate = new Date(startDate);
    var eDate = new Date(endDate);
    var projectName = await IndexLibrary.GetCurrentProjectName();
    var workItemUrl =
        "https://dev.azure.com/" +
        await IndexLibrary.GetAccountNameAsync() +
        "/" +
        projectName +
        "/_workitems/edit/" +
        workitemId +
        "/";
    return (
        "<tr id='" +
        rowId +
        "' class='workItemRow' data-delete-button-id='" +
        deleteButtonId +
        "'><td style='vertical-align:top'>" +
        workitemId +
        "</td>" +
        "<td style='padding-bottom: 10px; width:42%'><a href='" +
        workItemUrl +
        "' target='_blank'>" +
        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>" +
        (startDate == null ? "Unavailable" : sDate.toLocaleDateString("en-US")) +
        "</td>" +
        "<td>" +
        (endDate == null ? "Unavailable" : eDate.toLocaleDateString("en-US")) +
        "</td>" +
        "<td>" +
        workitemProject +
        "</td>" +
        "<td>" +
        workitemState +
        "</td>" +
        "<td style='background-color: " +
        workItemHealthStatusColor +
        "'>" +
        workItemHealthStatusText +
        "</td></tr>"
    );
}
function OpenWorkItemDialog(workItemId) {
    IndexLibrary.Navigate(workItemId);
}

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

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

    var EvolveAssistRow = document.getElementById(
        "selectedWorkItemsTableRow_" + EvolveAssistId
    ).previousElementSibling;
    $("#selectedWorkItemsTableRow_" + EvolveAssistId).remove();
    CreateShellWorkItemsTable(EvolveAssistRow, EvolveAssistId);
    PopulateEvolveAssistWorkItems(EvolveAssistId);
}

function NextWorkItemPage(EvolveAssistId) {
    var expandedRowIndex =
        expandedEvolveAssistWorkItemsCurrentPageNumbers.findIndex(
            (x) => x.EvolveAssistId == EvolveAssistId
        );
    var currentPage =
        expandedEvolveAssistWorkItemsCurrentPageNumbers[expandedRowIndex]
            .pageNumber;
    var EvolveAssistWorkItemsIndex = expandedEvolveAssistWorkItems.findIndex(
        (e) => e.EvolveAssistId === EvolveAssistId
    );

    if (
        currentPage * pageSize <
        expandedEvolveAssistWorkItems[EvolveAssistWorkItemsIndex].workItems.length
    )
        expandedEvolveAssistWorkItemsCurrentPageNumbers[expandedRowIndex]
            .pageNumber++;

    var EvolveAssistRow = document.getElementById(
        "selectedWorkItemsTableRow_" + EvolveAssistId
    ).previousElementSibling;
    $("#selectedWorkItemsTableRow_" + EvolveAssistId).remove();
    CreateShellWorkItemsTable(EvolveAssistRow, EvolveAssistId);
    PopulateEvolveAssistWorkItems(EvolveAssistId);
}

function GotoWorkItemPage(pageNumber, EvolveAssistId) {
    var expandedRowIndex =
        expandedEvolveAssistWorkItemsCurrentPageNumbers.findIndex(
            (x) => x.EvolveAssistId == EvolveAssistId
        );
    var EvolveAssistRow = document.getElementById(
        "selectedWorkItemsTableRow_" + EvolveAssistId
    ).previousElementSibling;
    expandedEvolveAssistWorkItemsCurrentPageNumbers[expandedRowIndex].pageNumber =
        pageNumber;
    $("#selectedWorkItemsTableRow_" + EvolveAssistId).remove();
    CreateShellWorkItemsTable(EvolveAssistRow, EvolveAssistId);
    PopulateEvolveAssistWorkItems(EvolveAssistId);
}

async function PopulateEvolveAssistWorkItems(EvolveAssistId) {
    var EvolveAssistWorkItemsIndex = expandedEvolveAssistWorkItems.findIndex(
        (e) => e.EvolveAssistId === EvolveAssistId
    );
    EvolveAssistWorkItems =
        expandedEvolveAssistWorkItems[EvolveAssistWorkItemsIndex].workItems;
    var totalWorkItems =
        expandedEvolveAssistWorkItems[EvolveAssistWorkItemsIndex].workItems.length;
    var numberOfPages = Math.ceil(totalWorkItems / pageSize);
    if (numberOfPages > 1) {
        var paginationHtml = "";
        for (var pageNumber = 1; pageNumber <= numberOfPages; pageNumber++) {
            paginationHtml =
                paginationHtml +
                "<button onclick=\"GotoWorkItemPage('" +
                pageNumber +
                "','" +
                EvolveAssistId +
                "')\" id='page_" +
                EvolveAssistId +
                "_" +
                pageNumber +
                "'>" +
                pageNumber +
                "</button>";
        }
        $("#pagination_" + EvolveAssistId).html(paginationHtml);
    } else {
        $("#paginationFooter_" + EvolveAssistId).hide();
    }
    EvolveAssistWorkItems.filter((row, index) => {
        var expandedRowIndex =
            expandedEvolveAssistWorkItemsCurrentPageNumbers.findIndex(
                (x) => x.EvolveAssistId == EvolveAssistId
            );
        var currentPage =
            expandedEvolveAssistWorkItemsCurrentPageNumbers[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,
            EvolveAssistId,
            c.startDate,
            c.endDate
        );
        selectedWorkItems.push(parseInt(c.id));
        $("#selectedWorkItemsTable_" + EvolveAssistId + " tr:last").after(rowHtml);
    });

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

function CreateShellWorkItemsTable(row, EvolveAssistId) {
    var html = "";
    var tableId = "selectedWorkItemsTable_" + EvolveAssistId;
    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_" +
        EvolveAssistId +
        "' 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_" +
        EvolveAssistId +
        "' style='float: right; padding-top:10px;padding-bottom:10px'><button onclick=\"PreviousWorkItemPage('" +
        EvolveAssistId +
        '\')" id="prevButton_' +
        EvolveAssistId +
        "\"><</button><span id='pagination_" +
        EvolveAssistId +
        "'></span><button onclick=\"NextWorkItemPage('" +
        EvolveAssistId +
        '\')" id="nextButton_' +
        EvolveAssistId +
        '">></button></span>';
    $(row)
        .closest("tr")
        .after(
            '<tr id="selectedWorkItemsTableRow_' +
            EvolveAssistId +
            '"><td><td colspan="6">' +
            html +
            "</td></tr>"
        );
    document.querySelectorAll("#" + tableId + " thead tr th").forEach((t) => {
        t.addEventListener("click", sort, false);
    });
}


async function navigateToCreateProject() {
    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-evolve-assist";

    await IndexLibrary.NavigateToUrl(newUrl);
}

async function CreateEvolveAssistProject(
    projectName,
    organizationId,
    organizationName
) {
    try {
        // Prepare the request payload based on the CreateEvolveAssistProjectRequest model
        const requestPayload = {
            ProjectName: projectName,
            OrganizationId: organizationId || IndexLibrary.GetAccountId(),
            OrganizationName: organizationName || await IndexLibrary.GetAccountNameAsync(),
        };

        const response = await IndexLibrary.PostRequest({
            endpoint: `/api/EvolveAssist/Create`,
            body: requestPayload,
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const result = await response.json();
        return result;
    } catch (error) {
        console.error("Error creating project:", error);
        throw error;
    }
}

$(document).on(
    "click",
    "#EvolveAssistListTable thead th[data-sort]",
    function () {
        const clickedColumn = $(this).data("sort");

        if (currentSortColumn === clickedColumn) {
            currentSortOrder = currentSortOrder === "asc" ? "desc" : "asc";
        } else {
            currentSortColumn = clickedColumn;
            currentSortOrder = "desc";
        }
        updateSortArrows();

        currentEvolveAssistPage = 1;
        LoadPageFromServer();
    }
);



$(document).ready(async function () {
    $("#missingFieldMappingsMsg").hide();
    $("#evolveAssistTrialPill").hide();

    const orgName = await IndexLibrary.GetAccountNameAsync();

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

        const licenseResponse = await IndexLibrary.PostRequest({
            endpoint: `/api/License/GetLicense`,
            body: { organizationName: orgName }
        });

        if (licenseResponse.status == 404) {
            $("#startTrialMessage").show();
            $("#evolveAssistTrialPill").hide();
            setNewChatButtonState(false);
            CreateTrialLicense();
            return;
        }

        const licenseData = await licenseResponse.json();
        if (licenseData.status !== undefined && licenseData.status == 404) {
            $("#startTrialMessage").show();
            $("#evolveAssistTrialPill").hide();
            setNewChatButtonState(false);
            CreateTrialLicense();
            return;
        }

        const userLicenseResponse = await IndexLibrary.GetRequest({
            endpoint: `/api/License/IsUserLicensed?organizationName=${orgName}&email=${IndexLibrary.GetUserEmail()}&moduleUserType=devOpsAssist`
        });
        const isUserLicensed = await userLicenseResponse.text();

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

        const settingsResponse = await IndexLibrary.GetRequest({
            endpoint: `/api/Settings/Get`
        });
        const settingsData = await settingsResponse.json();
        pageSize = settingsData.pageSizeForTables;
        currentEvolveAssistPage = 1;
        await LoadPageFromServer();
    } catch (error) {
        $("#startTrialMessage").show();
        $("#evolveAssistTrialPill").hide();
        setNewChatButtonState(false);
    }

    let searchDebounceTimer = null;

    $("#txtEvolveAssistNameFilter").on("keyup", function () {
        clearTimeout(searchDebounceTimer);

        searchDebounceTimer = setTimeout(() => {
            currentEvolveAssistPage = 1; // reset paging
            LoadPageFromServer();       // fetch fresh data from API
        }, 300); // debounce to reduce API calls
    });

});

async function NavigateToWorkItem(itemId) {
    if (!itemId) return;
    const workItemId = itemId.toString().replace(/^#/, "");
    const org = await IndexLibrary.GetAccountNameAsync();
    const project = await IndexLibrary.GetCurrentProjectName();

    const url = `https://dev.azure.com/${org}/${project}/_workitems/edit/${workItemId}`;
    window.open(url, "_blank");
}
function openUserGuideLink() {
    IndexLibrary.openInNewTab(userguidelink);
}

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