function isValidJSON(value) {
    try {
        JSON.parse(value);
        return true;
    } catch (e) {
        return false;
    }
}

document.addEventListener("DOMContentLoaded", function () {
    // Attach JSON validation to all textareas with data-validate-json
    document.querySelectorAll("[data-validate-json]").forEach(textarea => {
        textarea.addEventListener("input", function () {
            const value = this.value.trim();
            const feedback = this.nextElementSibling; // Assuming <small> is right after <textarea>

            if (value === "" || isValidJSON(value)) {
                feedback.textContent = __('json_valid');
                feedback.style.color = "green";
                this.classList.remove("is-invalid");
                this.classList.add("is-valid");
            } else {
                feedback.textContent = __('json_invalid');
                feedback.style.color = "red";
                this.classList.remove("is-valid");
                this.classList.add("is-invalid");
            }
        });
    });
});