jQuery(document).ready(function($){
    function resizeInlineTextarea(textarea) {
        if (!textarea) {
            return;
        }

        const computedStyle = window.getComputedStyle(textarea);
        const minHeight = parseFloat(computedStyle.minHeight || "0") || 0;

        textarea.style.height = "auto";
        textarea.style.height = Math.max(textarea.scrollHeight, minHeight) + "px";
    }

    function resizeVisibleInlineTextareas(scope) {
        $(scope || document).find(".griffinforms-app-textarea_update_field").each(function () {
            if (!$(this).is(":visible")) {
                this.style.height = "";
                return;
            }

            resizeInlineTextarea(this);
        });
    }

    // Auto-resize textareas to fit their content
    document.addEventListener("form-html-received", () => {
        requestAnimationFrame(() => {
            resizeVisibleInlineTextareas(document);
        });
    });

    document.addEventListener("item-selected", () => {
        requestAnimationFrame(() => {
            resizeVisibleInlineTextareas(document);
        });
    });

    $(document).on("focus input", ".griffinforms-app-textarea_update_field", function() {
        resizeInlineTextarea(this);
    });

    // Prevent Enter key from inserting line breaks in contenteditable heading spans
    $(document).on("keydown", ".griffinforms-app-heading-ce", function(e) {
        if (e.key === "Enter") {
            e.preventDefault();
            this.blur();
        }
    });

    // Strip formatting on paste — plain text only
    $(document).on("paste", ".griffinforms-app-heading-ce", function(e) {
        e.preventDefault();
        var text = (e.originalEvent.clipboardData || window.clipboardData).getData("text/plain");
        document.execCommand("insertText", false, text);
    });
});
