<!DOCTYPE html>
{% set _admin_lang = get_admin_language() %}
<html lang="{{ _admin_lang }}" dir="{{ 'rtl' if _admin_lang in ('ar', 'he') else 'ltr' }}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    {%- if settings.get('webmcp_admin_enabled', 'false') == 'true' and settings.get('webmcp_origin_trial_token', '') %}
    <meta http-equiv="origin-trial" content="{{ settings.get('webmcp_origin_trial_token') }}">
    {%- endif %}
    <title>{% block title %}{{ t('sidebar.dashboard') }}{% endblock %} - AliothPress</title>
    <link rel="stylesheet" href="{{ static_v('css/admin.css') }}">
    {# AdminDialog: themed alert/confirm/prompt used by page scripts and
       data-confirm attributes everywhere — must load before any of them,
       hence the head. Registers only functions + delegated listeners. #}
    <script>window.AdminDialogI18N = { ok: {{ t('aeditor.ok')|tojson }}, cancel: {{ t('common.cancel')|tojson }} };</script>
    <script src="{{ static_v('js/admin-dialog.js') }}"></script>
    {% block extra_css %}{% endblock %}
</head>
<body data-theme="{{ demo_pref_theme or current_user.admin_theme or 'light' }}">
    <script>
    (function(){
        var t = document.body.getAttribute('data-theme');
        if (t === 'system') {
            document.body.setAttribute('data-theme', 
                window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
            window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function(e) {
                document.body.setAttribute('data-theme', e.matches ? 'dark' : 'light');
            });
        }
    })();
    </script>
    <div class="admin-container">
        <!-- Hamburger toggle (mobile) -->
        <button class="sidebar-toggle" aria-label="Toggle menu" onclick="document.querySelector('.sidebar').classList.toggle('is-open'); document.querySelector('.sidebar-overlay').classList.toggle('is-open');">☰</button>
        <!-- Overlay for closing sidebar on outside click -->
        <div class="sidebar-overlay" onclick="document.querySelector('.sidebar').classList.remove('is-open'); this.classList.remove('is-open');"></div>
        <!-- Sidebar -->
        <aside class="sidebar">
            <div class="sidebar-header">
                <h1><img src="{{ url_for('static', filename='img/admin-star.png') }}" alt="" width="32" height="32" class="sidebar-brand-icon"> AliothPress</h1>
                <p>{{ t('sidebar.admin_panel') }}</p>
            </div>
            
            <nav class="sidebar-menu">
                {# ── MAIN ── #}
                <div class="menu-section">
                    <div class="menu-section-title">{{ t('sidebar.main') }}</div>
                    <ul>
                        <li class="menu-item">
                            <a href="{{ url_for('admin_dashboard') }}" {% if request.endpoint == 'admin_dashboard' %}class="active"{% endif %}>
                                <span class="menu-icon">📊</span> {{ t('sidebar.dashboard') }}
                            </a>
                        </li>
                    </ul>
                </div>
                
                {# ── CONTENT ── #}
                <div class="menu-section">
                    <div class="menu-section-title">{{ t('sidebar.content') }}</div>
                    <ul>
                        <li class="menu-item">
                            <a href="{{ url_for('admin_posts_list') }}" {% if 'posts' in request.endpoint %}class="active"{% endif %}>
                                <span class="menu-icon">📝</span> {{ t('sidebar.posts') }}
                            </a>
                        </li>
                        <li class="menu-item">
                            <a href="{{ url_for('admin_pages_list') }}" {% if 'pages' in request.endpoint %}class="active"{% endif %}>
                                <span class="menu-icon">📄</span> {{ t('sidebar.pages') }}
                            </a>
                        </li>
                        <li class="menu-item">
                            <a href="{{ url_for('admin_media_library') }}" {% if 'media' in request.endpoint %}class="active"{% endif %}>
                                <span class="menu-icon">🖼️</span> {{ t('sidebar.library') }}
                            </a>
                        </li>
                        <li class="menu-item">
                            <a href="{{ url_for('admin_files_list') }}" {% if 'files' in request.endpoint %}class="active"{% endif %}>
                                <span class="menu-icon">📁</span> {{ t('sidebar.files') }}
                            </a>
                        </li>
                    </ul>
                </div>
                
                {# ── TOOLS ── #}
                <div class="menu-section">
                    <div class="menu-section-title">{{ t('sidebar.tools') }}</div>
                    <ul>
                        <li class="menu-item">
                            <a href="{{ url_for('admin_forms_list') }}" {% if 'forms' in request.endpoint %}class="active"{% endif %}>
                                <span class="menu-icon">📋</span> {{ t('sidebar.forms') }}
                            </a>
                        </li>
                        <li class="menu-item">
                            <a href="{{ url_for('admin_newsletter_list') }}" {% if 'newsletter' in request.endpoint %}class="active"{% endif %}>
                                <span class="menu-icon">📨</span> {{ t('sidebar.newsletter') }}
                            </a>
                        </li>
                        <li class="menu-item">
                            <a href="{{ url_for('admin_ai') }}" {% if 'ai' in request.endpoint %}class="active"{% endif %}>
                                <span class="menu-icon">🤖</span> {{ t('sidebar.ai_assistant') }}
                            </a>
                        </li>
                        <li class="menu-item">
                            <a href="{{ url_for('admin_tools') }}" {% if 'tools' in request.endpoint %}class="active"{% endif %}>
                                <span class="menu-icon">🔧</span> {{ t('sidebar.seo_tools') }}
                            </a>
                        </li>
                    </ul>
                </div>
                
                {# ── APPEARANCE ── #}
                <div class="menu-section">
                    <div class="menu-section-title">{{ t('sidebar.appearance') }}</div>
                    <ul>
                        <li class="menu-item">
                            <a href="{{ url_for('admin_themes') }}" {% if request.endpoint == 'admin_themes' %}class="active"{% endif %}>
                                <span class="menu-icon">🎨</span> {{ t('sidebar.themes') }}
                            </a>
                        </li>
                        <li class="menu-item">
                            <a href="{{ url_for('admin_menus') }}" {% if request.endpoint == 'admin_menus' %}class="active"{% endif %}>
                                <span class="menu-icon">📱</span> {{ t('sidebar.menus') }}
                            </a>
                        </li>
                        <li class="menu-item">
                            <a href="{{ url_for('admin_favicon_manager') }}" {% if request.endpoint == 'admin_favicon_manager' %}class="active"{% endif %}>
                                <span class="menu-icon">🎯</span> {{ t('sidebar.favicon') }}
                            </a>
                        </li>
                    </ul>
                </div>
                
                {# ── PLUGINS: management (owner) on top, then entries from loaded plugins ── #}
                {% set _pnav = plugin_nav_items() if plugin_nav_items is defined else [] %}
                {% if _pnav or current_user.is_owner() %}
                <div class="menu-section">
                    <div class="menu-section-title">{{ t('sidebar.plugins') }}</div>
                    <ul>
                        {% if current_user.is_owner() %}
                        <li class="menu-item">
                            <a href="{{ url_for('plugins_admin.admin_plugins') }}" {% if request.endpoint and request.endpoint.startswith('plugins_admin.') %}class="active"{% endif %}>
                                <span class="menu-icon">🧩</span> {{ t('plugins.installed') }}
                            </a>
                        </li>
                        {% endif %}
                        {% for _pitem in _pnav %}
                        <li class="menu-item">
                            <a href="{{ url_for(_pitem.endpoint, **(_pitem.endpoint_args or {})) }}" {% if request.endpoint == _pitem.endpoint %}class="active"{% endif %}{% if _pitem.locked %} style="color: var(--adm-sidebar-muted);"{% endif %}>
                                <span class="menu-icon">{{ _pitem.icon }}</span> {{ t(_pitem.label_key) }}
                            </a>
                        </li>
                        {% endfor %}
                    </ul>
                </div>
                {% endif %}

                {# ── SYSTEM (admin only) ── #}
                {% if current_user.can_access_settings() %}
                <div class="menu-section">
                    <div class="menu-section-title">{{ t('sidebar.system') }}</div>
                    <ul>
                        <li class="menu-item">
                            <a href="{{ url_for('admin_audit_log') }}" {% if request.endpoint == 'admin_audit_log' %}class="active"{% endif %}>
                                <span class="menu-icon">🛡️</span> {{ t('sidebar.audit_log') }}
                            </a>
                        </li>
                        <li class="menu-item">
                            <a href="{{ url_for('admin_backup') }}" {% if request.endpoint == 'admin_backup' %}class="active"{% endif %}>
                                <span class="menu-icon">💾</span> {{ t('sidebar.backup') }}
                            </a>
                        </li>
                        <li class="menu-item">
                            <a href="{{ url_for('admin_users_list') }}" {% if 'users' in request.endpoint %}class="active"{% endif %}>
                                <span class="menu-icon">👨‍💻</span> {{ t('sidebar.users') }}
                            </a>
                        </li>
                        <li class="menu-item">
                            <a href="{{ url_for('admin_settings') }}" {% if request.endpoint == 'admin_settings' %}class="active"{% endif %}>
                                <span class="menu-icon">⚙️</span> {{ t('sidebar.settings') }}
                            </a>
                        </li>
                    </ul>
                </div>
                {% endif %}
            </nav>
            
            <div class="user-menu">
                <div class="user-info">
                    <div class="user-avatar">{{ current_user.get_display_name()[0].upper() }}</div>
                    <div>
                        <div class="user-name">{{ current_user.get_display_name() }}</div>
                        <div class="user-role">{{ t('users.role_' + current_user.role) }}</div>
                    </div>
                </div>
                <a href="{{ url_for('admin_profile') }}" class="profile-btn">{{ t('sidebar.my_profile') }}</a>
                <form method="post" action="{{ url_for('admin_logout') }}" class="logout-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><button type="submit" class="logout-btn">{{ t('sidebar.logout') }}</button></form>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="main-content">
            {% with messages = get_flashed_messages(with_categories=true) %}
                {% if messages %}
                    {% for category, message in messages %}
                        <div class="alert alert-{{ category }}">{{ message }}</div>
                    {% endfor %}
                {% endif %}
            {% endwith %}
            
            {% if demo_mode %}
                <div class="alert alert-info demo-mode-banner">🧪 {{ t('demo.banner') }}</div>
            {% endif %}
            
            <div class="page-body">
                {% block content %}{% endblock %}
            </div>
        </main>
    </div>
    
    {% block extra_js %}{% endblock %}

<!-- ================================================================
     Shared admin image picker (centralized in one file, not duplicated
     across posts/pages/newsletter edit templates). Exposes two globals:
     
       window.openImagePicker(callback)           — core modal
       window.pickImageFor(inputId, altInputId)   — convenience wrapper
     
     Translations are passed via window.AdminPickerI18n so the JS file
     itself stays pure (no Jinja templating). See _find_image_usage in
     app.py for the matching backend endpoint.
     ================================================================ -->
<script>
window.AdminPickerI18n = {
    select_image: {{ t('media.select_image')|tojson }},
    loading: {{ t('common.loading')|tojson }},
    no_images_picker: {{ t('media.no_images_picker')|tojson }},
    upload_first_link: {{ t('media.upload_first_link')|tojson }},
    error_loading_retry: {{ t('media.error_loading_retry')|tojson }},
    search_placeholder: {{ t('media.search_placeholder')|tojson }},
    no_results: {{ t('media.no_results')|tojson }},
    prev: {{ t('pagination.prev')|tojson }},
    next: {{ t('pagination.next')|tojson }}
};
</script>
<script src="{{ static_v('js/admin-image-picker.js') }}"></script>

<!-- Toast controller (readability rework):
     one fixed stack for ALL toasts — server flashes and dynamic
     adminToast() calls alike. Lifetime grows with the text (people
     read footnotes, not glimpse them), hovering pauses the clock,
     the close button always works, and nothing ever overlaps. -->
<script>
(function () {
    var stack = document.createElement('div');
    stack.id = 'adm-toasts';
    document.body.appendChild(stack);

    window.admToastMount = function (el) {
        if (!el.querySelector('.alert-close')) {
            var close = document.createElement('button');
            close.className = 'alert-close';
            close.setAttribute('aria-label', 'Close');
            close.innerHTML = '&times;';
            el.appendChild(close);
        }
        el.querySelector('.alert-close').addEventListener('click',
            function () { el.remove(); });
        stack.appendChild(el);

        var text = el.textContent || '';
        var life = Math.min(10000, 4000 + text.length * 50);
        var timer = null;
        function leave() {
            el.classList.add('is-leaving');
            el.addEventListener('animationend', function (e) {
                if (e.animationName === 'toastFadeOut') el.remove();
            });
        }
        function arm() { timer = setTimeout(leave, life); }
        el.addEventListener('mouseenter', function () {
            clearTimeout(timer);            /* reading — the clock waits */
        });
        el.addEventListener('mouseleave', arm);
        arm();
        return el;
    };

    /* Server-rendered flashes move from the page flow into the stack */
    document.querySelectorAll('.alert').forEach(function (el) {
        window.admToastMount(el);
    });
})();
</script>

<!-- CSRF auto-injection: adds token to all forms and fetch requests -->
<script>
(function(){
    var token = document.querySelector('meta[name="csrf-token"]');
    if (!token) return;
    var csrfValue = token.getAttribute('content');
    
    // 1. Inject hidden input into all forms that don't already have one
    document.querySelectorAll('form').forEach(function(form) {
        if (!form.querySelector('input[name="csrf_token"]')) {
            var input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'csrf_token';
            input.value = csrfValue;
            form.prepend(input);
        }
    });
    
    // 2. Auto-add CSRF header to all fetch() POST/PUT/DELETE requests
    var origFetch = window.fetch;
    window.fetch = function(url, opts) {
        opts = opts || {};
        if (opts.method && ['POST','PUT','DELETE','PATCH'].indexOf(opts.method.toUpperCase()) !== -1) {
            opts.headers = opts.headers || {};
            if (opts.headers instanceof Headers) {
                if (!opts.headers.has('X-CSRFToken')) opts.headers.set('X-CSRFToken', csrfValue);
            } else {
                if (!opts.headers['X-CSRFToken']) opts.headers['X-CSRFToken'] = csrfValue;
            }
        }
        return origFetch.call(this, url, opts);
    };
})();
</script>

<!-- ============================================================
     Shared admin toast + inline edit save
     ------------------------------------------------------------
     adminToast(message, type) reuses the SAME .alert component the
     server flashes render with (see the flash loop above): same markup,
     same themed --adm-* colours (light/dark), same toastFadeOut timing.
     No new styles, no hardcoded strings — the text is passed in from
     i18n by whoever calls it.

     The inline saver upgrades any <form data-inline-save> so that "Save"
     posts in place and shows that toast instead of navigating away. It
     runs AFTER each editor's own submit listener (slug checks, TinyMCE
     sync, hidden-field updates), and bails if that listener already
     called preventDefault, so existing validation still wins.
     ============================================================ -->
<script>
(function(){
    window.adminToast = function(message, type) {
        var el = document.createElement('div');
        el.className = 'alert alert-' + (type || 'success');
        el.textContent = message || '';
        // The shared controller (above) owns stacking, lifetime,
        // hover-pause and the close button.
        return window.admToastMount(el);
    };

    var FALLBACK = {
        save_failed: {{ t('builder.save_failed')|tojson }},
        network_error: {{ t('builder.network_error')|tojson }},
        session_expired: {{ t('flash.session_expired')|tojson }}
    };

    function submitButtonsFor(form){
        var btns = Array.prototype.slice.call(form.querySelectorAll('[type="submit"]'));
        if (form.id) {
            document.querySelectorAll('[type="submit"][form="' + form.id + '"]').forEach(function(b){
                if (btns.indexOf(b) === -1) btns.push(b);
            });
        }
        return btns;
    }

    document.querySelectorAll('form[data-inline-save]').forEach(function(form){
        form.addEventListener('submit', function(e){
            // An earlier listener (slug validation, etc.) already blocked it.
            if (e.defaultPrevented) return;
            // Keep rich-text editors in sync before we read the form values.
            if (typeof AliothEditor !== 'undefined') {
                try { AliothEditor.triggerSave(); } catch (_) {}
            }
            // Legacy fallback: a third-party plugin may still load TinyMCE.
            if (typeof tinymce !== 'undefined') {
                try { tinymce.triggerSave(); } catch (_) {}
            }
            e.preventDefault();

            var btns = submitButtonsFor(form);
            btns.forEach(function(b){ b.disabled = true; });

            fetch(form.getAttribute('action') || window.location.href, {
                method: 'POST',
                headers: { 'X-Requested-With': 'XMLHttpRequest' },
                body: new FormData(form)
            })
            .then(function(r){
                // An expired CSRF token / login comes back as a 3xx that fetch
                // silently follows to an HTML page (or as a non-JSON body). Catch
                // that and report "session expired" instead of a generic failure.
                var ct = r.headers.get('content-type') || '';
                if (r.redirected || ct.indexOf('application/json') === -1) {
                    return { ok: false, data: { error: FALLBACK.session_expired } };
                }
                return r.json().catch(function(){ return {}; }).then(function(d){
                    return { ok: r.ok, data: d };
                });
            })
            .then(function(res){
                if (res.ok && res.data && res.data.success) {
                    adminToast(res.data.message || '', 'success');
                } else {
                    var msg = (res.data && (res.data.message || res.data.error)) || FALLBACK.save_failed;
                    adminToast(msg, 'error');
                }
            })
            .catch(function(){
                adminToast(FALLBACK.network_error, 'error');
            })
            .finally(function(){
                btns.forEach(function(b){ b.disabled = false; });
            });
        });
    });
})();
</script>

<!-- ============================================================
     AI ASSISTANT — Global modal component
     Available on all admin pages via window.AliothAI
     ============================================================ -->
<div class="ai-modal-overlay" id="aiModalOverlay">
    <div class="ai-modal">
        <div class="ai-modal__header">
            <h3>🤖 {{ t('ai.title') }}</h3>
            <button class="ai-modal__close" onclick="AliothAI.close()">&times;</button>
        </div>
        <div class="ai-modal__body">
            <div class="ai-modal__context" id="aiContext"></div>
            <div class="ai-modal__chat" id="aiChat"></div>
            <div class="ai-modal__input-row">
                <textarea class="ai-modal__textarea" id="aiInput" rows="2"
                    placeholder="{{ t('ai.prompt_placeholder') }}"
                    onkeydown="if(event.key==='Enter'&&!event.shiftKey){event.preventDefault();AliothAI.send()}"></textarea>
                <button class="ai-modal__send" id="aiSendBtn" onclick="AliothAI.send()">{{ t('ai.send') }}</button>
            </div>
            <div class="ai-modal__actions d-none" id="aiActions">
                <button class="ai-modal__apply" id="aiApplyBtn" onclick="AliothAI.apply()">✅ {{ t('ai.apply_result') }}</button>
                <button class="ai-modal__discard" onclick="AliothAI.close()">{{ t('common.cancel') }}</button>
            </div>
        </div>
    </div>
</div>

<script>
/**
 * AliothAI — Global AI Assistant
 * Usage:
 *   AliothAI.open({ mode, contentType, language, onApply })
 *   mode: 'generate_full' | 'seo' | 'translate' | 'builder_blocks'
 *   onApply: function(result) — called when user clicks "Apply"
 */
window.AliothAI = (function() {
    var overlay = document.getElementById('aiModalOverlay');
    var chat = document.getElementById('aiChat');
    var input = document.getElementById('aiInput');
    var sendBtn = document.getElementById('aiSendBtn');
    var actionsDiv = document.getElementById('aiActions');
    var applyBtn = document.getElementById('aiApplyBtn');
    var contextDiv = document.getElementById('aiContext');

    var _t = {
        mode_generate: '{{ t("ai.modal_mode_generate") }}',
        mode_seo: '{{ t("ai.modal_mode_seo") }}',
        mode_translate: '{{ t("ai.modal_mode_translate") }}',
        mode_builder: '{{ t("ai.modal_mode_builder") }}',
        mode_form: '{{ t("ai.modal_mode_form") }}',
        context_language: '{{ t("ai.modal_context_language") }}',
        welcome_generate: '{{ t("ai.modal_welcome_generate") }}',
        welcome_seo: '{{ t("ai.modal_welcome_seo") }}'.replace(/&#34;/g, '"'),
        welcome_translate: '{{ t("ai.modal_welcome_translate") }}'.replace(/&#34;/g, '"'),
        welcome_builder: '{{ t("ai.modal_welcome_builder") }}',
        welcome_form: '{{ t("ai.modal_welcome_form") }}'.replace(/&#34;/g, '"'),
        welcome_default: '{{ t("ai.modal_welcome_default") }}',
        thinking: '{{ t("ai.modal_thinking") }}',
        network_error: '{{ t("ai.modal_network_error") }}',
        summary_generated: '{{ t("ai.modal_summary_generated") }}',
        summary_title: '{{ t("ai.modal_summary_title") }}',
        summary_excerpt: '{{ t("ai.modal_summary_excerpt") }}',
        summary_content: '{{ t("ai.modal_summary_content") }}',
        summary_seo_title: '{{ t("ai.modal_summary_seo_title") }}',
        summary_seo_desc: '{{ t("ai.modal_summary_seo_desc") }}',
        summary_blocks: '{{ t("ai.modal_summary_blocks") }}',
        summary_blocks_count: '{{ t("ai.modal_summary_blocks_count") }}',
        summary_fields: '{{ t("ai.modal_summary_fields") }}',
        summary_fields_count: '{{ t("ai.modal_summary_fields_count") }}',
        summary_submit: '{{ t("ai.modal_summary_submit") }}'
    };

    var state = {
        isOpen: false,
        mode: 'generate_full',
        contentType: 'page',
        language: 'English',
        existingTitle: '',
        existingContent: '',
        onApply: null,
        lastResult: null,
        messages: [],
        busy: false
    };

    // Auto-resize textarea
    input.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = Math.min(this.scrollHeight, 300) + 'px';
    });

    function open(opts) {
        opts = opts || {};
        state.mode = opts.mode || 'generate_full';
        state.contentType = opts.contentType || 'page';
        state.language = opts.language || 'English';
        state.existingTitle = opts.existingTitle || '';
        state.existingContent = opts.existingContent || '';
        state.onApply = opts.onApply || null;
        state.lastResult = null;
        state.messages = [];
        state.busy = false;

        // Context info
        var modeLabels = {
            'generate_full': '📝 ' + _t.mode_generate.replace('{content_type}', state.contentType),
            'seo': '🔍 ' + _t.mode_seo,
            'translate': '🌍 ' + _t.mode_translate,
            'builder_blocks': '🧩 ' + _t.mode_builder,
            'generate_form': '📋 ' + _t.mode_form
        };
        contextDiv.innerHTML = '<strong>' + (modeLabels[state.mode] || state.mode) + '</strong>' +
            ' · ' + _t.context_language + ' <strong>' + esc(state.language) + '</strong>' +
            (state.existingTitle ? ' · "' + esc(state.existingTitle) + '"' : '');

        chat.innerHTML = '';
        actionsDiv.classList.add('d-none');
        input.value = '';
        input.style.height = 'auto';
        input.disabled = false;
        sendBtn.disabled = false;

        // Welcome message
        var welcomeMsgs = {
            'generate_full': _t.welcome_generate.replace('{content_type}', state.contentType),
            'seo': _t.welcome_seo,
            'translate': _t.welcome_translate,
            'builder_blocks': _t.welcome_builder,
            'generate_form': _t.welcome_form
        };
        addMessage('ai', welcomeMsgs[state.mode] || _t.welcome_default);

        overlay.classList.add('is-open');
        state.isOpen = true;
        setTimeout(function() { input.focus(); }, 100);
    }

    function close() {
        overlay.classList.remove('is-open');
        state.isOpen = false;
        state.onApply = null;
    }

    function addMessage(role, text) {
        var div = document.createElement('div');
        div.className = 'ai-msg ai-msg--' + role;
        div.innerHTML = text;
        chat.appendChild(div);
        chat.scrollTop = chat.scrollHeight;
        state.messages.push({ role: role, text: text });
        return div;
    }

    function send() {
        if (state.busy) return;
        var text = input.value.trim();
        if (!text) return;

        addMessage('user', esc(text));
        input.value = '';
        input.style.height = 'auto';
        input.disabled = true;
        sendBtn.disabled = true;
        state.busy = true;

        var loadingMsg = addMessage('ai', _t.thinking);
        loadingMsg.classList.add('ai-msg--loading');

        // Build request
        var body = {
            task: state.mode,
            prompt: text,
            content_type: state.contentType,
            language: state.language,
            title: state.existingTitle,
            content: state.existingContent
        };

        // Conversation history for context
        var history = state.messages.filter(function(m) {
            return m.role === 'user' || m.role === 'ai';
        }).slice(0, -1).map(function(m) {
            return (m.role === 'user' ? 'User' : 'Assistant') + ': ' + m.text;
        }).join('\n');
        if (history) body.conversation_history = history;

        fetch('/admin/ai/generate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            body: JSON.stringify(body)
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            loadingMsg.remove();
            state.messages.pop(); // remove loading

            if (data.error) {
                addMessage('system', '❌ ' + esc(data.error));
                return;
            }

            // Parse AI response
            var result = data.result;
            state.lastResult = data;

            // Try to extract JSON for structured responses
            if (state.mode === 'generate_full' || state.mode === 'seo' || state.mode === 'builder_blocks' || state.mode === 'generate_form') {
                try {
                    // AI might return JSON wrapped in markdown
                    var jsonStr = result;
                    var jsonMatch = result.match(/```(?:json)?\s*([\s\S]*?)```/);
                    if (jsonMatch) jsonStr = jsonMatch[1];
                    var parsed = JSON.parse(jsonStr.trim());
                    state.lastResult.parsed = parsed;

                    // Show AI comment if present
                    if (parsed.ai_message) {
                        addMessage('ai', parsed.ai_message);
                    }

                    // Show summary of what was generated
                    var summary = formatResultSummary(parsed);
                    if (summary) {
                        addMessage('ai', summary);
                    }

                    // Show apply button
                    actionsDiv.classList.remove('d-none');
                    applyBtn.disabled = false;

                } catch (e) {
                    // Plain text response — show as is (could be a clarifying question from AI)
                    addMessage('ai', esc(result).replace(/\n/g, '<br>'));
                }
            } else {
                // translate or other — show raw result
                state.lastResult.parsed = { content: result };
                addMessage('ai', esc(result).replace(/\n/g, '<br>'));
                actionsDiv.classList.remove('d-none');
            }
        })
        .catch(function(err) {
            loadingMsg.remove();
            state.messages.pop();
            addMessage('system', '❌ ' + _t.network_error + ' ' + esc(err.message));
        })
        .finally(function() {
            input.disabled = false;
            sendBtn.disabled = false;
            state.busy = false;
            input.focus();
        });
    }

    function formatResultSummary(parsed) {
        var parts = [];
        if (parsed.title) parts.push('<strong>' + _t.summary_title + '</strong> ' + esc(parsed.title));
        if (parsed.excerpt) parts.push('<strong>' + _t.summary_excerpt + '</strong> ' + esc(parsed.excerpt).substring(0, 100) + '...');
        if (parsed.content) parts.push('<strong>' + _t.summary_content + '</strong> ' + (parsed.content.length > 100 ? parsed.content.substring(0, 100).replace(/</g,'&lt;') + '...' : esc(parsed.content)));
        if (parsed.meta_title) parts.push('<strong>' + _t.summary_seo_title + '</strong> ' + esc(parsed.meta_title));
        if (parsed.meta_description) parts.push('<strong>' + _t.summary_seo_desc + '</strong> ' + esc(parsed.meta_description));
        if (parsed.blocks && parsed.blocks.length) parts.push('<strong>' + _t.summary_blocks + '</strong> ' + parsed.blocks.length + ' ' + _t.summary_blocks_count);
        if (parsed.fields && parsed.fields.length) parts.push('<strong>' + _t.summary_fields + '</strong> ' + parsed.fields.length + ' ' + _t.summary_fields_count);
        if (parsed.settings && parsed.settings.submit_label) parts.push('<strong>' + _t.summary_submit + '</strong> ' + esc(parsed.settings.submit_label));
        if (parts.length === 0) return '';
        return '📋 <strong>' + _t.summary_generated + '</strong><br>' + parts.join('<br>');
    }

    function apply() {
        if (!state.lastResult || !state.onApply) return;
        var parsed = state.lastResult.parsed || {};
        state.onApply(parsed);
        close();
    }

    function esc(s) {
        var d = document.createElement('div');
        d.textContent = s || '';
        return d.innerHTML;
    }

    // Close on overlay click
    overlay.addEventListener('click', function(e) {
        if (e.target === overlay) close();
    });

    // Close on Escape
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && state.isOpen) close();
    });

    return { open: open, close: close, send: send, apply: apply };
})();
</script>

<!-- Sidebar scroll memory: remembers position between page navigations -->
<script>
(function() {
    var sb = document.querySelector('.sidebar');
    if (!sb) return;
    var key = 'ap-sidebar-scroll';
    var saved = sessionStorage.getItem(key);
    if (saved) sb.scrollTop = parseInt(saved, 10);
    sb.addEventListener('scroll', function() {
        sessionStorage.setItem(key, sb.scrollTop);
    });
})();
</script>

{%- if settings.get('webmcp_admin_enabled', 'false') == 'true' %}
<!-- WebMCP: let an AI agent (e.g. Claude in Chrome) use the admin panel -->
<script>
  window.AP_WEBMCP = {
    surface: 'admin',
    csrf: "{{ csrf_token() }}",
    usePolyfill: {{ 'true' if settings.get('webmcp_polyfill', 'false') == 'true' else 'false' }},
    aiTools: {{ 'true' if ai_provider_ready else 'false' }},
    debug: false,
    i18n: {
      confirm_create_post: {{ t('webmcp.confirm_create_post') | tojson }},
      confirm_create_page: {{ t('webmcp.confirm_create_page') | tojson }},
      confirm_create_builder_page: {{ t('webmcp.confirm_create_builder_page') | tojson }},
      confirm_set_page_blocks:     {{ t('webmcp.confirm_set_page_blocks')     | tojson }},
      confirm_build_menu:  {{ t('webmcp.confirm_build_menu')  | tojson }},
      confirm_upload_image: {{ t('webmcp.confirm_upload_image') | tojson }},
      confirm_update_post:  {{ t('webmcp.confirm_update_post')  | tojson }},
      confirm_update_page:  {{ t('webmcp.confirm_update_page')  | tojson }},
      confirm_attach_image: {{ t('webmcp.confirm_attach_image') | tojson }},
      publish_blocked:      {{ t('webmcp.publish_blocked')      | tojson }},
      builder_content_locked: {{ t('webmcp.builder_content_locked') | tojson }},
      confirm_title:     {{ t('webmcp.confirm_title')     | tojson }},
      approve:           {{ t('webmcp.approve')           | tojson }},
      cancel:            {{ t('webmcp.cancel')            | tojson }},
      select_all:        {{ t('webmcp.select_all')        | tojson }},
      approve_selected:  {{ t('webmcp.approve_selected')  | tojson }},
      batch_title_posts: {{ t('webmcp.batch_title_posts') | tojson }},
      batch_title_pages: {{ t('webmcp.batch_title_pages') | tojson }},
      batch_title_images: {{ t('webmcp.batch_title_images') | tojson }},
      autopilot_label:   {{ t('webmcp.autopilot_label')   | tojson }},
      autopilot_minutes: {{ t('webmcp.autopilot_minutes') | tojson }},
      autopilot_badge:   {{ t('webmcp.autopilot_badge')   | tojson }},
      autopilot_revoke:  {{ t('webmcp.autopilot_revoke')  | tojson }},
      declined:            {{ t('webmcp.declined')            | tojson }}
    }
  };
</script>
<script src="{{ static_v('js/webmcp-core.js') }}"></script>
<script src="{{ static_v('js/webmcp-admin.js') }}"></script>
{%- endif %}
</body>
</html>
