(function($) {
    const KanewsAIAdmin = {
        init() {
            this.cacheDom();
            if (!this.$popup.length) {
                return;
            }
            this.bindEvents();
        },

        cacheDom() {
            this.$popup = $('#kanews-ai-popup');
            this.$launch = $('#kanews-ai-launch');
            this.$closeButtons = $('.kanews-ai-popup-close');
            this.$taskSelector = $('#kanews-ai-selector');
            this.$taskInputs = $('#kanews-ai-task-inputs');
            this.$execute = $('#kanews-ai-execute');
            this.$results = $('#kanews-ai-results');
            this.$loading = $('#kanews-ai-loading');
            this.$providerSelector = $('#kanews-ai-provider');
            this.$window = $(window);
            this.apiStatus = (window.kanewsAiConfig && window.kanewsAiConfig.apiStatus) || {};
        },

        bindEvents() {
            this.$launch.on('click', () => this.togglePopup(true));
            this.$closeButtons.on('click', () => this.togglePopup(false));
            this.$window.on('click', (event) => {
                if ($(event.target).is('.kanews-ai-popup')) {
                    this.togglePopup(false);
                }
            });
            this.$taskSelector.on('change', (event) => this.renderTaskInputs(event.target.value));
            this.$execute.on('click', () => this.handleExecute());
        },

        togglePopup(shouldShow) {
            this.$popup.toggle(!!shouldShow);
        },

        renderTaskInputs(task) {
            const template = this.taskRenderers[task] ? this.taskRenderers[task]() : '';
            this.$taskInputs.html(template || '');
            this.$execute.prop('disabled', !task);
            if (task === 'featured-image') {
                this.bindImageSelection();
            }
        },

        handleExecute() {
            const task = this.$taskSelector.val();
            if (!task) {
                return;
            }

            const normalizedTask = this.normalizeTask(task);
            const selectedProvider = this.$providerSelector.val() || 'openai';
            const effectiveProvider = this.getEffectiveProvider(normalizedTask, selectedProvider);

            if (effectiveProvider.message) {
                this.showNotice('info', effectiveProvider.message);
            }

            if (this.isProviderInactive(effectiveProvider.provider)) {
                this.showProviderInactive(effectiveProvider.provider);
                return;
            }

            const payload = this.buildPayload(task, normalizedTask, effectiveProvider.provider);

            this.setLoadingState(true);

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: payload,
                timeout: 60000, // increase timeout to 60s for long TTS tasks
                dataType: 'text',
                success: (response) => this.handleAjaxSuccess(response, normalizedTask),
                error: (xhr, status, error) => this.handleAjaxError(xhr, status, error),
            });
        },

        buildPayload(task, normalizedTask, provider) {
            const selectedProvider = provider || this.$providerSelector.val() || 'openai';
            const payload = {
                action: 'generate_' + normalizedTask,
                post_id: $('#post_ID').val(),
                nonce: $('#kanews_ai_nonce_name').val(),
                provider: selectedProvider,
            };

            const enhancer = this.taskEnhancers[normalizedTask];
            if (enhancer) {
                enhancer.call(this, payload);
            }

            return payload;
        },

        handleAjaxSuccess(rawResponse, task) {
            let response = rawResponse;
            if (typeof response === 'string') {
                try {
                    response = JSON.parse(response);
                } catch (error) {
                    console.error('Response parse error:', error, response);
                    this.showNotice('error', 'Yanıt işlenirken hata oluştu. Konsolu kontrol edin.');
                    this.setLoadingState(false);
                    return;
        }
            }

            if (response.success) {
                const payload = (response && response.data && typeof response.data === 'object')
                    ? response.data
                    : response;
                const handler = this.successHandlers[task];
                const message = handler
                    ? handler.call(this, payload)
                    : (payload.message || response.message || 'İşlem tamamlandı.');
                this.showNotice('success', message);
            } else {
                const errorPayload = (response && response.data) ? response.data : response;
                const errorMessage = (response && (response.message || (response.data && response.data.message))) || 'İşlem sırasında bir hata oluştu.';

                if ((errorPayload && errorPayload.code === 'quota_exceeded') || this.isQuotaMessage(errorMessage)) {
                    this.showQuotaNotice(errorMessage);
                } else {
                    this.showNotice('error', errorMessage);
                }
            }

            this.setLoadingState(false);
        },

        handleAjaxError(xhr, status, error) {
            let errorMsg = 'İşlem sırasında bir hata oluştu.';
            let quota = false;

            if (status === 'timeout') {
                errorMsg = 'İşlem zaman aşımına uğradı. Lütfen daha sonra tekrar deneyin.';
            } else if (xhr.responseText) {
                try {
                    const parsed = JSON.parse(xhr.responseText);
                    if (parsed.message) {
                        errorMsg = parsed.message;
                    }
                    const payload = parsed.data || parsed;
                    if (payload && payload.code === 'quota_exceeded') {
                        quota = true;
                    } else if (this.isQuotaMessage(errorMsg)) {
                        quota = true;
                    }
                } catch (parseError) {
                    errorMsg = 'Sunucu hatası: ' + xhr.status + ' - ' + error;
                }
            } else if (this.isQuotaMessage(errorMsg)) {
                quota = true;
            }

            if (quota) {
                this.showQuotaNotice(errorMsg);
            } else {
                this.showNotice('error', errorMsg);
            }
            this.setLoadingState(false);
        },

        setLoadingState(isLoading) {
            this.$loading.html(isLoading ? '<span class="spinner is-active"></span>' : '');
            this.$execute.prop('disabled', isLoading || !this.$taskSelector.val());
            if (isLoading) {
                this.$results.empty();
            }
        },

        showNotice(type, message) {
            this.$results.html('<div class="notice notice-' + type + '">' + this.escapeHtml(message || '') + '</div>');
        },

        showProviderInactive(provider) {
            const label = this.getProviderLabel(provider);
            const message = provider === 'gemini'
                ? 'Gemini API anahtarı pasif. Lütfen ayarlar sayfasından anahtarınızı girin.'
                : 'OpenAI API anahtarı pasif. Lütfen ayarlar sayfasından anahtarınızı girin.';

            this.showNotice('warning', label + ': ' + message);
        },

        getEffectiveProvider(task, provider) {
            const info = {
                provider: provider || 'openai',
                message: '',
            };

            if (provider === 'gemini' && this.openAiOnlyTasks.includes(task)) {
                info.provider = 'openai';
                info.message = 'Bu görev Gemini tarafından desteklenmiyor. OpenAI ile devam edilecek.';
            }

            return info;
        },

        showQuotaNotice(message) {
            const text = message || 'Seçilen yapay zekâ sağlayıcısının API kotası doldu.';
            const helper = this.escapeHtml(text);
            this.$results.html(
                '<div class="notice notice-warning kanews-ai-quota">' +
                '<strong>API kotası doldu.</strong>' +
                '<p>' + helper + '</p>' +
                '<p>Kendi API anahtarınızı ayarlar sayfasından girebilir veya daha sonra tekrar deneyebilirsiniz.</p>' +
                '</div>'
            );
        },

        isQuotaMessage(message) {
            if (!message || typeof message !== 'string') {
                return false;
            }
            const text = message.toLowerCase();
            const keywords = ['quota', 'rate limit', 'limit exceeded', 'exceeded your current quota', 'insufficient tokens', '429'];
            return keywords.some((keyword) => text.includes(keyword));
        },

        escapeHtml(text) {
            return $('<div>').text(text || '').html();
        },

        getProviderLabel(provider) {
            if (provider === 'gemini') {
                return 'Gemini';
            }
            if (provider === 'openai') {
                return 'OpenAI';
            }
            return (provider || 'OpenAI').charAt(0).toUpperCase() + (provider || 'OpenAI').slice(1);
        },

        isProviderInactive(provider) {
            if (!provider || !this.apiStatus || typeof this.apiStatus !== 'object') {
                return false;
            }
            if (!(provider in this.apiStatus)) {
                return false;
            }
            return this.apiStatus[provider] === false;
        },

        convertToBlocks(text) {
            if (typeof wp === 'undefined' || !wp.blocks || !wp.blocks.parse) {
                return [];
            }

            let blocks = [];
            try {
                blocks = wp.blocks.parse(text || '');
            } catch (error) {
                blocks = [];
            }

            if (!blocks || !blocks.length) {
                blocks = this.plainTextToBlocks(text);
            }

            return blocks;
        },

        plainTextToBlocks(text) {
            if (typeof wp === 'undefined' || !wp.blocks || !wp.blocks.createBlock) {
                return [];
            }

            const paragraphs = (text || '')
                .split(/\n{2,}/)
                .map((part) => part.trim())
                .filter(Boolean);

            const safeParagraphs = paragraphs.length ? paragraphs : [text || ''];

            return safeParagraphs.map((paragraph) =>
                wp.blocks.createBlock('core/paragraph', {
                    content: this.escapeParagraph(paragraph),
                })
            );
        },

        escapeParagraph(text) {
            return this.escapeHtml(text || '').replace(/\n/g, '<br />');
        },

        formatClassicContent(text) {
            const paragraphs = (text || '')
                .split(/\n{2,}/)
                .map((part) => part.trim())
                .filter(Boolean);

            if (!paragraphs.length) {
                return text || '';
            }

            return '<p>' + paragraphs.map((p) => this.escapeParagraph(p)).join('</p><p>') + '</p>';
        },

        normalizeContent(text) {
            if (!text) {
                return '';
            }
            return String(text)
                .replace(/\*\*(.*?)\*\*/g, '$1')
                .replace(/__(.*?)__/g, '$1')
                .replace(/`([^`]+)`/g, '$1');
        },

        ensureValidTitle(title, content) {
            let clean = this.cleanTitle(title);
            if (!clean) {
                clean = this.generateTitleFromContent(content);
            }
            return this.enforceTitleLimit(clean);
        },

        cleanTitle(title) {
            return (title || '').replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim();
        },

        generateTitleFromContent(content) {
            const plain = this.cleanTitle((content || '').replace(/\n+/g, ' '));
            if (!plain) {
                return 'Yeni Haber Başlığı';
            }
            return plain.split(' ').slice(0, 14).join(' ');
        },

        enforceTitleLimit(title) {
            const limit = 110;
            if (!title) {
                return 'Yeni Haber Başlığı';
            }
            if (title.length <= limit) {
                return title;
            }
            const truncated = title.slice(0, limit).split(' ');
            truncated.pop();
            return truncated.join(' ').trim();
        },

        openAiOnlyTasks: ['tts'],

        normalizeTask(task) {
            return (task || '').replace(/-/g, '_');
        },

        isGutenberg() {
            return typeof wp !== 'undefined' && wp.data && wp.data.select('core/editor');
        },

        getContentEditor() {
            return typeof tinyMCE !== 'undefined' && tinyMCE.get('content') ? tinyMCE.get('content') : null;
        },

        bindImageSelection() {
            $(document).on('click', '.kanews-ai-image-item', function() {
                $('.kanews-ai-image-item').removeClass('selected');
                $(this).addClass('selected');
            });
        },

        taskRenderers: {
            'tts': () => `
                    <div class='kanews-ai-input-group'>
                        <label>Seslendiren</label>
                        <select id='kanews-voice-selector' class='widefat'>
                            <option value='alloy'>Alloy</option>
                            <option value='echo'>Echo</option>
                            <option value='fable'>Fable</option>
                            <option value='onyx'>Onyx</option>
                            <option value='nova'>Nova</option>
                            <option value='shimmer'>Shimmer</option>
                            <option value='ash'>Ash</option>
                            <option value='coral'>Coral</option>
                            <option value='sage'>Sage</option>
                        </select>
                    </div>
            `,
            'excerpt': () => `
                    <div class='kanews-ai-info-message'>
                        Yazı içeriğinden otomatik olarak açıklama oluşturulacak.
                    </div>
            `,
            'summary': () => `
                    <div class='kanews-ai-info-message'>
                        Yazı içeriğinden otomatik olarak özet oluşturulacak.
                    </div>
            `,
            'seo-title': () => `
                    <div class='kanews-ai-info-message'>
                        Yazı içeriğinden SEO dostu başlık oluşturulacak.
                    </div>
            `,
            'article': () => `
                    <div class='kanews-ai-input-group'>
                        <label>Konu</label>
                        <input autocomplete="off" type='text' id='article-topic' class='widefat' placeholder='Makale konusunu girin'>
                    </div>
                    <div class='kanews-ai-input-group'>
                        <label>Makale hakkında şunları unutma</label>
                        <input autocomplete="off" type='text' id='article-notes' class='widefat' placeholder='Eklemek istedikleriniz'>
                    </div>
                    <div class='kanews-ai-input-group'>
                        <label>Dil</label>
                        <select id='article-language' class='widefat'>
                            <option value='tr'>Türkçe</option>
                            <option value='en'>İngilizce</option>
                            <option value='de'>Almanca</option>
                            <option value='fr'>Fransızca</option>
                            <option value='es'>İspanyolca</option>
                            <option value='it'>İtalyanca</option>
                            <option value='ru'>Rusça</option>
                            <option value='ar'>Arapça</option>
                        </select>
                    </div>
                    <div class='kanews-ai-input-group'>
                        <label>Anlatım Biçimi</label>
                        <select id='article-style' class='widefat'>
                            <option value='news'>Haber Yazısı</option>
                            <option value='analysis'>Analiz</option>
                            <option value='interview'>Röportaj</option>
                            <option value='opinion'>Köşe Yazısı</option>
                            <option value='custom-news'>Özel Haber</option>
                            <option value='guide'>Rehber</option>
                            <option value='review'>İnceleme</option>
                            <option value='list'>Liste</option>
                            <option value='clickbait'>Clickbait</option>
                        </select>
                    </div>
                    <div class='kanews-ai-checkbox-group'>
                        <label><input type='checkbox' id='use-5w1h'> 5N1K Formatı Kullan</label>
                        <label><input type='checkbox' id='add-faq' checked> SSS Bölümü Ekle</label>
                        <label><input type='checkbox' id='use-tables'> Karşılaştırma Tabloları Kullan</label>
                        <label><input type='checkbox' id='use-list'> Listeler Kullan</label>
                    </div>
            `,
            'paraphrase': () => `
                    <div class='kanews-ai-input-group'>
                        <label>Özgünleştirme Seviyesi</label>
                        <select id='paraphrase-level' class='widefat'>
                            <option value='light'>Hafif (Minimal değişiklik)</option>
                            <option value='medium' selected>Orta (Dengeli değişiklik)</option>
                            <option value='high'>Yüksek (Tamamen özgün)</option>
                        </select>
                    </div>
                    <div class='kanews-ai-checkbox-group'>
                        <label><input type='checkbox' id='preserve-keywords' checked> Anahtar Kelimeleri Koru</label>
                        <label><input type='checkbox' id='preserve-structure' checked> Yapıyı Koru</label>
                        <label><input type='checkbox' id='improve-seo'> SEO'yu İyileştir</label>
                    </div>
                    <div class='kanews-ai-info-message'>
                        Mevcut yazı içeriği otomatik olarak özgünleştirilecek.
                    </div>
            `,
            'translate': () => `
                    <div class='kanews-ai-input-group'>
                        <label>Hedef Dil</label>
                        <select id='translate-target-language' class='widefat'>
                            <option value='tr'>Türkçe</option>
                            <option value='en' selected>İngilizce</option>
                            <option value='de'>Almanca</option>
                            <option value='fr'>Fransızca</option>
                            <option value='es'>İspanyolca</option>
                            <option value='it'>İtalyanca</option>
                            <option value='ru'>Rusça</option>
                            <option value='ar'>Arapça</option>
                            <option value='pt'>Portekizce</option>
                            <option value='zh'>Çince</option>
                            <option value='ja'>Japonca</option>
                            <option value='ko'>Korece</option>
                            <option value='nl'>Felemenkçe</option>
                            <option value='pl'>Lehçe</option>
                            <option value='sv'>İsveççe</option>
                            <option value='da'>Danca</option>
                            <option value='fi'>Fince</option>
                            <option value='no'>Norveççe</option>
                            <option value='cs'>Çekçe</option>
                            <option value='hu'>Macarca</option>
                            <option value='ro'>Rumence</option>
                            <option value='bg'>Bulgarca</option>
                            <option value='hr'>Hırvatça</option>
                            <option value='sk'>Slovakça</option>
                            <option value='sl'>Slovence</option>
                            <option value='el'>Yunanca</option>
                            <option value='he'>İbranice</option>
                            <option value='th'>Tayca</option>
                            <option value='vi'>Vietnamca</option>
                            <option value='id'>Endonezce</option>
                            <option value='ms'>Malayca</option>
                            <option value='hi'>Hintçe</option>
                            <option value='uk'>Ukraynaca</option>
                        </select>
                    </div>
                    <div class='kanews-ai-checkbox-group'>
                        <label><input type='checkbox' id='translate-title' checked> Başlığı da Çevir</label>
                    </div>
                    <div class='kanews-ai-info-message'>
                        Mevcut yazı içeriği seçilen dile çevrilecek.
                    </div>
            `,
            'featured-image': () => `
                    <div class='kanews-ai-input-group'>
                        <label>Görsel Konusu</label>
                        <input type='text' id='image-topic' class='widefat' placeholder='Görsel konusunu girin'>
                    </div>
                    <div id="kanews-ai-images-grid" class="kanews-ai-images-grid"></div>
            `,
            'comments': () => `
                    <div class='kanews-ai-input-group'>
                        <label>Yorum Sayısı</label>
                        <select id='comment-count' class='widefat'>
                            <option value='1'>1 Yorum</option>
                            <option value='3'>3 Yorum</option>
                            <option value='5' selected>5 Yorum</option>
                            <option value='10'>10 Yorum</option>
                            <option value='15'>15 Yorum</option>
                            <option value='20'>20 Yorum</option>
                        </select>
                    </div>
                    <div class='kanews-ai-info-message'>
                        Yazı içeriğine uygun gerçekçi yorumlar otomatik olarak oluşturulacak.
                    </div>
            `,
            'faq': () => `
                    <div class='kanews-ai-input-group'>
                        <label>Soru Sayısı</label>
                        <select id='faq-count' class='widefat'>
                            <option value='3'>3 Soru</option>
                            <option value='5' selected>5 Soru</option>
                            <option value='7'>7 Soru</option>
                            <option value='10'>10 Soru</option>
                        </select>
                    </div>
                    <div class='kanews-ai-checkbox-group'>
                        <label><input type='checkbox' id='faq-detailed' checked> Detaylı Cevaplar</label>
                    </div>
            `,
        },

        taskEnhancers: {
            comments(payload) {
                payload.count = $('#comment-count').val() || '5';
            },
            tts(payload) {
                payload.voice = $('#kanews-voice-selector').val() || 'alloy';
            },
            article(payload) {
                payload.topic = $('#article-topic').val();
                payload.notes = $('#article-notes').val();
                payload.language = $('#article-language').val();
                payload.style = $('#article-style').val();
                payload.use_5w1h = $('#use-5w1h').is(':checked');
                payload.use_list = $('#use-list').is(':checked');
                payload.add_faq = $('#add-faq').is(':checked');
                payload.use_tables = $('#use-tables').is(':checked');
            },
            paraphrase(payload) {
                payload.level = $('#paraphrase-level').val();
                payload.preserve_keywords = $('#preserve-keywords').is(':checked');
                payload.preserve_structure = $('#preserve-structure').is(':checked');
                payload.improve_seo = $('#improve-seo').is(':checked');
            },
            translate(payload) {
                payload.target_language = $('#translate-target-language').val();
                payload.translate_title = $('#translate-title').is(':checked');
            },
            featured_image(payload) {
                const topic = $('#image-topic').val();
                if (topic) {
                    payload.topic = topic;
                }

                    let selectedImage = $('.kanews-ai-image-item.selected').data('image');
                    if (selectedImage && typeof selectedImage === 'string') {
                        try {
                            selectedImage = JSON.parse(selectedImage);
                    } catch (error) {
                            selectedImage = null;
                        }
                    }

                if (selectedImage) {
                    payload.selected_image = selectedImage;
                    }
            },
            faq(payload) {
                payload.count = $('#faq-count').val() || '5';
                payload.detailed = $('#faq-detailed').is(':checked');
            },
        },

        successHandlers: {
            seo_title(response) {
                const cleaned = this.ensureValidTitle(this.normalizeContent(response.message || ''), '');
                if (cleaned) {
                    $('#title').val(cleaned);
                    if (this.isGutenberg()) {
                        wp.data.dispatch('core/editor').editPost({ title: cleaned });
                        }
                }
                return cleaned || 'Başlık güncellendi.';
            },
            article(response) {
                const content = this.normalizeContent(response.message || '');
                const lines = content.split('\n');
                let title = (lines[0] || '').replace(/<[^>]*>/g, '').trim();
                let articleContent = lines.slice(1).join('\n').trim();

                if (!title) {
                    title = $('#title').val() || '';
                }
                if (!articleContent) {
                    articleContent = content;
                }

                title = this.ensureValidTitle(title, articleContent);

                if (this.isGutenberg()) {
                    const blocks = this.convertToBlocks(articleContent);
                    wp.data.dispatch('core/editor').resetBlocks(blocks);
                    if (title) {
                        wp.data.dispatch('core/editor').editPost({ title });
                    }
                        } else {
                    if (title) {
                        $('#title').val(title);
                    }
                    const editor = this.getContentEditor();
                    const formatted = this.formatClassicContent(articleContent);
                    if (editor) {
                        editor.setContent(formatted);
                            } else {
                                $('#content').val(articleContent);
                            }
                        }

                return 'Makale oluşturuldu.';
            },
            paraphrase(response) {
                let content = this.normalizeContent(response.message || '');
                const titleMatch = content.match(/^title:\s*(.+)$/i);

                if (titleMatch) {
                    const newTitle = this.ensureValidTitle(titleMatch[1].trim(), content);
                    content = content.replace(/^title:.*\n?/i, '').trim();

                    if (newTitle) {
                        if (this.isGutenberg()) {
                            wp.data.dispatch('core/editor').editPost({ title: newTitle });
                        } else {
                            $('#title').val(newTitle);
                        }
                    }
                }

                if (this.isGutenberg()) {
                            wp.data.dispatch('core/editor').resetBlocks([]);
                    wp.data.dispatch('core/editor').insertBlocks(wp.blocks.parse(content));
                        } else {
                    const editor = this.getContentEditor();
                    if (editor) {
                        editor.setContent(content);
                            } else {
                                $('#content').val(content);
                            }
                        }
                return 'Makale özgünleştirildi.';
            },
            translate(response) {
                const content = this.normalizeContent(response.message || '');
                const translatedTitle = this.ensureValidTitle(this.normalizeContent(response.title || ''), content);
                        
                if (this.isGutenberg()) {
                            if (translatedTitle) {
                        wp.data.dispatch('core/editor').editPost({ title: translatedTitle });
                            }
                            wp.data.dispatch('core/editor').resetBlocks([]);
                    wp.data.dispatch('core/editor').insertBlocks(wp.blocks.parse(content));
                        } else {
                            if (translatedTitle) {
                                $('#title').val(translatedTitle);
                            }
                    const editor = this.getContentEditor();
                    if (editor) {
                        editor.setContent(content);
                            } else {
                                $('#content').val(content);
                            }
                        }

                return 'Makale çevrildi.';
            },
            excerpt(response) {
                if (response.message) {
                    $('#excerpt').val(this.normalizeContent(response.message));
                }
                return response.message || 'Açıklama hazırlandı.';
            },
            featured_image(response) {
                const imageId = response.image_id || (response.data && response.data.image_id);
                const imageUrl = response.image_url || (response.data && response.data.image_url);
                const message = response.message || (response.data && response.data.message);

                if (!imageId) {
                    return { type: 'error', message: 'Görsel üretilemedi.' };
                }

                if (this.isGutenberg()) {
                    wp.data.dispatch('core/editor').editPost({ featured_media: imageId });
                          }

                if (imageUrl) {
                    const thumb = $('#set-post-thumbnail img');
                            if (thumb.length) {
                        thumb.attr('src', imageUrl);
                            }
                          }

                this.$execute.prop('disabled', false);
                this.togglePopup(false);

                return message || 'Öne görsel ayarlandı.';
            },
            tts(response) {
                if (response.file_url) {
                        $('input[data-depend-id="post_text_to_speech"]').val(response.file_url);
                }
                if (response.file_id) {
                        $('input[name="kanews_post_options[post_text_to_speech][id]"]').val(response.file_id);
                }
                return 'Ses dosyası oluşturuldu.';
            },
            faq(response) {
                const content = this.normalizeContent(response.message || '');
                if (!content) {
                    return 'SSS üretildi.';
                }

                if (this.isGutenberg()) {
                    wp.data.dispatch('core/editor').insertBlocks(wp.blocks.parse(content));
                        } else {
                    const editor = this.getContentEditor();
                    if (editor) {
                        editor.setContent(editor.getContent() + content);
                            } else {
                        $('#content').val($('#content').val() + content);
                            }
                        }

                return 'SSS içerikleri eklendi.';
            },
        },
    };

    $(document).ready(() => KanewsAIAdmin.init());
})(jQuery);

// Gutenberg Toolbar Button
(function() {
    // Gutenberg yüklendiğinde çalış
    if (typeof wp === 'undefined' || typeof wp.domReady === 'undefined') {
        // Eğer wp henüz yüklenmemişse, yüklendiğinde çalıştır
        if (typeof window.addEventListener !== 'undefined') {
            window.addEventListener('load', function() {
                initGutenbergToolbar();
            });
        }
        return;
    }

    function initGutenbergToolbar() {
        if (typeof wp === 'undefined' || !wp.plugins || !wp.editPost || !wp.element || !wp.components) {
            return;
        }

        const { registerPlugin } = wp.plugins;
        const { PluginDocumentSettingPanel } = wp.editPost;
        const { createElement: el } = wp.element;
        const { Button } = wp.components;

        function openAIPopup() {
            // Popup'ı aç
            const popup = document.getElementById('kanews-ai-popup');
            if (popup) {
                popup.style.display = 'block';
            } else {
                // Eğer popup henüz yüklenmemişse, launch butonunu tetikle
                const launchButton = document.getElementById('kanews-ai-launch');
                if (launchButton) {
                    launchButton.click();
                } else {
                    // jQuery ile tetikle
                    if (typeof jQuery !== 'undefined') {
                        jQuery('#kanews-ai-launch').trigger('click');
                    }
                }
            }
        }

        // Toolbar'a buton ekle
        function addToolbarButton() {
            // editor-header__toolbar container'ı bul
            const toolbar = document.querySelector('.editor-header__toolbar, .edit-post-header__toolbar');
            if (!toolbar) {
                return;
            }

            // Buton zaten varsa ekleme
            if (document.getElementById('kanews-ai-toolbar-btn')) {
                return;
            }

            const button = document.createElement('button');
            button.id = 'kanews-ai-toolbar-btn';
            button.className = 'components-button is-secondary kanews-ai-toolbar-btn';
            button.style.cssText = 'display: flex; align-items: center; gap: 6px; margin-left: 8px;';
            button.innerHTML = '<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="none" stroke="currentColor" stroke-width="2" d="M18.3482396,15.9535197 C18.7664592,15.0561341 19,14.0553403 19,13 C19,9.13400675 15.8659932,6 12,6 C8.13400675,6 5,9.13400675 5,13 C5,14.1167756 5.2615228,15.1724692 5.72666673,16.1091793 L5.72666673,16.1091793 M12,3 C12.5522847,3 13,2.55228475 13,2 C13,1.44771525 12.5522847,1 12,1 C11.4477153,1 11,1.44771525 11,2 C11,2.55228475 11.4477153,3 12,3 Z M12,23 C12.5522847,23 13,22.5522847 13,22 C13,21.4477153 12.5522847,21 12,21 C11.4477153,21 11,21.4477153 11,22 C11,22.5522847 11.4477153,23 12,23 Z M12,6 L12,3 M9,14 C9.55228475,14 10,13.5522847 10,13 C10,12.4477153 9.55228475,12 9,12 C8.44771525,12 8,12.4477153 8,13 C8,13.5522847 8.44771525,14 9,14 Z M15,14 C15.5522847,14 16,13.5522847 16,13 C16,12.4477153 15.5522847,12 15,12 C14.4477153,12 14,12.4477153 14,13 C14,13.5522847 14.4477153,14 15,14 Z M6,18.9876876 L5,16 C5,16 5.07242747,15.2283988 5.5,15.5 C6.43069361,16.0911921 8.57396448,17 12,17 C15.5536669,17 17.6181635,16.0844828 18.5,15.5 C18.8589052,15.262117 19,16 19,16 L18,18.9876876 C18,18.9876876 17.0049249,20.9999997 12,21 C6.99507512,21.0000003 6,18.9876876 6,18.9876876 Z"/></svg> <span> Kanews Ai ile Başla</span>';
            button.onclick = function(e) {
                e.preventDefault();
                openAIPopup();
            };

            // Toolbar'ın içine direkt ekle
            toolbar.appendChild(button);

            // Meta box'ı gizle
            hideMetaBox();
        }

        // Meta box'ı gizle
        function hideMetaBox() {
            const metaBox = document.getElementById('kanews_ai_meta_box');
            if (metaBox) {
                metaBox.style.display = 'none';
            }
        }

        // Document settings panel'e ekleme - Toolbar butonu olduğu için panel'i eklemiyoruz
        // Panel'i gizlemek için CSS kullanıyoruz
        function hideSidebarPanel() {
            // Farklı selector'larla panel'i bul
            const selectors = [
                '.kanews-ai-panel',
                '[data-name="kanews-ai-panel"]',
                '.edit-post-sidebar__panel-tab[aria-label*="Kanews AI"]',
                '.components-panel__body-title:contains("Kanews AI")',
                '.edit-post-sidebar .components-panel__body:has(.kanews-ai-panel)'
            ];
            
            selectors.forEach(function(selector) {
                try {
                    const elements = document.querySelectorAll(selector);
                    elements.forEach(function(el) {
                        // Eğer "Kanews AI" içeriyorsa gizle
                        if (el.textContent && el.textContent.includes('Kanews AI')) {
                            el.style.display = 'none';
                            // Parent panel'i de gizle
                            const panel = el.closest('.components-panel__body');
                            if (panel) {
                                panel.style.display = 'none';
                            }
                        }
                    });
                } catch(e) {
                    // Selector geçersizse devam et
                }
            });
            
            // Tüm sidebar panel'lerini kontrol et
            const allPanels = document.querySelectorAll('.components-panel__body, .edit-post-sidebar__panel-tab');
            allPanels.forEach(function(panel) {
                if (panel.textContent && panel.textContent.includes('Kanews AI')) {
                    panel.style.display = 'none';
                }
            });
        }
        
        // Panel'i gizle
        hideSidebarPanel();

        // Toolbar butonunu ekle
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', function() {
                setTimeout(function() {
                    addToolbarButton();
                    // Eğer toolbar butonu eklendiyse meta box'ı gizle
                    if (document.getElementById('kanews-ai-toolbar-btn')) {
                        hideMetaBox();
                    }
                }, 1000);
            });
        } else {
            setTimeout(function() {
                addToolbarButton();
                // Eğer toolbar butonu eklendiyse meta box'ı gizle
                if (document.getElementById('kanews-ai-toolbar-btn')) {
                    hideMetaBox();
                }
            }, 1000);
        }

        // Gutenberg yüklendiğinde tekrar dene
        if (typeof wp !== 'undefined' && wp.domReady) {
            wp.domReady(function() {
                setTimeout(function() {
                    addToolbarButton();
                    // Eğer toolbar butonu eklendiyse meta box'ı gizle
                    if (document.getElementById('kanews-ai-toolbar-btn')) {
                        hideMetaBox();
                    }
                }, 500);
            });
        }

        // Gutenberg editöründe olduğumuzu kontrol et ve meta box'ı gizle
        function checkAndHideMetaBox() {
            // Gutenberg editöründe olduğumuzu kontrol et
            const isGutenberg = document.querySelector('.block-editor-page, .editor-header__toolbar, .edit-post-header__toolbar');
            if (isGutenberg) {
                hideMetaBox();
            }
        }

        // Sayfa yüklendiğinde kontrol et
        checkAndHideMetaBox();
        
        // MutationObserver ile meta box ve sidebar panel eklendiğinde gizle
        const observer = new MutationObserver(function(mutations) {
            const toolbar = document.querySelector('.editor-header__toolbar, .edit-post-header__toolbar');
            if (toolbar && document.getElementById('kanews_ai_meta_box')) {
                hideMetaBox();
            }
            
            // Sidebar panel'i gizle
            hideSidebarPanel();
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
        
        // Sidebar panel'i periyodik olarak kontrol et ve gizle
        setInterval(function() {
            hideSidebarPanel();
        }, 1000);
    }

    // Sayfa yüklendiğinde çalıştır
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initGutenbergToolbar);
    } else {
        initGutenbergToolbar();
    }
})();