document.addEventListener('DOMContentLoaded', () => {
    const dynamicSelectors = ["#menu-to-edit"];


    if (typeof wp === 'undefined' || typeof wp.media === 'undefined')
        return;

    function initMediaUploader(parent) {
        let frame;

        const imgInput = parent.querySelector('[data-type="iu-input"]');
        const addButton = parent.querySelector('[data-type="iu-add"]');
        const removeButton = parent.querySelector('[data-type="iu-remove"]');
        const imgContainer = parent.querySelector('[data-type="iu-image"]');

        if (!imgInput || !addButton || !removeButton || !imgContainer)
            return;

        addButton.addEventListener('click', (e) => {
            e.preventDefault();

            if (frame) {
                frame.open();
                return;
            }

            frame = wp.media({
                title: 'مدیا مدنظر خود را انتخاب یا بارگذاری نمایید.',
                button: {
                    text: 'تایید'
                },
                library: {
                    type: 'image/svg+xml'
                },
                multiple: false
            });

            frame.on('select', () => {
                const attachment = frame.state().get('selection').first().toJSON();
                imgInput.value = attachment.id;
                let img = attachment.sizes.thumbnail || attachment.sizes.full;
                imgContainer.innerHTML = `<img src="${img.url}" alt="${attachment.alt}">`;
            });

            frame.open();
        });

        removeButton.addEventListener('click', (e) => {
            e.preventDefault();
            imgInput.value = '';
            imgContainer.innerHTML = '';
        });
    }

    const appendScript = () => {
        const uploaders = document.querySelectorAll('[data-event="image-uploader"]');

        uploaders.forEach(uploader => {
            if (uploader.dataset.activeScript !== 'true') {
                initMediaUploader(uploader);
                uploader.dataset.activeScript = 'true';
            }
        });
    };
    appendScript();

    dynamicSelectors.forEach(selector => {
        let elements = document.querySelectorAll(selector);
        elements.forEach(element => {
            new MutationObserver(() => {
                appendScript();
            }).observe(element, {
                childList: true
            });
        });
    });
});