<!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() }}">
    <title>{% block title %}{{ t('sidebar.dashboard') }}{% endblock %} - AliothPress</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/admin.css') }}">
    {% block extra_css %}{% endblock %}
</head>
<body data-theme="{{ 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>
                
                {# ── 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>
                <a href="{{ url_for('admin_logout') }}" class="logout-btn">{{ t('sidebar.logout') }}</a>
            </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 }}<button class="alert-close" onclick="this.parentElement.remove()" aria-label="Close">&times;</button></div>
                    {% endfor %}
                {% endif %}
            {% endwith %}
            
            <div class="page-body">
                {% block content %}{% endblock %}
            </div>
        </main>
    </div>
    
    <!-- TinyMCE theme-aware config (used by editor pages) -->
    <script>
    window._tinyTheme = (function() {
        var isDark = document.body.getAttribute('data-theme') === 'dark';
        var muted = getComputedStyle(document.documentElement).getPropertyValue('--ap-color-text-muted').trim() || (isDark ? '#94a3b8' : '#64748b');
        return {
            skin: isDark ? 'oxide-dark' : 'oxide',
            content_style: isDark
                ? 'body { background: #1a1c25; color: #e2e8f0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; font-size: 16px; line-height: 1.6; } a { color: #a8b4d0; } [data-mce-placeholder]::before { color: ' + muted + ' !important; }'
                : 'body { background: #ffffff; color: #1e293b; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; font-size: 16px; line-height: 1.6; } a { color: #5c7a9e; } [data-mce-placeholder]::before { color: ' + muted + ' !important; }'
        };
    })();
    </script>
    
    {% 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 }}
};
</script>
<script src="{{ url_for('static', filename='js/admin-image-picker.js') }}"></script>

<!-- Auto-remove flash alerts after fadeout to prevent click-blocking -->
<script>
document.querySelectorAll('.alert').forEach(function(el) {
    el.addEventListener('animationend', function(e) {
        if (e.animationName === 'toastFadeOut') {
            el.remove();
        }
    });
});
</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>

<!-- ============================================================
     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>
</body>
</html>
