import $ from "jquery";

const SETUP_CLASS_NAME = "devowl-tinymce-setup";

/**
 * @see https://aurooba.com/adding-tinymce-editor-in-wordpress-customizer/
 */
function initializeTinyMce() {
    function setup(this: HTMLElement) {
        const element = $(this);
        element.addClass(SETUP_CLASS_NAME);
        const li = element.parents("li.customize-control");
        const settingId = element.data("customize-setting-link");
        const controlSettings = (window as any)._wpCustomizeSettings.controls[settingId] as {
            mediaButtons: boolean;
            toolbar1: string;
            toolbar2: string;
        };
        const { editor } = (window as any).wp;

        if (!controlSettings) {
            return;
        }

        const { mediaButtons, toolbar1, toolbar2 } = controlSettings;

        // Initialize with unique ID (so you can have multiple) and with all the settings attributed correctly
        try {
            editor.initialize($(this).attr("id"), {
                quicktags: true,
                dragDropUpload: false,
                teeny: false,
                textareaRows: 5,
                mediaButtons,
                tinymce: {
                    toolbar1,
                    toolbar2,
                    forced_root_block: false,
                    wordpress_adv_hidden: false,
                    wpautop: false,
                    setup: function (instance: any) {
                        li.on("customize-reset-value", (e, { defaultValue }) => {
                            instance.setContent(defaultValue);
                        });
                    },
                },
            });
        } catch (e) {
            // Silence is golden. This could happen if `user_can_richedit` is disabled
        }
    }

    function listeners(e: any, editor: any) {
        editor.on("change", () => {
            (window as any).tinyMCE.triggerSave();
            $("#".concat(editor.id)).trigger("change");
        });
    }

    $(document).on("tinymce-editor-init", listeners);

    const setupElements = () => $(`.customize-control-devowl-tinymce-editor:not(.${SETUP_CLASS_NAME})`).each(setup);
    setupElements();

    // OceanWP compatibility (https://github.com/oceanwp/oceanwp/blob/9beedbad85fcf6a9696d43a2645970c1c31f70c9/inc/customizer/assets/js/customizer.js)
    jQuery(document).on("oceanready", setupElements);
}

export { initializeTinyMce };
