// Wait for IndexLibrary to be available
function waitForIndexLibrary() {
    if (typeof IndexLibrary !== 'undefined' && IndexLibrary.InitializeSDK) {
        IndexLibrary.InitializeSDK().then(() => {
            console.log('Summarize form initialized');
        });
    } else {
        setTimeout(waitForIndexLibrary, 50);
    }
}

waitForIndexLibrary();

async function handleSummarizeClick() {
    try {
        // Ensure IndexLibrary is loaded
        if (typeof IndexLibrary === 'undefined') {
            IndexLibrary.ShowToast('error', 'Extension library is not loaded. Please refresh the page.');
            return;
        }

        console.log("Summarize button clicked");

        // Get work item ID using IndexLibrary
        const workItemId = await IndexLibrary.CurrentWorkItem();

        if (!workItemId || workItemId === "0") {
            IndexLibrary.ShowToast('error', "Please open a work item first");
            return;
        }

        console.log("Work item ID:", workItemId);

        // Trigger the summarize action
        await IndexLibrary.TriggerSummarizeAction(parseInt(workItemId));

    } catch (error) {
        console.error("Error:", error);
        IndexLibrary.ShowToast('error', 'Failed to generate summary: ' + error.message);
    }
}
