/* ==================================================
   Nuclear Fancy Pants Edition™ — NUCLEAR+++
   File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/assets/js/amai-manual-post.js
   Description: JS for manual Facebook post compose page — three-step hard flow
   Last Edited: 2026-04-08
   ================================================== */

(function () {
    'use strict';

    // ── State ──
    var channel    = (typeof amaiManual !== 'undefined' && amaiManual.channel) ? amaiManual.channel : 'facebook';
    var isInstagram = channel === 'instagram';
    var isFeeling   = channel === 'facebook';
    var isX         = channel === 'x';
    var isTikTok    = channel === 'tiktok';
    var charLimit   = isInstagram ? 2200 : (isX ? 280 : 63206);
    var charLimitDisplay = isInstagram ? '2,200' : (isX ? '280' : '63,206');
    var warnAt      = isInstagram ? 2000 : (isX ? 260 : 60000);

    var state = {
        step:              1,
        content:           '',
        feeling:           '',
        feelingLabel:      '',
        attachmentId:      0,
        imageUrl:          '',
        imageCredit:       '',
        unsplashDownloadLocation: '',
        imageKeyword: '',
        tracked:           false,
    };

    // ── DOM refs ──
    var el = {
        step1:             document.getElementById('amai-step-1'),
        step2:             document.getElementById('amai-step-2'),
        step3:             document.getElementById('amai-step-3'),
        stepsIndicator:    document.getElementById('amai-manual-steps'),
        textarea:          document.getElementById('amai-post-content'),
        charCount:         document.getElementById('amai-char-count'),
        emojiBtn:          document.getElementById('amai-emoji-btn'),
        emojiDropdown:     document.getElementById('amai-emoji-dropdown'),
        emojiGrid:         document.getElementById('amai-emoji-grid'),
        emojiStickyCat:    document.getElementById('amai-emoji-sticky-cat'),
        feelingBtn:        document.getElementById('amai-feeling-btn'),
        feelingChip:       document.getElementById('amai-feeling-chip'),
        feelingChipLabel:  document.getElementById('amai-feeling-chip-label'),
        feelingChipRemove: document.getElementById('amai-feeling-chip-remove'),
        step1Next:         document.getElementById('amai-step1-next'),
        seedBtn:           document.getElementById('amai-seed-btn'),
        seedLabel:         document.getElementById('amai-seed-label'),
        seedSpinner:       document.getElementById('amai-seed-spinner'),
        unsplashSearching: document.getElementById('amai-unsplash-searching'),
        unsplashKeyword:   document.getElementById('amai-unsplash-keyword'),
        unsplashKeywordWrap: document.getElementById('amai-unsplash-keyword-wrap'),
        unsplashGrid:      document.getElementById('amai-unsplash-grid'),
        unsplashError:     document.getElementById('amai-unsplash-error'),
        selectedImgWrap:   document.getElementById('amai-selected-img-wrap'),
        selectedImg:       document.getElementById('amai-selected-img'),
        selectedCredit:    document.getElementById('amai-selected-credit'),
        removeImageBtn:    document.getElementById('amai-remove-image-btn'),
        imageActions:      document.getElementById('amai-image-actions'),
        mediaLibraryBtn:   document.getElementById('amai-media-library-btn'),
        fileInput:         document.getElementById('amai-file-input'),
        uploadStrip:       document.getElementById('amai-upload-strip'),
        step2Back:         document.getElementById('amai-step2-back'),
        aiImgBtn:          document.getElementById('amai-ai-img-btn'),
        aiImgPromptWrap:   document.getElementById('amai-ai-img-prompt-wrap'),
        aiImgPrompt:       document.getElementById('amai-ai-img-prompt'),
        aiImgCancel:       document.getElementById('amai-ai-img-cancel'),
        aiImgGenerate:     document.getElementById('amai-ai-img-generate'),
        aiImgGenerating:   document.getElementById('amai-ai-img-generating'),
        aiImgError:        document.getElementById('amai-ai-img-error'),
        step2Next:         document.getElementById('amai-step2-next'),
        previewContent:    document.getElementById('amai-preview-content'),
        previewFeeling:    document.getElementById('amai-preview-feeling'),
        previewImgWrap:    document.getElementById('amai-preview-img-wrap'),
        previewImg:        document.getElementById('amai-preview-img'),
        previewCredit:     document.getElementById('amai-preview-credit'),
        postError:         document.getElementById('amai-post-error'),
        postSuccess:       document.getElementById('amai-post-success'),
        postBtn:           document.getElementById('amai-post-btn'),
        step3Back:         document.getElementById('amai-step3-back'),
        feelingModal:      document.getElementById('amai-feeling-modal'),
        feelingModalClose: document.getElementById('amai-feeling-modal-close'),
        feelingModalGrid:  document.getElementById('amai-feeling-modal-grid'),
    };

    // ── Emoji data ──
    var EMOJI_CATS = [
        { cat: 'Smileys', emojis: ['😀','😃','😄','😁','😆','😅','🤣','😂','🙂','😊','😇','🥰','😍','🤩','😘','😗','😙','😚','😋','😛','😜','🤪','😝','🤑','🤗','🤭','🤫','🤔','🤐','🤨','😐','😑','😶','😏','😒','🙄','😬','🤥','😌','😔','😪','🤤','😴','😷','🤒','🤕','🥴','😵','🤯','🤠','🥳','😎','🤓','🧐'] },
        { cat: 'Gestures', emojis: ['👍','👎','👌','🤌','🤏','✌️','🤞','🤟','🤘','🤙','👈','👉','👆','👇','☝️','👋','🤚','🖐️','✋','🖖','👏','🙌','🤲','🤝','🙏','💪','🦾','🦿','🖕','✍️','💅','🤳'] },
        { cat: 'Hearts', emojis: ['❤️','🧡','💛','💚','💙','💜','🖤','🤍','🤎','💔','❣️','💕','💞','💓','💗','💖','💘','💝','💟','☮️','✝️','☯️','🕉️','☪️','🔯'] },
        { cat: 'Nature', emojis: ['🌸','🌺','🌻','🌹','🌷','🌼','💐','🍀','🌿','🌱','🌲','🌳','🌴','🍃','🍂','🍁','🌾','🍄','🌵','🎋','🎄','🌊','⭐','🌟','💫','✨','🌙','☀️','🌈','☁️','❄️','🔥','💧','🌍'] },
        { cat: 'Objects', emojis: ['🎉','🎊','🎈','🎁','🏆','🥇','🏅','🎯','🎪','🎨','🎭','🎬','🎤','🎧','🎵','🎶','📱','💻','📷','📸','💡','🔑','🔒','💰','💎','🚀','✈️','🌐','📌','📎','✏️','📝','📚','📖'] },
        { cat: 'Business', emojis: ['💼','📊','📈','📉','💹','🏦','🏢','📋','📁','📂','🗂️','📅','📆','🗓️','📇','📌','✅','☑️','❎','🔔','📣','📢','💬','💭','🗣️','👥','👤','🤝','💡','⚡','🎯','🔧','⚙️','🛠️'] },
    ];

    // ── Init ──
    function init() {
        if (!el.textarea) return;
        bindCharCount();
        bindEmoji();
        if (isFeeling) { bindFeeling(); }
        bindSeed();
        bindStep1();
        bindStep2();
        bindStep3();
        if (isFeeling) { bindFeelingModal(); }
        loadPrefill();
    }

    // ── Pre-fill from duplicate ──
    function loadPrefill() {
        try {
            var raw = sessionStorage.getItem('amai_compose_prefill');
            if (!raw) { return; }
            sessionStorage.removeItem('amai_compose_prefill');
            var data = JSON.parse(raw);
            if (data.content && el.textarea) {
                el.textarea.value = data.content;
                el.textarea.dispatchEvent(new Event('input'));
            }
        } catch (e) {}
    }

    // ── Char count ──
    function bindCharCount() {
        if (el.charCount) { el.charCount.style.visibility = 'hidden'; }
        el.textarea.addEventListener('input', function () {
            var len = el.textarea.value.length;
            if (len === 0) {
                if (el.charCount) { el.charCount.style.visibility = 'hidden'; }
                return;
            }
            if (el.charCount) { el.charCount.style.visibility = ''; }
            if (len > warnAt) {
                el.charCount.textContent = len + ' / ' + charLimitDisplay;
                el.charCount.style.color = '#ef4444';
            } else {
                el.charCount.textContent = len;
                el.charCount.style.color = '#A8A29E';
            }
        });
    }

    // ── Emoji picker ──
    function buildEmojiGrid() {
        if (el.emojiGrid.children.length > 0) return;
        EMOJI_CATS.forEach(function (cat) {
            el.emojiStickyCat.textContent = cat.cat;
            cat.emojis.forEach(function (emoji) {
                var btn = document.createElement('button');
                btn.type = 'button';
                btn.textContent = emoji;
                btn.addEventListener('click', function () {
                    insertAtCursor(el.textarea, emoji);
                    el.emojiDropdown.style.display = 'none';
                    el.textarea.dispatchEvent(new Event('input'));
                });
                el.emojiGrid.appendChild(btn);
            });
        });
        el.emojiStickyCat.textContent = EMOJI_CATS[0].cat;
    }

    function insertAtCursor(textarea, text) {
        var start = textarea.selectionStart;
        var end   = textarea.selectionEnd;
        var val   = textarea.value;
        textarea.value = val.substring(0, start) + text + val.substring(end);
        textarea.selectionStart = textarea.selectionEnd = start + text.length;
        textarea.focus();
    }

    function bindEmoji() {
        el.emojiBtn.addEventListener('click', function (e) {
            e.stopPropagation();
            buildEmojiGrid();
            var visible = el.emojiDropdown.style.display !== 'none';
            el.emojiDropdown.style.display = visible ? 'none' : 'flex';
        });
        document.addEventListener('click', function (e) {
            if (!el.emojiDropdown.contains(e.target) && e.target !== el.emojiBtn) {
                el.emojiDropdown.style.display = 'none';
            }
        });
    }

    // ── Feeling ──
    function bindFeeling() {
        if (!el.feelingBtn) return;
        el.feelingBtn.addEventListener('click', function () {
            openFeelingModal();
        });
        el.feelingChipRemove.addEventListener('click', function () {
            state.feeling      = '';
            state.feelingLabel = '';
            el.feelingChip.style.display = 'none';
        });
    }

    function bindFeelingModal() {
        el.feelingModalClose.addEventListener('click', closeFeelingModal);
        el.feelingModal.addEventListener('click', function (e) {
            if (e.target === el.feelingModal) closeFeelingModal();
        });
        var opts = el.feelingModalGrid.querySelectorAll('.amai-feeling-option');
        opts.forEach(function (opt) {
            opt.addEventListener('click', function () {
                state.feeling      = opt.getAttribute('data-feeling');
                state.feelingLabel = opt.textContent.trim();
                el.feelingChipLabel.textContent = state.feelingLabel;
                el.feelingChip.style.display = 'inline-flex';
                opts.forEach(function (o) { o.classList.remove('amai-feeling-option--selected'); });
                opt.classList.add('amai-feeling-option--selected');
                closeFeelingModal();
            });
        });
    }

    function openFeelingModal() {
        el.feelingModal.style.display = 'flex';
        document.body.style.overflow  = 'hidden';
    }

    function closeFeelingModal() {
        el.feelingModal.style.display = 'none';
        document.body.style.overflow  = '';
    }

    // ── AI seed ──
    function bindSeed() {
        if (!el.seedBtn) return;
        el.seedBtn.addEventListener('click', function () {
            if (el.seedLabel) { el.seedLabel.style.display = 'none'; el.seedLabel.textContent = ''; }
            state.imageKeyword = '';
            var postTypeEl = document.getElementById('amai-post-type');
            var postType   = postTypeEl ? postTypeEl.value : 'educational';
            el.seedBtn.disabled = true;
            if (el.seedSpinner) { el.seedSpinner.style.display = 'inline'; }
            el.seedBtn.textContent = 'Generating…';
            var data = new FormData();
            data.append('action',    'amai_generate_post_seed');
            data.append('_wpnonce', amaiManual.nonce);
            data.append('post_type', postType);
            data.append('channel',   channel);
            fetch(amaiManual.ajaxUrl, { method: 'POST', body: data })
                .then(function (r) { return r.json(); })
                .then(function (res) {
                    el.seedBtn.disabled = false;
                    if (el.seedSpinner) { el.seedSpinner.style.display = 'none'; }
                    el.seedBtn.textContent = '✨ Write with AI';
                    var typeLabels = {
                        educational: 'Educational', product: 'Product', feel_good: 'Feel Good',
                        behind_scenes: 'Behind the Scenes', engagement: 'Engagement',
                        quote: 'Quote', humor: 'Humor', myth_bust: 'Myth Bust', tip: 'Tip',
                        other: 'General'
                    };
                    if (res.success && res.data && res.data.post_content) {
                        el.textarea.value = res.data.post_content;
                        el.textarea.dispatchEvent(new Event('input'));
                        el.textarea.focus();
                        if (res.data.image_keyword) {
                            state.imageKeyword = res.data.image_keyword;
                        }
                        if (el.seedLabel) {
                            var labelParts = [];
                            if (state.imageKeyword) { labelParts.push('Image search: ' + state.imageKeyword); }
                            el.seedLabel.textContent = labelParts.length ? labelParts.join(' - ') : '';
                            el.seedLabel.style.display = labelParts.length ? 'inline-block' : 'none';
                        }
                    } else {
                        var msg = res.data && res.data.message ? res.data.message : 'Generation failed. Try again.';
                        el.seedBtn.textContent = msg;
                        setTimeout(function () { el.seedBtn.textContent = '✨ Write with AI'; }, 3000);
                    }
                })
                .catch(function () {
                    el.seedBtn.disabled = false;
                    if (el.seedSpinner) { el.seedSpinner.style.display = 'none'; }
                    el.seedBtn.textContent = 'Network error - try again';
                    setTimeout(function () { el.seedBtn.textContent = '✨ Write with AI'; }, 3000);
                });
        });
    }

    // ── Step 1 → 2 ──
    function bindStep1() {
        el.step1Next.addEventListener('click', function () {
            var content = el.textarea.value.trim();
            if (content === '') {
                el.textarea.focus();
                el.textarea.style.borderColor = '#ef4444';
                setTimeout(function () { el.textarea.style.borderColor = ''; }, 2000);
                return;
            }
            state.content = content;
            goToStep(2);
            runUnsplashSearch();
        });
    }

    // ── Step 2 ──
    function bindStep2() {
        bindAiImageGenerate();
        el.step2Back.addEventListener('click', function () { goToStep(1); });
        el.step2Next.addEventListener('click', function () {
            if (isInstagram && !state.imageUrl && state.attachmentId === 0) {
                var err = el.unsplashError;
                if (err) {
                    err.textContent   = 'Instagram requires an image. Please select or upload one.';
                    err.style.display = 'block';
                }
                return;
            }
            goToStep(3);
            buildPreview();
        });

        // Media library picker
        el.mediaLibraryBtn.addEventListener('click', function () {
            var frame = wp.media({
                title:    'Choose Image',
                button:   { text: 'Use this image' },
                multiple: false,
                library:  { type: 'image' },
            });
            frame.on('select', function () {
                var attachment = frame.state().get('selection').first().toJSON();
                state.attachmentId           = attachment.id;
                state.imageUrl               = attachment.url;
                state.imageCredit            = '';
                state.unsplashDownloadLocation = '';
                state.tracked                = false;
                clearUnsplashSelection();
                showSelectedImage(attachment.url, '');
            });
            frame.open();
        });

        // File upload (unused — media library covers this, but kept for future)
        el.fileInput.addEventListener('change', function () {
            if (!el.fileInput.files.length) return;
            var file = el.fileInput.files[0];
            uploadFile(file);
            el.fileInput.value = '';
        });

        el.removeImageBtn.addEventListener('click', function () {
            clearImage();
        });
    }

    function runUnsplashSearch() {
        el.unsplashSearching.style.display = 'flex';
        el.unsplashGrid.innerHTML          = '';
        el.unsplashError.style.display     = 'none';
        el.unsplashKeywordWrap.style.display = 'none';

        var data = new FormData();
        data.append('action',       'amai_manual_unsplash_search');
        data.append('_wpnonce',     amaiManual.nonce);
        if (state.imageKeyword) {
            data.append('keyword', state.imageKeyword);
        } else {
            data.append('post_content', state.content);
        }

        fetch(amaiManual.ajaxUrl, { method: 'POST', body: data })
            .then(function (r) { return r.json(); })
            .then(function (res) {
                el.unsplashSearching.style.display = 'none';
                if (!res.success) {
                    el.unsplashError.textContent   = res.data && res.data.message ? res.data.message : 'No images found.';
                    el.unsplashError.style.display = 'block';
                    return;
                }
                el.unsplashKeyword.textContent       = res.data.keywords;
                el.unsplashKeywordWrap.style.display = 'block';
                renderUnsplashGrid(res.data.photos);
            })
            .catch(function () {
                el.unsplashSearching.style.display = 'none';
                el.unsplashError.textContent       = 'Image search failed. You can skip and add an image later.';
                el.unsplashError.style.display     = 'block';
            });
    }

    function renderUnsplashGrid(photos) {
        el.unsplashGrid.innerHTML = '';
        photos.forEach(function (photo) {
            var item = document.createElement('div');
            item.className = 'amai-manual-unsplash-item';

            var img = document.createElement('img');
            img.src     = photo.thumb;
            img.alt     = 'Photo by ' + photo.photographer;
            img.loading = 'lazy';

            var check = document.createElement('div');
            check.className   = 'amai-manual-unsplash-item-check';
            check.textContent = '✓';

            var credit = document.createElement('div');
            credit.className   = 'amai-manual-unsplash-credit-overlay';
            credit.textContent = photo.photographer;

            item.appendChild(img);
            item.appendChild(check);
            item.appendChild(credit);

            item.addEventListener('click', function () {
                selectUnsplashPhoto(item, photo);
            });

            el.unsplashGrid.appendChild(item);
        });
    }

    function selectUnsplashPhoto(item, photo) {
        // Deselect all
        var items = el.unsplashGrid.querySelectorAll('.amai-manual-unsplash-item');
        items.forEach(function (i) { i.classList.remove('amai-manual-unsplash-item--selected'); });

        item.classList.add('amai-manual-unsplash-item--selected');

        state.attachmentId             = 0;
        state.imageUrl                 = photo.url;
        state.imageCredit              = photo.photographer;
        state.unsplashDownloadLocation = photo.download_location;
        state.tracked                  = false;

        // Track download (Unsplash API requirement)
        trackUnsplashDownload(photo.download_location);

        var creditText = photo.photographer
            ? 'Photo by <a href="' + photo.profile_url + '" target="_blank" rel="noopener">' + escHtml(photo.photographer) + '</a> on Unsplash'
            : '';

        showSelectedImage(photo.url, creditText);
    }

    function trackUnsplashDownload(download_location) {
        if (!download_location || state.tracked) return;
        state.tracked = true;
        var data = new FormData();
        data.append('action',            'amai_manual_unsplash_track');
        data.append('_wpnonce',          amaiManual.nonce);
        data.append('download_location', download_location);
        fetch(amaiManual.ajaxUrl, { method: 'POST', body: data }).catch(function () {});
    }

    function showSelectedImage(url, creditHtml) {
        el.selectedImg.src                      = url;
        el.selectedCredit.innerHTML             = creditHtml;
        el.selectedImgWrap.style.display        = 'block';
        el.imageActions.style.display           = 'none';
    }

    function clearUnsplashSelection() {
        var items = el.unsplashGrid.querySelectorAll('.amai-manual-unsplash-item');
        items.forEach(function (i) { i.classList.remove('amai-manual-unsplash-item--selected'); });
    }

    function clearImage() {
        state.attachmentId             = 0;
        state.imageUrl                 = '';
        state.imageCredit              = '';
        state.unsplashDownloadLocation = '';
        state.tracked                  = false;
        el.selectedImgWrap.style.display = 'none';
        el.imageActions.style.display    = 'flex';
        clearUnsplashSelection();
    }

    function uploadFile(file) {
        el.uploadStrip.style.display = 'flex';
        var formData = new FormData();
        formData.append('action',   'amai_manual_image_upload');
        formData.append('_wpnonce', amaiManual.nonce);
        formData.append('image',    file);

        fetch(amaiManual.ajaxUrl, { method: 'POST', body: formData })
            .then(function (r) { return r.json(); })
            .then(function (res) {
                el.uploadStrip.style.display = 'none';
                if (!res.success) {
                    showStep2Error(res.data && res.data.message ? res.data.message : 'Upload failed.');
                    return;
                }
                state.attachmentId             = res.data.attachment_id;
                state.imageUrl                 = res.data.url;
                state.imageCredit              = '';
                state.unsplashDownloadLocation = '';
                state.tracked                  = false;
                clearUnsplashSelection();
                showSelectedImage(res.data.url, '');
            })
            .catch(function () {
                el.uploadStrip.style.display = 'none';
                showStep2Error('Upload failed. Please try again.');
            });
    }

    function showStep2Error(msg) {
        el.unsplashError.textContent   = msg;
        el.unsplashError.style.display = 'block';
    }

    // ── Step 3 ──
    function bindAiImageGenerate() {
        if (!el.aiImgBtn) return;
        el.aiImgBtn.addEventListener('click', function () {
            el.aiImgPromptWrap.style.display = 'block';
            el.aiImgBtn.style.display = 'none';
        });
        if (el.aiImgCancel) {
            el.aiImgCancel.addEventListener('click', function () {
                el.aiImgPromptWrap.style.display = 'none';
                el.aiImgBtn.style.display = '';
                if (el.aiImgError) el.aiImgError.style.display = 'none';
            });
        }
        if (el.aiImgGenerate) {
            el.aiImgGenerate.addEventListener('click', function () {
                var prompt = el.aiImgPrompt ? el.aiImgPrompt.value.trim() : '';
                if (prompt === '') { return; }
                el.aiImgPromptWrap.style.display = 'none';
                el.aiImgGenerating.style.display = 'block';
                if (el.aiImgError) el.aiImgError.style.display = 'none';
                var formData = new FormData();
                formData.append('action',   'amai_compose_generate_image');
                formData.append('_wpnonce', amaiManual.nonce);
                formData.append('prompt',   prompt);
                fetch(amaiManual.ajaxUrl, { method: 'POST', body: formData })
                    .then(function (r) { return r.json(); })
                    .then(function (res) {
                        el.aiImgGenerating.style.display = 'none';
                        if (!res.success) {
                            if (el.aiImgError) {
                                el.aiImgError.textContent = res.data && res.data.message ? res.data.message : 'Image generation failed. Please try again.';
                                el.aiImgError.style.display = 'block';
                            }
                            el.aiImgPromptWrap.style.display = 'block';
                            return;
                        }
                        state.attachmentId             = 0;
                        state.imageUrl                 = res.data.url;
                        state.imageCredit              = '';
                        state.unsplashDownloadLocation = '';
                        state.tracked                  = false;
                        clearUnsplashSelection();
                        showSelectedImage(res.data.url, '');
                        el.aiImgBtn.style.display = '';
                        if (el.aiImgPrompt) el.aiImgPrompt.value = '';
                    })
                    .catch(function () {
                        el.aiImgGenerating.style.display = 'none';
                        if (el.aiImgError) {
                            el.aiImgError.textContent = 'Image generation failed. Please try again.';
                            el.aiImgError.style.display = 'block';
                        }
                        el.aiImgPromptWrap.style.display = 'block';
                    });
            });
        }
    }

    function bindStep3() {
        el.step3Back.addEventListener('click', function () { goToStep(2); });
        el.postBtn.addEventListener('click', function () { submitPost(); });
    }

    function buildPreview() {
        el.previewContent.textContent = state.content;

        if (el.previewFeeling) {
            if (state.feeling && state.feelingLabel) {
                el.previewFeeling.textContent   = 'Feeling ' + state.feelingLabel;
                el.previewFeeling.style.display = 'inline-block';
            } else {
                el.previewFeeling.style.display = 'none';
            }
        }

        if (state.imageUrl) {
            el.previewImg.src = state.imageUrl;
            if (state.imageCredit) {
                el.previewCredit.innerHTML = 'Photo by <a href="#" target="_blank" rel="noopener">' + escHtml(state.imageCredit) + '</a> on Unsplash';
            } else {
                el.previewCredit.innerHTML = '';
            }
            el.previewImgWrap.style.display = 'block';
        } else {
            el.previewImgWrap.style.display = 'none';
        }

        el.postError.style.display   = 'none';
        el.postSuccess.style.display = 'none';
        el.postBtn.disabled          = false;
    }

    function submitPost() {
        el.postBtn.disabled          = true;
        el.postError.style.display   = 'none';
        el.postSuccess.style.display = 'none';

        var btnText = el.postBtn.innerHTML;
        el.postBtn.innerHTML = '<svg class="amai-regen-spin" width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M12 2.5A5.5 5.5 0 1 0 13 7" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><path d="M10 2.5h2V.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg> Posting…';

        var data = new FormData();
        var postTypeEl = document.getElementById('amai-post-type');
        var postType   = (postTypeEl && !isInstagram) ? postTypeEl.value : 'other';
        data.append('action',        'amai_manual_post_now');
        data.append('channel',       channel);
        data.append('_wpnonce',      amaiManual.nonce);
        data.append('post_content',  state.content);
        data.append('feeling',       state.feeling);
        data.append('attachment_id', state.attachmentId);
        data.append('image_url',     state.imageUrl);
        data.append('post_type',     postType);

        fetch(amaiManual.ajaxUrl, { method: 'POST', body: data })
            .then(function (r) { return r.json(); })
            .then(function (res) {
                el.postBtn.innerHTML = btnText;
                if (!res.success) {
                    el.postError.textContent   = res.data && res.data.message ? res.data.message : 'Something went wrong. Please try again.';
                    el.postError.style.display = 'block';
                    el.postBtn.disabled        = false;
                    return;
                }
                el.postSuccess.style.display = 'flex';
                el.postBtn.style.display     = 'none';
                el.step3Back.style.display   = 'none';
                // Redirect to channel dashboard after 2s
                var dashUrl = window.location.href.replace(/[&?]tab=compose.*$/, '');
                setTimeout(function () {
                    window.location.href = dashUrl;
                }, 2000);
            })
            .catch(function () {
                el.postBtn.innerHTML  = btnText;
                el.postBtn.disabled   = false;
                el.postError.textContent   = 'Request failed. Please check your connection and try again.';
                el.postError.style.display = 'block';
            });
    }

    // ── Step navigation ──
    function goToStep(n) {
        state.step = n;
        el.step1.style.display = n === 1 ? 'block' : 'none';
        el.step2.style.display = n === 2 ? 'block' : 'none';
        el.step3.style.display = n === 3 ? 'block' : 'none';
        if (n === 2 && state.imageKeyword && el.aiImgPrompt && el.aiImgPrompt.value.trim() === '') {
            el.aiImgPrompt.value = 'Vibrant, professional photo featuring ' + state.imageKeyword + ', warm natural lighting, clean background, suitable for social media';
        }
        updateStepIndicator(n);
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    function updateStepIndicator(current) {
        var steps = el.stepsIndicator.querySelectorAll('.amai-manual-step');
        steps.forEach(function (s) {
            var n = parseInt(s.getAttribute('data-step'), 10);
            s.classList.remove('amai-manual-step--active', 'amai-manual-step--done');
            if (n < current) s.classList.add('amai-manual-step--done');
            if (n === current) s.classList.add('amai-manual-step--active');
        });
    }

    // ── Reset ──
    function resetAll() {
        state.content                  = '';
        state.feeling                  = '';
        state.feelingLabel             = '';
        state.attachmentId             = 0;
        state.imageUrl                 = '';
        state.imageCredit              = '';
        state.unsplashDownloadLocation = '';
        state.tracked                  = false;

        el.textarea.value              = '';
        el.charCount.textContent       = '0';
        el.charCount.style.visibility  = 'hidden';
        el.feelingChip.style.display   = 'none';
        el.unsplashGrid.innerHTML      = '';
        el.unsplashError.style.display = 'none';
        el.unsplashKeywordWrap.style.display = 'none';
        el.selectedImgWrap.style.display     = 'none';
        el.imageActions.style.display        = 'flex';
        el.postSuccess.style.display         = 'none';
        el.postError.style.display           = 'none';
        el.postBtn.style.display             = 'inline-flex';
        el.postBtn.disabled                  = false;
        el.step3Back.style.display           = 'inline-flex';
    }

    // ── Helpers ──
    function escHtml(str) {
        return str
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }

    // ── Boot ──
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

}());