tinymce.PluginManager.add('dracula_tinymce_js', function (editor) {

    const enableEditorDarkMode = (e) => {
        const editorBody = editor.getBody();
        const {colors} = draculaDarkMode;

        if (!e && !draculaDarkMode.isEnabled()) {
            draculaDarkMode.enable();
        }

        editorBody.parentNode.setAttribute('data-dracula-scheme', 'dark');

        document.querySelector('.mce-i-dracula_toggle').classList.add('mode-dark');

        editorBody.style.setProperty('--dracula-background', colors.background);
        editorBody.style.setProperty('--dracula-text', colors.text);
    }

    const disableEditorDarkMode = (e) => {

        if (!e && draculaDarkMode.isEnabled()) {
            draculaDarkMode.disable();
        }

        const editorBody = editor.getBody();
        editorBody.parentNode.removeAttribute('data-dracula-scheme');
        document.querySelector('.mce-i-dracula_toggle').classList.remove('mode-dark');
    }

    editor.addButton('dracula_toggle', {
        title: wp.i18n.__("Dark Mode", "dracula-dark-mode"),
        classes: 'dracula-toggle',
        onclick: function (e) {

            const element = e.target;
            const shouldDark = !element.classList.contains('mode-dark');

            if (shouldDark) {
                element.classList.add('mode-dark');
                enableEditorDarkMode();
            } else {
                element.classList.remove('mode-dark');
                disableEditorDarkMode();
            }

            const mode = shouldDark ? 'dark' : 'light';
            localStorage.setItem('dracula_mode_admin', mode);

        }
    });

    editor.on('init', () => {

        if (draculaDarkMode.isEnabled()) {
            enableEditorDarkMode();
        }

    });

    const darkModeStateObserver = new MutationObserver((mutationsList) => {
        mutationsList.forEach((mutation) => {
            if (mutation.type === "attributes" && mutation.attributeName === "data-dracula-scheme") {

                const isDarkMode = document.documentElement.getAttribute('data-dracula-scheme') === 'dark';

                if (isDarkMode) {
                    enableEditorDarkMode();
                } else {
                    disableEditorDarkMode();
                }

            }
        });
    });

    darkModeStateObserver.observe(document.documentElement, {
        attributes: true,
    });

});



