/**
 * Sifency Taxonomy Form Move & CPT Thumbnail Uploader
 *
 * - Move WordPress Taxonomy add form to custom wrapper
 * - Reload page on successful tag/category addition
 * - Open WP Media Frame and set CPT Featured Image via AJAX
 *
 * @refactored Vanilla JS (ES6+)
 */

document.addEventListener('DOMContentLoaded', () => {

    const SifencyAdminFeatures = {

        init() {
            this.moveTaxonomyForm();
            this.listenTaxonomyAjax();
            this.initThumbnailUploader();
        },

        /**
         * Move Taxonomy Form
         * Uses MutationObserver instead of setInterval for better performance
         */
        moveTaxonomyForm() {
            const targetContainer = document.getElementById('sifency-move-form-here');
            if (!targetContainer) return;

            const checkAndMoveForm = () => {
                const wpForm = document.querySelector('#col-left .form-wrap');
                if (wpForm) {
                    targetContainer.appendChild(wpForm);
                    wpForm.classList.add('sifency-tax-add-form');
                    const h2 = wpForm.querySelector('h2');
                    if (h2) h2.style.display = 'none';
                    const parentWrapLabel = wpForm.querySelector('.form-field.term-parent-wrap label');
                    if (parentWrapLabel) parentWrapLabel.style.fontWeight = '600';

                    return true;
                }
                return false;
            };

            if (!checkAndMoveForm()) {
                const observer = new MutationObserver((mutations, obs) => {
                    if (checkAndMoveForm()) {
                        obs.disconnect();
                    }
                });

                const colLeft = document.getElementById('col-left');
                if (colLeft) {
                    observer.observe(colLeft, { childList: true, subtree: true });
                }
            }
        },
        listenTaxonomyAjax() {
            if (window.jQuery) {
                window.jQuery(document).ajaxComplete((event, xhr, settings) => {
                    if (settings.data && settings.data.includes('action=add-tag')) {
                        if (xhr.responseText && xhr.responseText.includes('<tr')) {
                            window.location.reload();
                        }
                    }
                });
            }
        },

        initThumbnailUploader() {
            document.body.addEventListener('click', (e) => {
                const wrapper = e.target.closest('.sifency-thumb-wrapper');
                if (!wrapper) return;

                e.preventDefault();
                this.handleThumbnailUpload(wrapper);
            });
        },

        /**
         * WP Media Frame & Fetch API logic for setting thumbnail
         */
        handleThumbnailUpload(wrapper) {
            const postId = wrapper.dataset.id;

            const frame = wp.media({
                title: 'Select Featured Image',
                button: { text: 'Set Featured Image' },
                multiple: false
            });

            frame.on('select', async () => {
                const attachment = frame.state().get('selection').first().toJSON();
                wrapper.classList.add('loading');

                const formData = new URLSearchParams();
                formData.append('action', 'sifency_set_cpt_thumbnail');
                formData.append('post_id', postId);
                formData.append('attach_id', attachment.id);
                formData.append('nonce', sifencyData.nonce);

                try {
                    const response = await fetch(sifencyData.ajax_url, {
                        method: 'POST',
                        body: formData,
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
                    });

                    const resData = await response.json();

                    if (resData.success) {
                        const img = wrapper.querySelector('.sifency-thumb-img');
                        const placeholder = wrapper.querySelector('.sifency-thumb-placeholder');

                        if (img) {
                            img.src = attachment.url;
                            img.classList.remove('hidden');
                        }
                        if (placeholder) {
                            placeholder.classList.add('hidden');
                        }
                    } else {
                        alert('Error saving image. Check console.');
                        console.error('Sifency Image Upload Error:', resData);
                    }
                } catch (error) {
                    alert('Network error occurred while saving image.');
                    console.error('Fetch Error:', error);
                } finally {
                    wrapper.classList.remove('loading');
                }
            });

            frame.open();
        }
    };

    SifencyAdminFeatures.init();

});