/* ==================================================
   Nuclear Fancy Pants Edition™ -- NUCLEAR+++
   File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/assets/js/amai-blog-generator.js
   Description: Blog post generator modal -- title selection
   Last Edited: 2026-04-24
   ================================================== */
document.addEventListener('DOMContentLoaded', function () {
    var modal      = document.getElementById('amai-gen-modal');
    var openBtn    = document.getElementById('amai-gen-open-btn');
    var closeBtn   = document.getElementById('amai-gen-close');
    var titlesList = document.getElementById('amai-gen-titles-list');
    var loading    = document.getElementById('amai-gen-loading');
    var loadingMsg = document.getElementById('amai-gen-loading-msg');
    var errorEl    = document.getElementById('amai-gen-error');
    var writeBtn   = document.getElementById('amai-gen-write-btn');
    var refreshBtn = document.getElementById('amai-gen-refresh-btn');

    // Boot auto-write/optimize before modal guard
    if (window.amaiGen && window.amaiGen.autoWrite === '1' && window.amaiGen.postId > 0) {
        bootAutoWrite();
    }
    if (window.amaiGen && window.amaiGen.autoOpt === '1') {
        bootAutoOptimize();
    }
    if (!modal || !openBtn) { return; }

    var selectedTitle = '';

    function openModal() {
        modal.classList.add('show');
        selectedTitle = '';
        writeBtn.disabled = true;
        titlesList.innerHTML = '';
        refreshBtn.style.display = 'none';
        hideError();
        fetchTitles();
    }

    function closeModal() {
        modal.classList.remove('show');
    }

    function showLoading(msg) {
        loading.style.display = 'flex';
        if (loadingMsg) { loadingMsg.textContent = msg || 'Generating title ideas...'; }
        titlesList.innerHTML = '';
        writeBtn.disabled = true;
        refreshBtn.style.display = 'none';
        hideError();
    }

    function hideLoading() {
        loading.style.display = 'none';
    }

    function showError(msg) {
        errorEl.textContent = msg;
        errorEl.style.display = 'block';
    }

    function hideError() {
        errorEl.style.display = 'none';
        errorEl.textContent = '';
    }

    function fetchTitles() {
        var ajaxurl = window.amaiGen ? window.amaiGen.ajaxurl : window.ajaxurl;
        var nonce   = window.amaiGen ? window.amaiGen.nonce   : '';

        showLoading('Generating title ideas...');

        var body = new URLSearchParams();
        body.append('action', 'amai_blog_gen_titles');
        body.append('nonce',  nonce);

        fetch(ajaxurl, {
            method:  'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body:    body.toString(),
        })
        .then(function (r) { return r.json(); })
        .then(function (data) {
            hideLoading();
            if (!data.success || !data.data || !data.data.titles) {
                showError('Could not generate titles. Please try again.');
                refreshBtn.style.display = 'inline-flex';
                return;
            }
            renderTitles(data.data.titles);
        })
        .catch(function () {
            hideLoading();
            showError('Request failed. Please try again.');
            refreshBtn.style.display = 'inline-flex';
        });
    }

    function renderTitles(titles) {
        titlesList.innerHTML = '';
        selectedTitle = '';
        writeBtn.disabled = true;

        titles.forEach(function (item) {
            var title = (typeof item === 'object' && item.title) ? item.title : item;
            var category = (typeof item === 'object' && item.category) ? item.category : '';
            var card = document.createElement('div');
            card.className = 'amai-gen-title-card';
            var titleText = document.createElement('span');
            titleText.className = 'amai-gen-title-text';
            titleText.textContent = title;
            card.appendChild(titleText);
            if (category) {
                var pill = document.createElement('span');
                pill.className = 'amai-gen-title-pill';
                pill.textContent = category;
                card.appendChild(pill);
            }
            card.addEventListener('click', function () {
                document.querySelectorAll('.amai-gen-title-card').forEach(function (c) {
                    c.classList.remove('selected');
                });
                card.classList.add('selected');
                selectedTitle = title;
                writeBtn.disabled = false;
            });
            titlesList.appendChild(card);
        });

        refreshBtn.style.display = 'inline-flex';
    }

    function createPost(aiWrite) {
        if (!selectedTitle) { return; }
        var ajaxurl = window.amaiGen ? window.amaiGen.ajaxurl : window.ajaxurl;
        var nonce   = window.amaiGen ? window.amaiGen.nonce   : '';

        showLoading('Creating your post...');
        writeBtn.disabled = true;

        var body = new URLSearchParams();
        body.append('action',   'amai_blog_gen_create');
        body.append('nonce',    nonce);
        body.append('title',    selectedTitle);
        body.append('ai_write', aiWrite ? '1' : '0');

        fetch(ajaxurl, {
            method:  'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body:    body.toString(),
        })
        .then(function (r) { return r.json(); })
        .then(function (data) {
            if (!data.success || !data.data || !data.data.edit_url) {
                hideLoading();
                showError('Failed to create post. Please try again.');
                writeBtn.disabled = false;
                return;
            }
            window.location.href = data.data.edit_url;
        })
        .catch(function () {
            hideLoading();
            showError('Request failed. Please try again.');
            writeBtn.disabled = false;
        });
    }

    openBtn.addEventListener('click', openModal);
    closeBtn.addEventListener('click', closeModal);
    writeBtn.addEventListener('click', function () { createPost(true); });
    refreshBtn.addEventListener('click', fetchTitles);

    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && modal.classList.contains('show')) {
            closeModal();
        }
    });

    function bootAutoWrite() {
        var overlay    = document.getElementById('amai-gen-overlay');
        var overlayMsg = document.getElementById('amai-gen-overlay-msg');
        var postId     = window.amaiGen.postId;
        var ajaxurl    = window.amaiGen.ajaxurl;
        var nonce      = window.amaiGen.nonce;

        if (!overlay) { return; }
        overlay.style.display = 'flex';
        if (overlayMsg) { overlayMsg.textContent = 'Generating content...'; }

        var body = new URLSearchParams();
        body.append('action',  'amai_blog_gen_content');
        body.append('nonce',   nonce);
        body.append('post_id', postId);

        fetch(ajaxurl, {
            method:  'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body:    body.toString(),
        })
        .then(function (r) { return r.json(); })
        .then(function (data) {
            if (!data.success) {
                overlay.style.display = 'none';
                return;
            }
            if (overlayMsg) { overlayMsg.textContent = 'Optimizing your post...'; }
            // Reload page so TinyMCE picks up saved content, then auto-optimize fires
            // We pass amai_opt=1 to trigger the orchestrator on reload
            var url = window.location.href
                .replace('amai_gen=1', 'amai_opt=1');
            window.location.href = url;
        })
        .catch(function () {
            overlay.style.display = 'none';
        });
    }

    function bootAutoOptimize() {
        // Show a non-blocking banner then click Auto-Optimize after a short delay
        var banner = document.createElement('div');
        banner.id = 'amai-gen-opt-banner';
        banner.style.cssText = 'position:fixed;top:32px;left:50%;transform:translateX(-50%);z-index:99999;'
            + 'background:#D97757;color:#fff;font-family:DM Sans,sans-serif;font-size:14px;'
            + 'padding:10px 22px;border-radius:8px;box-shadow:0 4px 16px rgba(0,0,0,0.15);';
        banner.textContent = 'Post written - optimizing now...';
        document.body.appendChild(banner);
        var attempts = 0;
        var poll = setInterval(function () {
            attempts++;
            var optimizeBtn = document.getElementById('amai-sw-optimize-btn');
            if (optimizeBtn) {
                clearInterval(poll);
                optimizeBtn.click();
                setTimeout(function () {
                    if (banner.parentNode) { banner.parentNode.removeChild(banner); }
                }, 3000);
            } else if (attempts >= 30) {
                clearInterval(poll);
                if (banner.parentNode) { banner.parentNode.removeChild(banner); }
            }
        }, 500);
    }
});


    // --------------------------------------------------
    // Image manager meta box
    // --------------------------------------------------
    (function () {
        var manager = document.getElementById('amai-img-manager');
        if (!manager) { return; }
        if (!window.amaiGen || window.amaiGen.isGenerated !== '1') { return; }

        var ajaxurl = window.amaiGen.ajaxurl;
        var nonce   = window.amaiGen.nonce;
        var postId  = window.amaiGen.postId;

        // Tab switching
        var tabs   = manager.querySelectorAll('.amai-img-tab');
        var panels = manager.querySelectorAll('.amai-img-panel');

        tabs.forEach(function (tab) {
            tab.addEventListener('click', function () {
                tabs.forEach(function (t) { t.classList.remove('active'); });
                panels.forEach(function (p) { p.classList.remove('active'); });
                tab.classList.add('active');
                var panelId = 'amai-img-panel-' + tab.getAttribute('data-tab');
                var panel = document.getElementById(panelId);
                if (panel) { panel.classList.add('active'); }
                hideSuccess();
                // Auto-search when Unsplash tab is clicked and grid is empty
                if (tab.getAttribute('data-tab') === 'unsplash' && unsplashGrid && unsplashGrid.children.length === 0) {
                    unsplashSearch();
                }
            });
        });

        function showSuccess() {
            var el = document.getElementById('amai-img-success');
            if (el) { el.style.display = 'block'; }
        }

        function hideSuccess() {
            var el = document.getElementById('amai-img-success');
            if (el) { el.style.display = 'none'; }
        }

        // --------------------------------------------------
        // Unsplash search
        // --------------------------------------------------
        var unsplashBtn     = document.getElementById('amai-img-unsplash-btn');
        var unsplashQuery   = document.getElementById('amai-img-unsplash-query');
        var unsplashGrid    = document.getElementById('amai-img-unsplash-grid');
        var unsplashLoading = document.getElementById('amai-img-unsplash-loading');
        var unsplashError   = document.getElementById('amai-img-unsplash-error');
        var selectedPhoto   = null;

        function unsplashSearch() {
            var query = unsplashQuery ? unsplashQuery.value.trim() : '';
            if (!query) { return; }

            selectedPhoto = null;
            if (unsplashGrid)    { unsplashGrid.innerHTML = ''; }
            if (unsplashError)   { unsplashError.style.display = 'none'; unsplashError.textContent = ''; }
            if (unsplashLoading) { unsplashLoading.style.display = 'flex'; }
            if (unsplashBtn)     { unsplashBtn.disabled = true; }

            var body = new URLSearchParams();
            body.append('action', 'amai_blog_img_unsplash');
            body.append('nonce',  nonce);
            body.append('query',  query);

            fetch(ajaxurl, {
                method:  'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body:    body.toString(),
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (unsplashLoading) { unsplashLoading.style.display = 'none'; }
                if (unsplashBtn)     { unsplashBtn.disabled = false; }
                if (!data.success || !data.data || !data.data.photos) {
                    if (unsplashError) {
                        unsplashError.textContent = (data.data && data.data.message) ? data.data.message : 'No photos found.';
                        unsplashError.style.display = 'block';
                    }
                    return;
                }
                renderUnsplashGrid(data.data.photos);
            })
            .catch(function () {
                if (unsplashLoading) { unsplashLoading.style.display = 'none'; }
                if (unsplashBtn)     { unsplashBtn.disabled = false; }
                if (unsplashError) {
                    unsplashError.textContent = 'Request failed. Please try again.';
                    unsplashError.style.display = 'block';
                }
            });
        }

        function renderUnsplashGrid(photos) {
            if (!unsplashGrid) { return; }
            unsplashGrid.innerHTML = '';
            selectedPhoto = null;

            photos.forEach(function (photo) {
                var thumb = document.createElement('div');
                thumb.className = 'amai-img-thumb';

                var img = document.createElement('img');
                img.src = photo.thumb || photo.url;
                img.alt = photo.photographer || '';
                img.loading = 'lazy';

                var credit = document.createElement('div');
                credit.className = 'amai-img-thumb-credit';
                credit.textContent = photo.photographer || '';

                thumb.appendChild(img);
                thumb.appendChild(credit);

                thumb.addEventListener('click', function () {
                    unsplashGrid.querySelectorAll('.amai-img-thumb').forEach(function (t) {
                        t.classList.remove('selected');
                    });
                    thumb.classList.add('selected');
                    selectedPhoto = photo;
                    unsplashSetSelected();
                });

                unsplashGrid.appendChild(thumb);
            });
        }

        function unsplashSetSelected() {
            if (!selectedPhoto) { return; }

            if (unsplashError) { unsplashError.style.display = 'none'; }

            var body = new URLSearchParams();
            body.append('action',       'amai_blog_img_unsplash_set');
            body.append('nonce',        nonce);
            body.append('post_id',      postId);
            body.append('url',          selectedPhoto.url);
            body.append('photographer', selectedPhoto.photographer || '');
            body.append('profile_url',  selectedPhoto.profile_url || '');

            fetch(ajaxurl, {
                method:  'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body:    body.toString(),
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (!data.success) {
                    if (unsplashError) {
                        unsplashError.textContent = (data.data && data.data.message) ? data.data.message : 'Failed to set image.';
                        unsplashError.style.display = 'block';
                    }
                    return;
                }
                showSuccess();
                setTimeout(function () { window.location.reload(); }, 1500);
            })
            .catch(function () {
                if (unsplashError) {
                    unsplashError.textContent = 'Request failed. Please try again.';
                    unsplashError.style.display = 'block';
                }
            });
        }

        if (unsplashBtn) {
            unsplashBtn.addEventListener('click', unsplashSearch);
        }
        if (unsplashQuery) {
            unsplashQuery.addEventListener('keydown', function (e) {
                if (e.key === 'Enter') { unsplashSearch(); }
            });
        }

        // --------------------------------------------------
        // AI image generate
        // --------------------------------------------------
        var aiBtn     = document.getElementById('amai-img-ai-btn');
        var aiPrompt  = document.getElementById('amai-img-ai-prompt');
        var aiLoading = document.getElementById('amai-img-ai-loading');
        var aiError   = document.getElementById('amai-img-ai-error');

        if (aiBtn) {
            aiBtn.addEventListener('click', function () {
                var prompt = aiPrompt ? aiPrompt.value.trim() : '';
                if (!prompt) { return; }

                if (aiError)   { aiError.style.display = 'none'; aiError.textContent = ''; }
                if (aiLoading) { aiLoading.style.display = 'flex'; }
                aiBtn.disabled = true;
                hideSuccess();

                var body = new URLSearchParams();
                body.append('action',  'amai_blog_img_ai_generate');
                body.append('nonce',   nonce);
                body.append('post_id', postId);
                body.append('prompt',  prompt);

                fetch(ajaxurl, {
                    method:  'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body:    body.toString(),
                })
                .then(function (r) { return r.json(); })
                .then(function (data) {
                    if (aiLoading) { aiLoading.style.display = 'none'; }
                    aiBtn.disabled = false;
                    if (!data.success) {
                        if (aiError) {
                            aiError.textContent = (data.data && data.data.message) ? data.data.message : 'Generation failed.';
                            aiError.style.display = 'block';
                        }
                        return;
                    }
                    showSuccess();
                    setTimeout(function () { window.location.reload(); }, 1500);
                })
                .catch(function () {
                    if (aiLoading) { aiLoading.style.display = 'none'; }
                    aiBtn.disabled = false;
                    if (aiError) {
                        aiError.textContent = 'Request failed. Please try again.';
                        aiError.style.display = 'block';
                    }
                });
            });
        }

        // --------------------------------------------------
        // Remove image
        // --------------------------------------------------
        var removeBtn   = document.getElementById('amai-img-remove-btn');
        var removeError = document.getElementById('amai-img-remove-error');

        if (removeBtn) {
            removeBtn.addEventListener('click', function () {
                if (removeError) { removeError.style.display = 'none'; removeError.textContent = ''; }
                removeBtn.disabled = true;
                hideSuccess();

                var body = new URLSearchParams();
                body.append('action',  'amai_blog_img_remove');
                body.append('nonce',   nonce);
                body.append('post_id', postId);

                fetch(ajaxurl, {
                    method:  'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body:    body.toString(),
                })
                .then(function (r) { return r.json(); })
                .then(function (data) {
                    removeBtn.disabled = false;
                    if (!data.success) {
                        if (removeError) {
                            removeError.textContent = (data.data && data.data.message) ? data.data.message : 'Failed to remove image.';
                            removeError.style.display = 'block';
                        }
                        return;
                    }
                    showSuccess();
                })
                .catch(function () {
                    removeBtn.disabled = false;
                    if (removeError) {
                        removeError.textContent = 'Request failed. Please try again.';
                        removeError.style.display = 'block';
                    }
                });
            });
        }
    }());