Problem with Javascript ParentNode – Div containers

There is a problem with parentnodes divs, and I really don’t know what I’m doing wrong

I have tried different things but I can’t get it to display correctly, and the console always gives me the same error. So I would appreciate the help of someone more experienced than me to try to solve this problem.

The result should be:

<div class="ipcl-embed">
    <div class="ipcl-embed-player">theplayer embed HERE</div>
</div>
        

But what I get is this:

The output:

enter image description here

The console’s error message:

Uncaught DOMException: Node.insertBefore: Child to insert before is not a child of this node
processNode ...
EventListener.handleEvent* 

The Style:

 <style>
            .ipcl-embed {
                position: relative;
                padding-bottom: 56.25%;
                height: auto;
                overflow: hidden;
                background-color: #000000;
                border-radius: 5px;
                cursor:pointer;
            }
            .ipcl-embed-player {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
            }
          </style>

The script:

<script>
document.addEventListener("DOMContentLoaded", function() {
    function processNode(node) {
        if (node.nodeType === 3) {
            var parent = node.parentNode;
            var text = node.nodeValue;
            var regex = /\[ipcl=(.*?)\]/g;
            var match = regex.exec(text);
             while (match) {
                if (match[1].includes("(.*?)")) {
                    match = regex.exec(text);
                    continue;
                }
                var before = document.createTextNode(text.slice(0, match.index));
                var embedDiv = document.createElement('div');
                embedDiv.className = 'ipcl-embed';
                var embedId = 'ipcl-embed-player';
                embedDiv.id = embedId;
                parent.insertBefore(before, node);
                parent.insertBefore(embedDiv, node);
                var after = document.createTextNode(text.slice(regex.lastIndex));
                parent.insertBefore(after, node);
                parent.removeChild(node);
                var script = document.createElement('script');
                script.innerHTML = `theplayer.embed('` + embedId + `', '` + match[1] + `',{locale: "auto", autoplay: true});`;
                parent.insertBefore(script, after);
            }
        } else if (node.nodeType === 1) {
            for (var i = 0; i < node.childNodes.length; i++) {
                processNode(node.childNodes[i]);
            }
        }
    }
    processNode(document.body);
});
</script>