function app() {
    return {
        wysiwyg: null,
        init: function (el) {
            this.wysiwyg = el;
            this.updateTextarea();
            this.wysiwyg.contentDocument.body.addEventListener('input', this.updateTextarea.bind(this));
            this.wysiwyg.contentDocument.querySelector('head').innerHTML += `<style>
            *, ::after, ::before {box-sizing: border-box;}
            :root {tab-size: 4;}
            html {line-height: 1.15;text-size-adjust: 100%;}
            body {margin: 0px; padding: 1rem 0.5rem;}
            body {font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";}
            </style>`;
            this.wysiwyg.contentDocument.body.innerHTML = '';
            this.wysiwyg.contentDocument.designMode = "on";
        },
        format: function (cmd, param) {
            this.wysiwyg.contentDocument.execCommand(cmd, false, param || null);
            this.updateTextarea();
        },
        updateTextarea: function() {
            // Wrap the body's innerHTML in a div and apply the direction class
            var wrapperDiv = document.createElement('div');
            wrapperDiv.className = this.wysiwyg.classList.contains('rtl')? 'rtl' : 'ltr';
            wrapperDiv.innerHTML = this.wysiwyg.contentDocument.body.innerHTML;
            
            // Set the textarea value to the wrapper div's outerHTML
            document.getElementById('textEditor').value = wrapperDiv.outerHTML;
            console.log(wrapperDiv)
        },
        setDirection: function(direction) {
            // Remove both classes first
            this.wysiwyg.classList.remove('rtl', 'ltr');
            this.wysiwyg.contentDocument.body.classList.remove('rtl', 'ltr');
            document.getElementById('textEditor').classList.remove('rtl', 'ltr');
        
            // Add the specified direction class
            this.wysiwyg.classList.add(direction);
            this.wysiwyg.contentDocument.body.classList.add(direction);
            document.getElementById('textEditor').classList.add(direction);
        
            // Apply direction style to the body of the iframe
            this.wysiwyg.contentDocument.body.style.direction = direction;
        
            this.updateTextarea();
    
        }
    }
}
