(function() {
    'use strict';

    function createElement(tagName, attrs, html) {
        var el = document.createElement(tagName);
        if (attrs) {
            Object.keys(attrs).forEach(function(k) { el.setAttribute(k, attrs[k]); });
        }
        if (html !== undefined) {
            el.innerHTML = html;
        }
        return el;
    }

    function isValidHttpUrl(url) {
        try {
            var u = new URL(url);
            return u.protocol === 'http:' || u.protocol === 'https:';
        } catch (e) {
            return false;
        }
    }

    function absoluteUrl(src, base) {
        try {
            return new URL(src, base).href;
        } catch (e) {
            return src;
        }
    }

    function fetchRemoteViaWP(url) {
        return new Promise(function(resolve, reject) {
            try {
                if (!window.aiautotool_js_setting || !window.aiautotool_js_setting.ajax_url) {
                    reject(new Error('WP AJAX unavailable - aiautotool_js_setting not configured'));
                    return;
                }
                
                var form = new URLSearchParams();
                form.append('action', 'aiautotool_fetch_remote_content');
                form.append('url', url);
                form.append('security', window.aiautotool_js_setting.security || '');

                console.log('Fetching remote content via WP AJAX:', url);

                fetch(window.aiautotool_js_setting.ajax_url, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: form,
                    credentials: 'same-origin'
                })
                .then(function(r) {
                    if (!r.ok) {
                        throw new Error('HTTP error ' + r.status);
                    }
                    return r.json();
                })
                .then(function(j) {
                    console.log('WP AJAX response:', j);
                    
                    if (j && j.success) {
                        var html = (j.data && (j.data.html || j.data.content)) || j.html || j.content || '';
                        if (html && typeof html === 'string' && html.length > 0) {
                            console.log('Successfully fetched ' + html.length + ' characters via WP');
                            resolve(html);
                        } else {
                            reject(new Error('Empty content received from WP'));
                        }
                    } else {
                        var errorMsg = (j && j.data && j.data.message) || 'WP fetch failed';
                        reject(new Error(errorMsg));
                    }
                })
                .catch(function(err) {
                    console.warn('WP fetch error:', err);
                    reject(err);
                });
            } catch (e) {
                console.error('Exception in fetchRemoteViaWP:', e);
                reject(e);
            }
        });
    }

    function fetchRemoteViaJina(url) {
        return new Promise(function(resolve, reject) {
            try {
                var u = new URL(url);
                var mirror = 'https://r.jina.ai/' + u.protocol + '//' + u.host + u.pathname + (u.search || '');
                
                console.log('Fetching via Jina.ai mirror:', mirror);
                
                fetch(mirror, { 
                    method: 'GET',
                    headers: {
                        'Accept': 'text/plain, text/html, application/json, */*'
                    }
                })
                .then(function(r) {
                    if (!r.ok) {
                        throw new Error('Jina.ai returned HTTP ' + r.status);
                    }
                    return r.text();
                })
                .then(function(t) {
                    if (!t || t.length < 100) {
                        throw new Error('Jina.ai returned insufficient content');
                    }
                    
                    try {
                        // Try to extract markdown content from Jina.ai response
                        var match = t.match(/(?:^|\n)Markdown Content:\s*\n([\s\S]*)$/i);
                        if (match && match[1]) {
                            console.log('Successfully extracted markdown content from Jina.ai');
                            resolve(match[1].trim());
                            return;
                        }
                    } catch (e) {
                        console.warn('Could not extract markdown, using raw content', e);
                    }
                    
                    console.log('Successfully fetched ' + t.length + ' characters via Jina.ai');
                    resolve(t);
                })
                .catch(function(e) {
                    console.warn('Jina.ai fetch error:', e);
                    reject(e);
                });
            } catch (e) {
                console.error('Exception in fetchRemoteViaJina:', e);
                reject(e);
            }
        });
    }

    function fetchRemoteContent(url) {
        console.log('Starting remote content fetch for:', url);
        
        // Try WP AJAX first, fallback to Jina.ai if it fails
        return fetchRemoteViaWP(url).catch(function(wpError) {
            console.warn('WP fetch failed, trying Jina.ai fallback:', wpError);
            return fetchRemoteViaJina(url).catch(function(jinaError) {
                console.error('Both WP and Jina.ai fetch failed');
                throw new Error('Failed to fetch content via both methods. WP: ' + wpError.message + ', Jina: ' + jinaError.message);
            });
        });
    }

    function extractLinearContent(html, pageUrl) {
        var parser = new DOMParser();
        var doc;
        try {
            doc = parser.parseFromString(html, 'text/html');
        } catch (e) {
            return { combined: html, images: {}, order: [] };
        }

        var body = doc.body || doc;
        var imgMap = {};
        var order = [];
        var imgIndex = 0;
        var textBuffer = [];

        function flushText() {
            if (textBuffer.length === 0) return;
            order.push({ type: 'text', content: textBuffer.join(' ').replace(/\s+/g, ' ').trim() });
            textBuffer = [];
        }

        function walk(node) {
            if (!node) return;
            var name = node.nodeName ? node.nodeName.toLowerCase() : '';
            if (name === 'script' || name === 'style' || name === 'noscript' || name === 'iframe') return;

            if (node.nodeType === Node.TEXT_NODE) {
                var val = (node.nodeValue || '').replace(/\s+/g, ' ').trim();
                if (val) textBuffer.push(val);
                return;
            }

            if (name === 'img') {
                var src = node.getAttribute('src') || '';
                if (src) {
                    flushText();
                    imgIndex += 1;
                    var key = '[[Image ' + imgIndex + ']]';
                    var abs = absoluteUrl(src, pageUrl);
                    var alt = node.getAttribute('alt') || '';
                    var imgHtml = '<img src="' + abs + '" alt="' + alt.replace(/"/g, '&quot;') + '" style="max-width:100%;height:auto;" />';
                    imgMap[key] = imgHtml;
                    order.push({ type: 'img', token: key });
                }
                return;
            }

            if (name === 'br' || name === 'p' || name === 'div' || name === 'section' || name === 'article' || name === 'li' || /^h[1-6]$/.test(name)) {
                if (name !== 'br') flushText();
            }

            var child = node.firstChild;
            while (child) { walk(child); child = child.nextSibling; }

            if (name === 'p' || name === 'div' || name === 'section' || name === 'article' || name === 'li' || /^h[1-6]$/.test(name)) {
                flushText();
            }
        }

        walk(body);
        flushText();

        var combinedParts = [];
        order.forEach(function(item) {
            if (item.type === 'text') {
                combinedParts.push(item.content);
            } else if (item.type === 'img') {
                combinedParts.push(item.token);
            }
        });
        var combined = combinedParts.join('\n\n').trim();
        return { combined: combined, images: imgMap, order: order };
    }

    function escapeHtml(str) {
        return String(str || '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }

    function markdownToHtml(md) {
        if (!md) return '';
        var text = String(md);

        // Extract fenced code blocks to placeholders
        var codeBlocks = [];
        text = text.replace(/```([\s\S]*?)```/g, function(_, code) {
            var idx = codeBlocks.length;
            codeBlocks.push('<pre><code>' + escapeHtml(code.trim()) + '</code></pre>');
            return '[[[CODEBLOCK_' + idx + ']]]';
        });

        // Escape remaining HTML
        text = escapeHtml(text);

        // Headings
        text = text.replace(/^######\s+(.*)$/gm, '<h6>$1</h6>')
                   .replace(/^#####\s+(.*)$/gm, '<h5>$1</h5>')
                   .replace(/^####\s+(.*)$/gm, '<h4>$1</h4>')
                   .replace(/^###\s+(.*)$/gm, '<h3>$1</h3>')
                   .replace(/^##\s+(.*)$/gm, '<h2>$1</h2>')
                   .replace(/^#\s+(.*)$/gm, '<h1>$1</h1>');

        // Blockquotes
        text = text.replace(/^>\s?(.*)$/gm, '<blockquote>$1</blockquote>');

        // Images ![alt](url)
        text = text.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, function(_, alt, src) {
            return '<img src="' + src + '" alt="' + alt + '" style="max-width:100%;height:auto;" />';
        });

        // Links [text](url)
        text = text.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, '<a href="$2" target="_blank" rel="nofollow noopener">$1</a>');

        // Bold and Italic
        text = text.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
                   .replace(/__([^_]+)__/g, '<strong>$1</strong>')
                   .replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, '<em>$1</em>')
                   .replace(/(?<!_)_([^_]+)_(?!_)/g, '<em>$1</em>');

        // Inline code
        text = text.replace(/`([^`]+)`/g, function(_, code) { return '<code>' + code + '</code>'; });

        // Lists (unordered)
        text = text.replace(/(?:^|\n)([\t ]*)(?:[-+*])\s+(.+)(?:\n\1(?:[-+*])\s+.+)*/g, function(list) {
            var items = list.trim().split(/\n/).map(function(line) {
                return line.replace(/^[\t ]*[-+*]\s+(.+)$/, '<li>$1</li>');
            }).join('');
            return '\n<ul>' + items + '</ul>';
        });

        // Lists (ordered)
        text = text.replace(/(?:^|\n)([\t ]*)\d+\.\s+(.+)(?:\n\1\d+\.\s+.+)*/g, function(list) {
            var items = list.trim().split(/\n/).map(function(line) {
                return line.replace(/^[\t ]*\d+\.\s+(.+)$/, '<li>$1</li>');
            }).join('');
            return '\n<ol>' + items + '</ol>';
        });

        // Restore code blocks
        text = text.replace(/\[\[\[CODEBLOCK_(\d+)\]\]\]/g, function(_, i) { return codeBlocks[Number(i)] || ''; });

        // Paragraphs: split on blank lines; keep block elements intact
        var blocks = text.split(/\n{2,}/).map(function(block) { return block.trim(); }).filter(Boolean);
        var htmlParts = blocks.map(function(block) {
            if (/^<(h[1-6]|ul|ol|pre|blockquote|img|p)\b/i.test(block)) return block;
            return '<p>' + block.replace(/\n/g, '<br>') + '</p>';
        });
        return htmlParts.join('\n');
    }

    function stripAnchorsFromText(text) {
        var s = String(text || '');
        try {
            // Remove HTML anchors but keep inner text or images
            s = s.replace(/<a\b[^>]*>([\s\S]*?)<\/a>/gi, '$1');
        } catch (e) {}
        try {
            // Inline Markdown links [text](url) -> text (do not touch images ![...](...))
            s = s.replace(/(^|[^!])\[([^\]]+)\]\((?:[^)\s]+)(?:\s+"[^"]+")?\)/g, '$1$2');
        } catch (e) {}
        try {
            // Reference-style Markdown links [text][id] or [text][] -> text (do not touch images)
            s = s.replace(/(^|[^!])\[([^\]]+)\]\s*\[([^\]]*)\]/g, '$1$2');
        } catch (e) {}
        try {
            // Markdown autolinks <http://...> -> http://...
            s = s.replace(/<([a-z][a-z0-9+.-]*:\/\/[^>\s]+)>/gi, '$1');
        } catch (e) {}
        return s;
    }

    function buildFinalHtmlFromAI(aiText, imagesMap) {
        var text = (aiText || '').toString();
        var html = markdownToHtml(text);
        html = html.replace(/\[\[Image\s+\d+\]\]/g, function(tok) {
            return imagesMap[tok] || '';
        });
        return html;
    }

    function resolveLang() {
        try {
            var post_language = (typeof window.get_lang === 'function') ? window.get_lang() : 'en';
            if (typeof window.languageCodes !== 'undefined' && window.languageCodes.hasOwnProperty(post_language)) {
                return window.languageCodes[post_language];
            }
            if (typeof window.langcheck !== 'undefined' && window.langcheck) return window.langcheck;
            return post_language || 'en';
        } catch (e) { return 'en'; }
    }

    function insertHtmlToEditor(html) {
        try {
            if (typeof tinymce !== 'undefined' && tinymce.activeEditor) {
                tinymce.activeEditor.setContent(html);
                return true;
            }
            var area = document.getElementById('content');
            if (area) { area.value = html; return true; }
            if (typeof wp !== 'undefined' && wp.data && wp.data.dispatch) {
                wp.data.dispatch('core/editor').editPost({ content: html });
                return true;
            }
        } catch (e) {}
        return false;
    }

    function showModal(contentHtml) {
        var wrapper = createElement('div', { id: 'remote-rewrite-modal', style: 'position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:999999;display:flex;align-items:center;justify-content:center;' });
        var inner = createElement('div', { style: 'background:#fff;border-radius:10px;max-width:95%;width:95%;max-height:85vh;overflow:hidden;box-shadow:0 10px 30px rgba(0,0,0,.2);' });
        inner.innerHTML = contentHtml;
        wrapper.appendChild(inner);
        document.body.appendChild(wrapper);
        return wrapper;
    }

    function closeModalByEl(modalEl) {
        try { if (modalEl && modalEl.parentNode) modalEl.parentNode.removeChild(modalEl); } catch (e) {}
    }

    function showInputModal() {
        // Inject improved CSS for modal if not already present
        if (!document.getElementById('rr-modal-style')) {
            var style = document.createElement('style');
            style.id = 'rr-modal-style';
            style.innerHTML = `
                #remote-rewrite-modal .rr-header {
                    padding: 24px 28px 0 28px;
                    border-bottom: 1px solid #e5e7eb;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    background: linear-gradient(90deg, #f8fafc 0%, #f1f5f9 100%);
                }
                #remote-rewrite-modal .rr-title {
                    margin: 0;
                    font-size: 22px;
                    color: #1e293b;
                    font-weight: 700;
                    letter-spacing: -0.5px;
                }
                #remote-rewrite-modal .rr-close-btn {
                    border: none;
                    background: #f3f4f6;
                    border-radius: 50%;
                    width: 36px;
                    height: 36px;
                    cursor: pointer;
                    font-size: 22px;
                    line-height: 36px;
                    color: #64748b;
                    transition: background 0.2s, color 0.2s;
                }
                #remote-rewrite-modal .rr-close-btn:hover {
                    background: #e0e7ef;
                    color: #1e293b;
                }
                #remote-rewrite-modal .rr-body {
                    padding: 28px;
                    gap: 18px;
                    display: flex;
                    flex-direction: column;
                    background: #f8fafc;
                }
                #remote-rewrite-modal label {
                    font-weight: 600;
                    color: #334155;
                    font-size: 15px;
                    margin-bottom: 4px;
                }
                #remote-rewrite-modal input#rr-url {
                    padding: 12px 14px;
                    border: 1.5px solid #cbd5e1;
                    border-radius: 10px;
                    font-size: 15px;
                    background: #fff;
                    transition: border 0.2s;
                }
                #remote-rewrite-modal input#rr-url:focus {
                    border-color: #2563eb;
                    outline: none;
                }
                #remote-rewrite-modal #rr-error {
                    display: none;
                    color: #b91c1c;
                    background: #fee2e2;
                    border: 1.5px solid #fecaca;
                    padding: 12px;
                    border-radius: 8px;
                    font-size: 14px;
                    margin-top: 2px;
                }
                #remote-rewrite-modal #rr-fetch {
                    align-self: flex-start;
                    background: linear-gradient(90deg, #2563eb 60%, #1d4ed8 100%);
                    color: #fff;
                    border: none;
                    border-radius: 10px;
                    padding: 12px 20px;
                    font-weight: 700;
                    font-size: 15px;
                    cursor: pointer;
                    box-shadow: 0 2px 8px rgba(37,99,235,0.07);
                    transition: background 0.2s, box-shadow 0.2s;
                }
                #remote-rewrite-modal #rr-fetch:disabled {
                    background: #a5b4fc;
                    cursor: not-allowed;
                }
                #remote-rewrite-modal #rr-fetch.loading::after {
                    content: '';
                    display: inline-block;
                    width: 16px;
                    height: 16px;
                    margin-left: 8px;
                    border: 2px solid rgba(255,255,255,0.6);
                    border-top-color: #fff;
                    border-radius: 50%;
                    animation: rr-spin .8s linear infinite;
                    vertical-align: -3px;
                }
                #remote-rewrite-modal #rr-progress {
                    display: none;
                    padding: 0 28px 28px 28px;
                    color: #475569;
                    background: #f1f5f9;
                }
                #remote-rewrite-modal .progress-container {
                    margin-top: 8px;
                }
                #remote-rewrite-modal .progress-bar {
                    background: #e0e7ef;
                    border-radius: 8px;
                    overflow: hidden;
                    height: 10px;
                    margin-bottom: 10px;
                }
                #remote-rewrite-modal .progress-fill {
                    width: 0%;
                    height: 10px;
                    background: linear-gradient(90deg, #3b82f6 60%, #2563eb 100%);
                    transition: width .3s;
                }
                #remote-rewrite-modal .progress-text {
                    margin-top: 8px;
                    font-size: 14px;
                    color: #334155;
                    font-weight: 500;
                }
                #remote-rewrite-modal .progress-steps {
                    margin-top: 14px;
                    display: flex;
                    flex-direction: column;
                    gap: 12px;
                }
                #remote-rewrite-modal .step {
                    display: flex;
                    gap: 14px;
                    align-items: flex-start;
                    opacity: 0.85;
                    transition: opacity 0.2s;
                }
                #remote-rewrite-modal .step.active {
                    opacity: 1;
                }
                #remote-rewrite-modal .step.completed .step-icon {
                    background: linear-gradient(90deg, #10b981 60%, #059669 100%) !important;
                    color: #fff !important;
                }
                #remote-rewrite-modal .step.active .step-icon {
                    background: linear-gradient(90deg, #3b82f6 60%, #2563eb 100%) !important;
                    color: #fff !important;
                }
                #remote-rewrite-modal .step-icon {
                    width: 26px;
                    height: 26px;
                    border-radius: 50%;
                    background: #e5e7eb;
                    color: #64748b;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 14px;
                    font-weight: 700;
                    box-shadow: 0 1px 2px rgba(0,0,0,0.04);
                    transition: background 0.2s, color 0.2s;
                }
                #remote-rewrite-modal .step-content {
                    display: flex;
                    flex-direction: column;
                }
                #remote-rewrite-modal .step-title {
                    font-weight: 700;
                    color: #1e293b;
                    font-size: 15px;
                }
                #remote-rewrite-modal .step-description {
                    font-size: 13px;
                    color: #64748b;
                }
                #remote-rewrite-modal #rr-result {
                    display: none;
                    padding: 0 28px 0px 28px;
                    max-height: 55vh;
                    overflow: auto;
                    border-top: 1.5px solid #e5e7eb;
                    background: #f8fafc;
                }
                #remote-rewrite-modal .rr-columns {
                    margin-top: 16px;
                    display: grid;
                    grid-template-columns: 1fr 1fr;
                    gap: 16px;
                }
                #remote-rewrite-modal .rr-col {
                    display: flex;
                    flex-direction: column;
                    gap: 10px;
                }
                #remote-rewrite-modal .rr-col-title {
                    font-weight: 800;
                    color: #0f172a;
                    font-size: 14px;
                    text-transform: uppercase;
                    letter-spacing: 0.4px;
                    opacity: 0.75;
                }
                #remote-rewrite-modal #rr-html {
                    border: 1.5px solid #e5e7eb;
                    border-radius: 10px;
                    padding: 16px;
                    background: #fff;
                    font-size: 15px;
                    color: #334155;
                    font-family: 'Inter', 'Segoe UI', Arial, sans-serif;
                    word-break: break-word;
                }
                #remote-rewrite-modal #rr-html-original,
                #remote-rewrite-modal #rr-html-rewritten {
                    border: 1.5px solid #e5e7eb;
                    border-radius: 10px;
                    padding: 16px;
                    background: #fff;
                    font-size: 15px;
                    color: #334155;
                    font-family: 'Inter', 'Segoe UI', Arial, sans-serif;
                    word-break: break-word;
                    min-height: 120px;
                }
                @media (max-width: 900px) {
                    #remote-rewrite-modal .rr-columns {
                        grid-template-columns: 1fr;
                    }
                }
                #remote-rewrite-modal .rr-actions {
                    margin-top: 16px;
                    display: flex;
                    gap: 12px;
                    position: sticky;
                    bottom: 0;
                    background: #f8fafc;
                    padding-top: 12px;
                    padding-bottom: 12px;
                    border-top: 1.5px solid #e5e7eb;
                    z-index: 2;
                }
                #remote-rewrite-modal #rr-insert {
                    background: linear-gradient(90deg, #10b981 60%, #059669 100%);
                    color: #fff;
                    border: none;
                    border-radius: 10px;
                    padding: 12px 20px;
                    font-weight: 700;
                    font-size: 15px;
                    cursor: pointer;
                    box-shadow: 0 2px 8px rgba(16,185,129,0.07);
                    transition: background 0.2s, box-shadow 0.2s;
                }
                #remote-rewrite-modal #rr-insert:hover {
                    background: linear-gradient(90deg, #059669 60%, #10b981 100%);
                }
                #remote-rewrite-modal #rr-close2 {
                    background: #e5e7eb;
                    color: #1e293b;
                    border: none;
                    border-radius: 10px;
                    padding: 12px 20px;
                    font-weight: 700;
                    font-size: 15px;
                    cursor: pointer;
                    transition: background 0.2s, color 0.2s;
                }
                #remote-rewrite-modal #rr-close2:hover {
                    background: #cbd5e1;
                    color: #0f172a;
                }
                @media (max-width: 600px) {
                    #remote-rewrite-modal .rr-header,
                    #remote-rewrite-modal .rr-body,
                    #remote-rewrite-modal #rr-progress,
                    #remote-rewrite-modal #rr-result {
                        padding-left: 10px !important;
                        padding-right: 10px !important;
                    }
                    #remote-rewrite-modal .rr-title {
                        font-size: 17px;
                    }
                }

                /* Enhancements */
                #remote-rewrite-modal {
                    -webkit-backdrop-filter: blur(3px);
                    backdrop-filter: blur(3px);
                    animation: rr-fade-in 160ms ease-out;
                }
                #remote-rewrite-modal > div {
                    animation: rr-pop-in 220ms cubic-bezier(.18,.89,.32,1.28);
                }
                #remote-rewrite-modal .rr-close-btn:focus-visible,
                #remote-rewrite-modal #rr-fetch:focus-visible,
                #remote-rewrite-modal #rr-insert:focus-visible,
                #remote-rewrite-modal #rr-close2:focus-visible,
                #remote-rewrite-modal input#rr-url:focus-visible {
                    outline: 3px solid rgba(37,99,235,0.35);
                    outline-offset: 2px;
                }
                #remote-rewrite-modal #rr-fetch:hover {
                    box-shadow: 0 6px 16px rgba(37,99,235,0.15);
                    filter: saturate(1.05);
                }
                #remote-rewrite-modal .progress-bar {
                    position: relative;
                }
                #remote-rewrite-modal .progress-fill {
                    background-image: linear-gradient(90deg, rgba(59,130,246,0.9), rgba(37,99,235,0.95)),
                                      linear-gradient(45deg, rgba(255,255,255,.25) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.25) 50%, rgba(255,255,255,.25) 75%, transparent 75%, transparent);
                    background-size: auto, 18px 18px;
                    background-blend-mode: overlay;
                    animation: rr-shimmer 1.2s linear infinite;
                }
                #remote-rewrite-modal .progress-steps {
                    position: relative;
                }
                #remote-rewrite-modal .step {
                    position: relative;
                }
                #remote-rewrite-modal .step::after {
                    content: '';
                    position: absolute;
                    left: 13px;
                    top: 28px;
                    bottom: -14px;
                    width: 2px;
                    background: #e5e7eb;
                }
                #remote-rewrite-modal .step:last-child::after {
                    display: none;
                }
                #remote-rewrite-modal .step-icon {
                    transition: transform .18s ease, box-shadow .18s ease, background .2s ease, color .2s ease;
                }
                #remote-rewrite-modal .step.active .step-icon {
                    transform: scale(1.08);
                    box-shadow: 0 4px 12px rgba(37,99,235,0.25);
                }
                #remote-rewrite-modal .step.completed .step-icon {
                    color: transparent !important;
                    position: relative;
                }
                #remote-rewrite-modal .step.completed .step-icon::after {
                    content: '\\2713';
                    position: absolute;
                    inset: 0;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: #fff;
                    font-weight: 900;
                    font-size: 15px;
                }

                @keyframes rr-fade-in {
                    from { opacity: 0; }
                    to { opacity: 1; }
                }
                @keyframes rr-pop-in {
                    from { transform: translateY(6px) scale(0.98); opacity: 0; }
                    to { transform: translateY(0) scale(1); opacity: 1; }
                }
                @keyframes rr-shimmer {
                    from { background-position: 0 0, 0 0; }
                    to { background-position: 0 0, 18px 0; }
                }
                @keyframes rr-spin {
                    from { transform: rotate(0deg); }
                    to { transform: rotate(360deg); }
                }
            `;
            document.head.appendChild(style);
        }

        var html = '' +
        '<div class="rr-header">' +
            '<h3 class="rr-title">Remote Content & Rewrite</h3>' +
            '<button id="rr-close" class="rr-close-btn" title="Close">&times;</button>' +
        '</div>' +
        '<div class="rr-body">' +
            '<label for="rr-url">Article URL</label>' +
            '<input id="rr-url" type="text" placeholder="https://example.com/article" autocomplete="off" />' +
            '<div id="rr-error"></div>' +
            '<button id="rr-fetch">Fetch & Rewrite</button>' +
        '</div>' +
        '<div id="rr-progress">' +
            '<div class="progress-container">' +
                '<div class="progress-bar">' +
                    '<div class="progress-fill" id="rr-progress-fill"></div>' +
                '</div>' +
                '<div class="progress-text" id="rr-progress-text">Initializing...</div>' +
                '<div class="progress-steps">' +
                    '<div class="step" id="rr-step-1">' +
                        '<div class="step-icon">1</div>' +
                        '<div class="step-content">' +
                            '<div class="step-title">Fetching</div>' +
                            '<div class="step-description">Getting remote content</div>' +
                        '</div>' +
                    '</div>' +
                    '<div class="step" id="rr-step-2">' +
                        '<div class="step-icon">2</div>' +
                        '<div class="step-content">' +
                            '<div class="step-title">Extracting</div>' +
                            '<div class="step-description">Parsing text and images</div>' +
                        '</div>' +
                    '</div>' +
                    '<div class="step" id="rr-step-3">' +
                        '<div class="step-icon">3</div>' +
                        '<div class="step-content">' +
                            '<div class="step-title">Rewriting</div>' +
                            '<div class="step-description">Improving clarity with AI</div>' +
                        '</div>' +
                    '</div>' +
                    '<div class="step" id="rr-step-4">' +
                        '<div class="step-icon">4</div>' +
                        '<div class="step-content">' +
                            '<div class="step-title">Finalizing</div>' +
                            '<div class="step-description">Building final HTML</div>' +
                        '</div>' +
                    '</div>' +
                '</div>' +
            '</div>' +
        '</div>' +
        '<div id="rr-result">' +
           '<div class="rr-columns">' +
               '<div class="rr-col">' +
                   '<div class="rr-col-title">Original</div>' +
                   '<div id="rr-html-original"></div>' +
               '</div>' +
               '<div class="rr-col">' +
                   '<div class="rr-col-title">Rewritten</div>' +
                   '<div id="rr-html-rewritten"></div>' +
               '</div>' +
           '</div>' +
            '<div class="rr-actions">' +
                '<button id="rr-insert">Insert to Editor</button>' +
                '<button id="rr-close2">Close</button>' +
            '</div>' +
        '</div>';

        var modal = showModal(html);
        var input = modal.querySelector('#rr-url');
        var btn = modal.querySelector('#rr-fetch');
        var closeBtn = modal.querySelector('#rr-close');
        var closeBtn2 = modal.querySelector('#rr-close2');
        var err = modal.querySelector('#rr-error');
        var prog = modal.querySelector('#rr-progress');
        var resultWrap = modal.querySelector('#rr-result');
        var originalDiv = modal.querySelector('#rr-html-original');
        var rewrittenDiv = modal.querySelector('#rr-html-rewritten');
        var insertBtn = modal.querySelector('#rr-insert');
        var bodyWrap = modal.querySelector('.rr-body');
        var preparedOriginalHtml = '';

        function setError(msg) {
            err.textContent = msg || '';
            err.style.display = msg ? 'block' : 'none';
        }

        function rrActivateStep(stepIndex) {
            var steps = [1,2,3,4];
            steps.forEach(function(i){
                var el = modal.querySelector('#rr-step-' + i);
                if (!el) return;
                el.classList.remove('active','completed');
                if (i < stepIndex) {
                    el.classList.add('completed');
                } else if (i === stepIndex) {
                    el.classList.add('active');
                } else {
                }
            });
        }

        function rrSetProgress(stepIndex, text, percent) {
            try {
                if (prog) prog.style.display = 'block';
                var fill = modal.querySelector('#rr-progress-fill');
                var label = modal.querySelector('#rr-progress-text');
                if (fill && typeof percent === 'number') fill.style.width = Math.max(0, Math.min(100, percent)) + '%';
                if (label && text) label.textContent = text;
                rrActivateStep(stepIndex);
                if (typeof percent === 'number' && percent >= 100) {
                    rrActivateStep(stepIndex + 1);
                }
            } catch (e) {}
        }

        function rrResetProgress() {
            try {
                var fill = modal.querySelector('#rr-progress-fill');
                var label = modal.querySelector('#rr-progress-text');
                if (fill) fill.style.width = '0%';
                if (label) label.textContent = 'Initializing...';
                rrActivateStep(0);
                if (prog) prog.style.display = 'none';
            } catch (e) {}
        }

        function setLoading(loading, text) {
            btn.disabled = !!loading;
            btn.textContent = loading ? 'Processing...' : 'Fetch & Rewrite';
            btn.classList.toggle('loading', !!loading);
            if (typeof text === 'string' && text) {
                var label = modal.querySelector('#rr-progress-text');
                if (label) label.textContent = text;
            }
        }

        function onClose() { closeModalByEl(modal); }

        closeBtn.addEventListener('click', onClose);
        if (closeBtn2) closeBtn2.addEventListener('click', onClose);

        btn.addEventListener('click', function() {
            var url = (input.value || '').trim();
            setError('');
            if (!url) { setError('Please enter a URL.'); return; }
            if (!isValidHttpUrl(url)) { setError('Please enter a valid http(s) URL.'); return; }
            if (typeof window.check_aipost_premium === 'function' && !window.check_aipost_premium()) {
                if (typeof window.showPremiumError === 'function') window.showPremiumError(); else alert('Require PRO');
                return;
            }

            // Reset previous run state
            if (resultWrap) resultWrap.style.display = 'none';
            if (originalDiv) originalDiv.innerHTML = '';
            if (rewrittenDiv) rewrittenDiv.innerHTML = '';
            if (bodyWrap) bodyWrap.style.display = '';
            preparedOriginalHtml = '';
            rrResetProgress();

            setLoading(true, 'Fetching remote content...');
            rrSetProgress(1, 'Fetching remote content...', 20);
            fetchRemoteContent(url)
                .then(function(raw) {
                    setLoading(true, 'Extracting text and images...');
                    rrSetProgress(2, 'Extracting text and images...', 50);
                    var extraction = extractLinearContent(raw, url);
                    var combined = extraction.combined || '';
                    var images = extraction.images || {};

                    if (!combined) {
                        setLoading(false);
                        setError('Could not extract content from the provided URL.');
                        return;
                    }

                    // Prepare original HTML, but do not show the result view until completion
                    try {
                        preparedOriginalHtml = buildFinalHtmlFromAI(combined, images);
                    } catch (e) { preparedOriginalHtml = ''; }

                    var lang = resolveLang();
                    
                    // Improved prompt for better AI rewriting
                    var instr = '' +
                        'You are a professional content editor. Your task is to rewrite the following article to make it clearer, more engaging, and better structured while maintaining all the original information and meaning.\n\n' +
                        'IMPORTANT RULES:\n' +
                        '1. Keep the same language as the original text\n' +
                        '2. DO NOT add, remove, or modify placeholder tokens like [[Image 1]], [[Image 2]], etc. Keep them EXACTLY in the SAME positions\n' +
                        '3. Maintain all factual information from the original\n' +
                        '4. Improve readability and flow\n' +
                        '5. Use clear, concise language\n' +
                        '6. Output PLAIN TEXT ONLY (no HTML tags)\n' +
                        '7. Keep the same approximate length as the original\n\n' +
                        '=== ORIGINAL TEXT START ===\n' + stripAnchorsFromText(combined) + '\n=== ORIGINAL TEXT END ===\n\n' +
                        'Please provide the rewritten version now:';

                    setLoading(true, 'Rewriting content with AI...');
                    rrSetProgress(3, 'Rewriting content with AI...', 80);
                    
                    // Improved AI service call with retry logic
                    var maxRetries = 2;
                    var retryCount = 0;
                    
                    function attemptAIRewrite() {
                        var call = (typeof window.sendbardToServer === 'function')
                            ? window.sendbardToServer(instr, null, 'writemore', lang)
                            : Promise.reject(new Error('AI service unavailable - sendbardToServer function not found'));

                        return call.then(function(aiOut) {
                            // Validate AI output
                            var cleanAiText = (aiOut || '').toString().trim();
                            
                            if (!cleanAiText || cleanAiText.length < 50) {
                                throw new Error('AI returned empty or very short response');
                            }
                            
                            return cleanAiText;
                            
                        }).catch(function(err) {
                            retryCount++;
                            
                            if (retryCount <= maxRetries) {
                                console.warn('AI request failed (attempt ' + retryCount + '/' + maxRetries + '), retrying...', err);
                                rrSetProgress(3, 'Retrying AI request (attempt ' + retryCount + ')...', 80);
                                return new Promise(function(resolve) {
                                    setTimeout(function() {
                                        resolve(attemptAIRewrite());
                                    }, 1000 * retryCount); // Exponential backoff
                                });
                            } else {
                                throw err;
                            }
                        });
                    }

                    attemptAIRewrite().then(function(cleanAiText) {
                        setLoading(true, 'Building final HTML...');
                        rrSetProgress(4, 'Building final HTML...', 95);
                        
                        // Build final HTML from AI output
                        var finalHtml = buildFinalHtmlFromAI(cleanAiText, images);
                        
                        // Validate final HTML
                        if (!finalHtml || finalHtml.trim().length < 50) {
                            throw new Error('Failed to build proper HTML from AI response');
                        }
                        
                        // Display results
                        if (originalDiv) originalDiv.innerHTML = preparedOriginalHtml || buildFinalHtmlFromAI(combined, images);
                        if (rewrittenDiv) rewrittenDiv.innerHTML = finalHtml;
                        
                        rrSetProgress(4, 'Completed!', 100);
                        setLoading(false);
                        if (prog) prog.style.display = 'none';
                        if (bodyWrap) bodyWrap.style.display = 'none';
                        if (resultWrap) resultWrap.style.display = 'block';
                        
                    }).catch(function(err2) {
                        setLoading(false);
                        
                        // Enhanced error handling with fallback
                        var errorMsg = 'AI Rewriting Failed';
                        var errorDetails = '';
                        
                        if (err2 && err2.message) {
                            errorDetails = err2.message;
                        } else {
                            errorDetails = 'Unknown error occurred';
                        }
                        
                        // Show error in rewritten div
                        if (rewrittenDiv) {
                            rewrittenDiv.innerHTML = '' +
                                '<div style="padding:20px;background:#fee2e2;border:2px solid #ef4444;border-radius:8px;">' +
                                    '<h3 style="color:#b91c1c;margin-top:0;">' + errorMsg + '</h3>' +
                                    '<p style="color:#7f1d1d;margin:8px 0;">' + errorDetails + '</p>' +
                                    '<p style="color:#7f1d1d;margin:8px 0;"><strong>Possible solutions:</strong></p>' +
                                    '<ul style="color:#7f1d1d;margin:0;padding-left:20px;">' +
                                        '<li>Check your AI service connection</li>' +
                                        '<li>Verify your API quota/limits</li>' +
                                        '<li>Try with a shorter article</li>' +
                                        '<li>Wait a moment and try again</li>' +
                                    '</ul>' +
                                    '<div style="margin-top:16px;">' +
                                        '<strong>Original content is still available below.</strong>' +
                                    '</div>' +
                                '</div>';
                        }
                        
                        // Show original content as fallback
                        if (originalDiv) {
                            originalDiv.innerHTML = preparedOriginalHtml || buildFinalHtmlFromAI(combined, images);
                        }
                        
                        setError('AI Rewriting Failed: ' + errorDetails + '. Original content shown instead.');
                        rrSetProgress(4, 'Error occurred', 100);
                        
                        // Still show results so user can see original
                        if (bodyWrap) bodyWrap.style.display = 'none';
                        if (resultWrap) resultWrap.style.display = 'block';
                    });
                })
                .catch(function(e) {
                    setLoading(false);
                    setError('Fetch error: ' + (e && e.message ? e.message : 'Unknown error'));
                });
        });

        function rrAutoTriggerFromValue(val) {
            try {
                var v = (val || '').trim();
                if (!v) return;
                if (isValidHttpUrl(v) && !btn.disabled) {
                    input.value = v;
                    setError('');
                    btn.click();
                }
            } catch (e) {}
        }

        input.addEventListener('paste', function(e) {
            try {
                var data = (e.clipboardData || window.clipboardData);
                var text = data ? data.getData('text') : '';
                // Allow the paste to populate input, then trigger
                setTimeout(function() {
                    rrAutoTriggerFromValue(text || input.value);
                }, 0);
            } catch (err) {
                setTimeout(function() { rrAutoTriggerFromValue(input.value); }, 0);
            }
        });

        input.addEventListener('drop', function(e) {
            try {
                var dt = e.dataTransfer;
                var t = dt ? (dt.getData('text/uri-list') || dt.getData('text/plain')) : '';
                setTimeout(function() { rrAutoTriggerFromValue(t || input.value); }, 0);
            } catch (err) {}
        });

        insertBtn.addEventListener('click', function() {
            var html = (rewrittenDiv && rewrittenDiv.innerHTML) || '';
            if (!html) {
                if (typeof window.showError === 'function') window.showError('No content to insert.'); else alert('No content to insert.');
                return;
            }
            var ok = insertHtmlToEditor(html);
            if (ok) {
                if (typeof window.showSuccess === 'function') window.showSuccess('Inserted rewritten content to editor.');
                closeModalByEl(modal);
            } else {
                if (typeof window.showError === 'function') window.showError('Cannot find editor. Please copy manually.'); else alert('Cannot find editor.');
            }
        });

        setTimeout(function() { try { input.focus(); } catch (e) {} }, 100);
    }

    window.showRemoteRewriteModal = function showRemoteRewriteModal() {
        showInputModal();
    };
})(); 