(function () {
    let workItemId = null;

    // DOM refs
    let loadingEl;
    let contentEl;
    let emptyEl;
    let lastUpdatedEl;
    let regenerateBtn;

    /* -------------------------------------------------------------
       Init entry point (runs automatically)
    ------------------------------------------------------------- */
    async function init() {
        try {
            cacheDom();
            const ctx = await getContext();
            workItemId = ctx.workItemId;
            if (!workItemId) {
                throw new Error("No work item open");
            }
            await loadSummary(ctx);
            bindEvents();
        } catch (err) {
            showError(err.message || "Failed to initialize summary");
        }
    }


    /* -------------------------------------------------------------
       DOM
    ------------------------------------------------------------- */
    function cacheDom() {
        loadingEl = document.getElementById("qa-summary-loading");
        contentEl = document.getElementById("qa-summary-content");
        emptyEl = document.getElementById("qa-summary-empty");
        lastUpdatedEl = document.getElementById("qa-summary-last-updated");
        regenerateBtn = document.getElementById("qa-summary-regenerate");
    }

    function bindEvents() {
        regenerateBtn.addEventListener("click", regenerateSummary);
    }

    async function getContext() {
        if (!window.ensureSDKReady) {
            throw new Error("SDK not initialized. ensureSDKReady missing.");
        }

        await window.ensureSDKReady();
        return window.QAContext;
    }

    async function loadSummary(ctx) {
        showLoading();

        try {
            const res = await IndexLibrary.GetRequest({
                baseAPIUrl: ctx.baseAPIUrl,
                endpoint: `/api/WorkItemSummary/Get/${workItemId}`,
                azureAuthenticationHeader: ctx.accessToken,
                organizationName: ctx.organizationName,
                organizationId: ctx.organizationId
            });

            if (res.ok) {
                const data = await res.json();
                renderSummary(data.summary, data.lastUpdated);
                return;
            }

            // Not found → auto-generate
            await generateSummary(ctx);

        } catch (err) {
            showError(err.message || "Failed to load summary");
        }

    }

    async function generateSummary(ctx) {
        showLoading();

        try {
            // Get summarize config
            const cfgRes = await IndexLibrary.GetRequest({
                baseAPIUrl: ctx.baseAPIUrl,
                endpoint: `/api/Settings/GetSummarizeConfigurations`,
                azureAuthenticationHeader: ctx.accessToken,
                organizationName: ctx.organizationName,
                organizationId: ctx.organizationId
            });

            if (!cfgRes.ok) {
                throw new Error("Failed to fetch summarize configuration");
            }

            const cfg = await cfgRes.json();
            const fields =
                cfg.summarizeFields
                    ?.split(",")
                    .map(f => f.trim()) ||
                ["System.Id", "System.Title", "System.Description", "System.State"];

            // Get work item fields
            const wi = await IndexLibrary.GetWorkItemWithFields(
                workItemId,
                fields
            );

            const workItemFields = {};
            fields.forEach(f => {
                workItemFields[f] = wi.fields[f];
            });

            // Generate
            const genRes = await IndexLibrary.PostRequest({
                baseAPIUrl: ctx.baseAPIUrl,
                endpoint: `/api/WorkItemSummary/Generate`,
                azureAuthenticationHeader: ctx.accessToken,
                organizationName: ctx.organizationName,
                organizationId: ctx.organizationId,
                body: {
                    organizationId: ctx.organizationId,
                    devOpsProjectId: ctx.projectId,
                    devOpsProjectName: ctx.projectName,
                    workItemId,
                    workItemFields,
                    createdBy: ctx.userEmail
                }
            });

            if (!genRes.ok) {
                const t = await genRes.text();
                throw new Error(t || "Failed to generate summary");
            }

            const data = await genRes.json();
            renderSummary(data.summary, data.lastUpdated);

        } catch (err) {
            showError(err.message || "Failed to generate summary");
        }
    }

    async function regenerateSummary() {
        const ctx = await getContext();

        await generateSummary(ctx);
    }

    /* -------------------------------------------------------------
       Rendering helpers
    ------------------------------------------------------------- */

    function setRegenerateEnabled(enabled) {
        regenerateBtn.disabled = !enabled;
        regenerateBtn.style.opacity = enabled ? "1" : "0.6";
    }

    function showLoading() {
        loadingEl.classList.remove("hidden");
        contentEl.innerHTML = "";
        emptyEl.classList.add("hidden");
        setRegenerateEnabled(false);
    }

    function renderSummary(summary, lastUpdated) {
        loadingEl.classList.add("hidden");
        emptyEl.classList.add("hidden");
        setRegenerateEnabled(true);
        lastUpdatedEl.textContent =
            IndexLibrary.convertUtcToLocal(lastUpdated);

        if (typeof DOMPurify === "undefined") {
            contentEl.textContent = summary || "";
            return;
        }
        const summaryHtml = marked.parse(summary || "");
        contentEl.innerHTML = DOMPurify.sanitize(summaryHtml, { USE_PROFILES: { html: true } });
    }


    // -------------------------------------------------------------
    // Boot
    // -------------------------------------------------------------
    function dispose() { }

    ScreenManager.register("summary", {
        init,
        dispose
    });

})();
