document.addEventListener("DOMContentLoaded", function () {
    const consentInformationFieldName = "consentInformation"; // Input field name
    const scopeDescriptionSource = "scope_name"; // JSON key for scope description

    function displayOAuthScopesConsent() {
        const jsonData = parseJson();
        if (jsonData !== undefined) {
            mapJsonToHtml(jsonData);
        }
    }

    function mapJsonToHtml(jsonData) {
        mapJsonToHtmlScopeList("listOfRequestedScopesWithExistingConsent", jsonData.requestedScopesWithExistingConsent, "Already accepted scopes:");
        mapJsonToHtmlScopeList("listOfRequestedScopes", jsonData.requestedScopesRequiringConsent, "Requested scopes that require consent:");
    }

    function mapJsonToHtmlScopeList(elementId, scopeInformation, title) {
        if (scopeInformation && Object.keys(scopeInformation).length > 0) {
            const consentInput = document.querySelector(`input[name="${consentInformationFieldName}"]`);
            if (consentInput) {
                const container = document.createElement("div");
                container.innerHTML = `<p style='margin-top: 0.5em'>${title}</p><div class='scopeinfobox'><ul id='${elementId}'></ul></div>`;
                consentInput.insertAdjacentElement("afterend", container);

                const ulElement = document.getElementById(elementId);
                for (const key in scopeInformation) {
                    if (scopeInformation.hasOwnProperty(key)) {
                        const scopeDescription = scopeInformation[key][scopeDescriptionSource] || key;
                        const li = document.createElement("li");
                        li.textContent = scopeDescription;
                        ulElement.appendChild(li);
                    }
                }
            }
        }
    }

    function parseJson() {
        const consentInformationField = document.querySelector(`input[name="${consentInformationFieldName}"]`);
        if (consentInformationField) {
            try {
                return JSON.parse(consentInformationField.value);
            } catch (e) {
                console.error("Invalid JSON in consent information field:", e);
            }
        }
    }

    displayOAuthScopesConsent();
});
