jQuery(document).ready(function($) {
////  Button handlers  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    document.getElementById("gen-button-id").addEventListener("click", function () {
        const container = document.getElementById("image-container");
        const genButton = document.getElementById("gen-button-id");
        const addToPostButton = document.getElementById("add-image-to-post-button")

        removePreviousImage();
        toggleLoadingIcon();
        disableButtons(genButton, addToPostButton)

        const data = {
            'action': "gen_button_action",
            'promt-field-name': document.getElementById("promt-field-id").value
        };

        doAjaxQuery(data, function (data) {
            if (data.image_url === null || data.image_url === "") {
                var text = document.createElement("p")
                text.innerText = "Произошла ошибка при генерации изображения"
                text.style = "color: red"
                container.appendChild(text)
            } else {
                var img = document.createElement("img");
                img.setAttribute('id', "generated-image");
                img.setAttribute('src', data.image_url);
                addExpandedAction(img);

                container.appendChild(img);
                addToPostButton.disabled = false
            }
            genButton.disabled = false;
            toggleLoadingIcon()
        })
    });

    $("#rewriteBtn").click( function() {
        const data = {
            'action': "rewrite_action",
            'post_id': $(this).data("post_id")
        };

        disable($("#rewriteBtn"))

        doAjaxQuery(data, function (data) {
            let status = data.status

            if (status === "success") {
                location.reload()
            }
        })

        enable($("#rewriteBtn"))
    })


    document.getElementById("add-image-to-post-button").addEventListener("click", function () {
        $image_url = document.getElementById("generated-image").src;

        insertImageBlockToPost($image_url)
        removePreviousImage();
    });

    function addExpandedAction(image) {
        image.addEventListener('click', function () {
            const fullPage = document.querySelector('#fullpage');
            fullPage.style.backgroundImage = 'url(' + image.src + ')';
            fullPage.style.display = 'block';
        });
    }

    // Эта функция добавит блок изображения в редактор Gutenberg
    function insertImageBlockToPost(imageUrl) {
        // Обеспечение доступности объекта wp и его методов
        if (wp && wp.blocks && wp.data && wp.element && wp.editPost) {
            const {createBlock} = wp.blocks;
            const {dispatch} = wp.data;
            const {Fragment} = wp.element;
            const {insertBlocksAfter} = wp.editPost;

            // Создание блока изображения
            const block = createBlock('core/image', {
                url: imageUrl,
                alt: 'Описание'
            });

            // Получение выбранного блока
            const selectedBlock = wp.data.select('core/block-editor').getSelectedBlock();

            // Вставка блока изображения после выбранного блока
            dispatch('core/block-editor').insertBlock(block, selectedBlock ? selectedBlock.clientId + 1 : 0);
        } else {
            console.error('Возникла ошибка при попытке доступа к API редактора Gutenberg.');
        }
    }

    ////  Helpers  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    function removePreviousImage() {
        const container = document.getElementById("image-container");

        if (container.firstChild) {
            container.removeChild(container.firstChild);
        }
    }

    function disableButtons(...buttons) {
        buttons.forEach(button => button.disabled = true)
    }

    function toggleLoadingIcon() {
        const loading_icon = document.getElementById("loading-icon")
        const isDisplay = loading_icon.style.display === "block";

        loading_icon.style.display = isDisplay ? "none" : "block"
    }

    let startBlinking = (btn) => {
        btn.addClass("blinking")
        disable(btn)
    }
    let stopBlinking = (btn) => {
        btn.removeClass("blinking")
        enable(btn)
    }

    let enable = (el) => {
        el.prop("disabled", false)
    }

    let disable = (el) => {
        el.prop("disabled", true)
    }
});