{% extends 'admin/base.html' %}
{% block title %}{{ t('ai.title') }}{% endblock %}

{% block content %}
<div class="page-header">
    <h2>🤖 {{ t('ai.title') }}</h2>
    <p>{{ t('ai.subtitle') }}</p>
</div>

<div class="ai-container">
    <!-- API Key Configuration -->
    <div class="ai-section">
        <h3>🔑 {{ t('ai.api_config') }}</h3>
        
        <div class="mb-4">
            <strong>{{ t('ai.status') }}</strong>
            {% if has_api_key %}
                <span class="status-badge status-connected">✅ {{ t('ai.connected') }}</span>
                <span class="text-sm text-muted ml-1">
                    {{ t('ai.provider_' + active_provider) }} · {{ api_key_preview }}
                </span>
            {% else %}
                <span class="status-badge status-not-connected">❌ {{ t('ai.not_configured') }}</span>
            {% endif %}
        </div>
        
        <form method="POST">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            <input type="hidden" name="action" value="save_ai_config">
            
            <!-- Provider selector -->
            <div class="form-group">
                <label for="ai_provider">{{ t('ai.provider_label') }}</label>
                <select id="ai_provider" name="ai_provider" onchange="toggleProviderFields()">
                    <option value="anthropic" {% if active_provider == 'anthropic' %}selected{% endif %}>{{ t('ai.provider_anthropic') }}{% if providers.anthropic.has_key %} · 🔑{% endif %}</option>
                    <option value="deepseek" {% if active_provider == 'deepseek' %}selected{% endif %}>{{ t('ai.provider_deepseek') }}{% if providers.deepseek.has_key %} · 🔑{% endif %}</option>
                    <option value="gemini" {% if active_provider == 'gemini' %}selected{% endif %}>{{ t('ai.provider_gemini') }}{% if providers.gemini.has_key %} · 🔑{% endif %}</option>
                </select>
                <div class="help-text">{{ t('ai.provider_help') }}</div>
            </div>
            
            <!-- Anthropic key -->
            <div class="ai-provider-field d-none" data-provider="anthropic">
                <div class="form-group">
                    <label>{{ t('ai.provider_anthropic') }} {{ t('ai.api_key_label') }}
                        {% if providers.anthropic.has_key %}<span class="text-success text-sm">✓ {{ t('ai.key_saved') }}</span>{% endif %}
                    </label>
                    <div class="api-key-row">
                        <input type="password" name="anthropic_api_key" 
                               placeholder="{% if providers.anthropic.has_key %}{{ providers.anthropic.preview }} — {{ t('ai.key_keep_hint') }}{% else %}sk-ant-...{% endif %}" value="">
                    </div>
                    <div class="help-text"><a href="https://console.anthropic.com/settings/keys" target="_blank" rel="noopener">console.anthropic.com</a> {{ t('ai.key_link_anthropic') }}</div>
                </div>
            </div>
            
            <!-- DeepSeek key -->
            <div class="ai-provider-field d-none" data-provider="deepseek">
                <div class="form-group">
                    <label>{{ t('ai.provider_deepseek') }} {{ t('ai.api_key_label') }}
                        {% if providers.deepseek.has_key %}<span class="text-success text-sm">✓ {{ t('ai.key_saved') }}</span>{% endif %}
                    </label>
                    <div class="api-key-row">
                        <input type="password" name="deepseek_api_key" 
                               placeholder="{% if providers.deepseek.has_key %}{{ providers.deepseek.preview }} — {{ t('ai.key_keep_hint') }}{% else %}sk-...{% endif %}" value="">
                    </div>
                    <div class="help-text"><a href="https://platform.deepseek.com/api_keys" target="_blank" rel="noopener">platform.deepseek.com</a> {{ t('ai.key_link_deepseek') }}</div>
                </div>
            </div>
            
            <!-- Gemini key -->
            <div class="ai-provider-field d-none" data-provider="gemini">
                <div class="form-group">
                    <label>{{ t('ai.provider_gemini') }} {{ t('ai.api_key_label') }}
                        {% if providers.gemini.has_key %}<span class="text-success text-sm">✓ {{ t('ai.key_saved') }}</span>{% endif %}
                    </label>
                    <div class="api-key-row">
                        <input type="password" name="gemini_api_key" 
                               placeholder="{% if providers.gemini.has_key %}{{ providers.gemini.preview }} — {{ t('ai.key_keep_hint') }}{% else %}AIza...{% endif %}" value="">
                    </div>
                    <div class="help-text"><a href="https://aistudio.google.com/apikey" target="_blank" rel="noopener">aistudio.google.com</a> {{ t('ai.key_link_gemini') }}</div>
                </div>
            </div>
            
            <button type="submit" class="btn btn-primary">💾 {{ t('common.save') }}</button>
        </form>
        
        <script>
        function toggleProviderFields() {
            var sel = document.getElementById('ai_provider').value;
            document.querySelectorAll('.ai-provider-field').forEach(function(el) {
                el.classList.toggle('d-none', el.dataset.provider !== sel);
            });
        }
        toggleProviderFields();
        </script>
    </div>

    <!-- AI Chat Interface -->
    <div class="ai-section">
        <h3>✨ {{ t('ai.tools_title') }}</h3>
        
        {% if not has_api_key %}
        <div class="info-box info-box--warning">
            <strong>⚠️ {{ t('ai.api_key_required') }}</strong><br>
            <small>{{ t('ai.api_key_required_hint') }}</small>
        </div>
        {% endif %}

        <!-- Quick Actions -->
        <div class="ai-quick-actions">
            <button class="ai-chip" data-task="generate" {% if not has_api_key %}disabled{% endif %}>
                📝 {{ t('ai.content_generator') }}
            </button>
            <button class="ai-chip" data-task="translate" {% if not has_api_key %}disabled{% endif %}>
                🌍 {{ t('ai.translator') }}
            </button>
            <button class="ai-chip" data-task="seo" {% if not has_api_key %}disabled{% endif %}>
                🔍 {{ t('ai.seo_optimizer') }}
            </button>
            <button class="ai-chip" data-task="builder_blocks" {% if not has_api_key %}disabled{% endif %}>
                🧱 {{ t('ai.page_builder') }}
            </button>
            <button class="ai-chip" data-task="generate_form" {% if not has_api_key %}disabled{% endif %}>
                📋 {{ t('ai.form_designer') }}
            </button>
        </div>

        <!-- Chat Window -->
        <div class="ai-chat">
            <div class="ai-chat__header">
                <span class="text-sm text-muted" id="aiChatStatus">{{ t('ai.new_conversation') }}</span>
                <button class="ai-chat__new-btn" onclick="newChat()" title="{{ t('ai.new_chat_hint') }}">
                    ✨ {{ t('ai.new_chat') }}
                </button>
            </div>
            <div class="ai-chat__messages" id="aiMessages">
            </div>

            <!-- Input Area -->
            <div class="ai-chat__input-area">
                <div class="ai-chat__context d-none" id="aiContext">
                    <span id="aiContextLabel"></span>
                    <button onclick="clearContext()" title="{{ t('common.clear') }}">&times;</button>
                </div>
                <div class="ai-chat__input-row">
                    <textarea id="aiInput" 
                              placeholder="{{ t('ai.prompt_placeholder') }}" 
                              rows="1"
                              {% if not has_api_key %}disabled{% endif %}></textarea>
                    <button id="aiSendBtn" class="ai-chat__send" onclick="sendMessage()" {% if not has_api_key %}disabled{% endif %}>
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>
                        </svg>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<div id="aiLanguagesData" class="d-none"
     data-languages='[{% for lang in available_languages %}{"code":"{{ lang.code }}","name":"{{ lang.name }}"}{% if not loop.last %},{% endif %}{% endfor %}]'></div>
<script>
(function() {
    var messagesEl = document.getElementById('aiMessages');
    var inputEl = document.getElementById('aiInput');
    var sendBtn = document.getElementById('aiSendBtn');
    var contextEl = document.getElementById('aiContext');
    var contextLabel = document.getElementById('aiContextLabel');
    
    var currentTask = 'chat';
    var conversationHistory = [];
    var isProcessing = false;
    var messageCount = 0;
    var statusEl = document.getElementById('aiChatStatus');

    // i18n strings passed from Jinja
    var I18N = {
        new_conversation: '{{ t("ai.new_conversation") }}',
        messages_count: '{{ t("ai.messages_count") }}',
        welcome: '{{ t("ai.chat_welcome") }}',
        welcome_hint: '{{ t("ai.chat_welcome_hint") }}',
        chip_generate: '{{ t("ai.chip_generate") }}',
        chip_translate: '{{ t("ai.chip_translate") }}',
        chip_seo: '{{ t("ai.chip_seo") }}',
        chip_builder: '{{ t("ai.chip_builder") }}',
        chip_form: '{{ t("ai.chip_form") }}',
        result_done: '{{ t("ai.result_done") }}',
        error_label: '{{ t("ai.error_label") }}',
        connection_error: '{{ t("ai.connection_error") }}',
        task_content: '{{ t("ai.task_content") }}',
        task_translate: '{{ t("ai.task_translate") }}',
        task_seo: '{{ t("ai.task_seo") }}',
        task_builder: '{{ t("ai.task_builder") }}',
        task_form: '{{ t("ai.task_form") }}',
        result_label: '{{ t("ai.result_label") }}',
        copy_btn: '{{ t("ai.copy_btn") }}',
        copied_btn: '{{ t("ai.copied_btn") }}',
        label_title: '{{ t("ai.label_title") }}',
        label_excerpt: '{{ t("ai.label_excerpt") }}',
        label_meta_title: '{{ t("ai.label_meta_title") }}',
        label_meta_desc: '{{ t("ai.label_meta_desc") }}',
        label_description: '{{ t("ai.label_description") }}',
        label_fields: '{{ t("ai.label_fields") }}',
        label_fields_count: '{{ t("ai.label_fields_count") }}',
        label_content_preview: '{{ t("ai.label_content_preview") }}',
        result_builder_blocks: '{{ t("ai.result_builder_blocks") }}',
        result_form_design: '{{ t("ai.result_form_design") }}',
        result_generated_content: '{{ t("ai.result_generated_content") }}',
        result_seo_fields: '{{ t("ai.result_seo_fields") }}'
    };

    function showWelcome() {
        messagesEl.innerHTML = '';
        addMessage('assistant', 
            I18N.welcome +
            '<span class="ai-welcome-hint">' +
            I18N.welcome_hint + '</span>'
        );
    }

    function newChat() {
        conversationHistory = [];
        messageCount = 0;
        statusEl.textContent = I18N.new_conversation;
        clearContext();
        showWelcome();
        inputEl.focus();
    }
    window.newChat = newChat;

    // Show initial welcome
    showWelcome();

    // Available languages from site config
    var languages = JSON.parse(document.getElementById('aiLanguagesData').dataset.languages);

    // Quick action chips — just set input hints, task stays 'chat'
    var chipHints = {
        'generate': I18N.chip_generate,
        'translate': I18N.chip_translate,
        'seo': I18N.chip_seo,
        'builder_blocks': I18N.chip_builder,
        'generate_form': I18N.chip_form
    };

    var taskLabels = {
        'generate': '📝 ' + I18N.task_content,
        'translate': '🌍 ' + I18N.task_translate,
        'seo': '🔍 ' + I18N.task_seo,
        'builder_blocks': '🧱 ' + I18N.task_builder,
        'generate_form': '📋 ' + I18N.task_form
    };

    document.querySelectorAll('.ai-chip').forEach(function(chip) {
        chip.addEventListener('click', function() {
            var task = chip.dataset.task;
            
            // Toggle active state
            document.querySelectorAll('.ai-chip').forEach(function(c) { c.classList.remove('is-active'); });
            chip.classList.add('is-active');
            
            // Show context indicator
            contextEl.classList.remove('d-none');
            contextLabel.textContent = taskLabels[task] || task;
            
            // Pre-fill input with hint
            inputEl.value = chipHints[task] || '';
            inputEl.focus();
            inputEl.style.height = 'auto';
            inputEl.style.height = Math.min(inputEl.scrollHeight, 300) + 'px';
            
            // Place cursor at end
            inputEl.selectionStart = inputEl.selectionEnd = inputEl.value.length;
        });
    });

    function clearContext() {
        contextEl.classList.add('d-none');
        document.querySelectorAll('.ai-chip').forEach(function(c) { c.classList.remove('is-active'); });
    }
    window.clearContext = clearContext;

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

    // Enter to send (Shift+Enter for newline)
    inputEl.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });

    function addMessage(role, content, resultData) {
        var msg = document.createElement('div');
        msg.className = 'ai-msg ai-msg--' + role;
        
        var avatar = document.createElement('div');
        avatar.className = 'ai-msg__avatar';
        avatar.textContent = role === 'user' ? '👤' : '🤖';
        
        var body = document.createElement('div');
        body.className = 'ai-msg__body';
        
        var text = document.createElement('div');
        text.className = 'ai-msg__text';
        text.innerHTML = content;
        body.appendChild(text);
        
        // Add result block if present
        if (resultData) {
            var block = document.createElement('div');
            block.className = 'ai-result-block';
            
            var header = document.createElement('div');
            header.className = 'ai-result-header';
            header.innerHTML = '<span>' + (resultData.label || I18N.result_label) + '</span>';
            
            var copyBtn = document.createElement('button');
            copyBtn.textContent = '📋 ' + I18N.copy_btn;
            copyBtn.addEventListener('click', function() {
                var copyText = block.querySelector('.ai-result-content').innerText;
                navigator.clipboard.writeText(copyText);
                copyBtn.textContent = '✅ ' + I18N.copied_btn;
                setTimeout(function() { copyBtn.textContent = '📋 ' + I18N.copy_btn; }, 1500);
            });
            header.appendChild(copyBtn);
            
            block.appendChild(header);
            
            var resultContent = document.createElement('div');
            resultContent.className = 'ai-result-content';
            resultContent.innerHTML = resultData.html;
            block.appendChild(resultContent);
            
            body.appendChild(block);
        }
        
        msg.appendChild(avatar);
        msg.appendChild(body);
        messagesEl.appendChild(msg);
        messagesEl.scrollTop = messagesEl.scrollHeight;
        
        return msg;
    }

    function addTypingIndicator() {
        var msg = document.createElement('div');
        msg.className = 'ai-msg ai-msg--assistant';
        msg.id = 'aiTyping';
        msg.innerHTML = '<div class="ai-msg__avatar">🤖</div><div class="ai-msg__body"><div class="ai-typing"><span></span><span></span><span></span></div></div>';
        messagesEl.appendChild(msg);
        messagesEl.scrollTop = messagesEl.scrollHeight;
    }

    function removeTypingIndicator() {
        var el = document.getElementById('aiTyping');
        if (el) el.remove();
    }

    function formatSeoResult(data) {
        var html = '<table>';
        for (var key in data) {
            if (key === 'ai_message') continue;
            html += '<tr><td>' + key + '</td><td>' + escHtml(String(data[key])) + '</td></tr>';
        }
        html += '</table>';
        return html;
    }

    function formatContentResult(data) {
        var html = '<table>';
        if (data.title) html += '<tr><td>' + I18N.label_title + '</td><td>' + escHtml(data.title) + '</td></tr>';
        if (data.excerpt) html += '<tr><td>' + I18N.label_excerpt + '</td><td>' + escHtml(data.excerpt) + '</td></tr>';
        if (data.meta_title) html += '<tr><td>' + I18N.label_meta_title + '</td><td>' + escHtml(data.meta_title) + '</td></tr>';
        if (data.meta_description) html += '<tr><td>' + I18N.label_meta_desc + '</td><td>' + escHtml(data.meta_description) + '</td></tr>';
        html += '</table>';
        if (data.content) {
            html += '<div class="ai-content-preview"><strong>' + I18N.label_content_preview + '</strong><div class="ai-content-preview__body">' + data.content.substring(0, 500) + (data.content.length > 500 ? '...' : '') + '</div></div>';
        }
        return html;
    }

    function escHtml(str) {
        var d = document.createElement('div');
        d.textContent = str;
        return d.innerHTML;
    }

    async function sendMessage() {
        if (isProcessing) return;
        
        var text = inputEl.value.trim();
        if (!text) return;
        
        isProcessing = true;
        sendBtn.disabled = true;
        inputEl.value = '';
        inputEl.style.height = 'auto';
        
        // Add user message
        addMessage('user', escHtml(text));
        
        // Build conversation context
        conversationHistory.push({ role: 'user', text: text });
        var historyStr = conversationHistory.map(function(m) {
            return (m.role === 'user' ? 'User' : 'AI') + ': ' + m.text;
        }).join('\n');
        
        // Show typing
        addTypingIndicator();
        
        try {
            var payload = {
                task: currentTask,
                prompt: text,
                language: languages.length > 0 ? languages[0].name : 'English',
                conversation_history: historyStr.length > 3000 ? historyStr.slice(-3000) : historyStr
            };
            
            // For translate task, pass content directly
            if (currentTask === 'translate') {
                payload.content = text;
            }
            
            var response = await fetch('/admin/ai/generate', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            
            var result = await response.json();
            removeTypingIndicator();
            
            if (result.error) {
                addMessage('assistant', '❌ <strong>' + I18N.error_label + '</strong> ' + escHtml(result.error));
                conversationHistory.push({ role: 'assistant', text: 'Error: ' + result.error });
            } else {
                var aiText = result.result || '';
                var parsed = null;
                
                // Try to parse as JSON
                try {
                    parsed = JSON.parse(aiText.replace(/```json\s*/g, '').replace(/```\s*/g, '').trim());
                } catch(e) {}
                
                if (parsed && typeof parsed === 'object') {
                    // Structured response — auto-detect type from JSON fields
                    var aiMessage = parsed.ai_message || '';
                    var resultData = null;
                    
                    if (parsed.blocks && Array.isArray(parsed.blocks)) {
                        // Builder blocks
                        var blockCount = parsed.blocks.length;
                        resultData = { label: '🧱 ' + I18N.result_builder_blocks + ' (' + blockCount + ')', html: '<pre class="ai-result-pre">' + escHtml(JSON.stringify(parsed.blocks, null, 2)) + '</pre>' };
                    } else if (parsed.fields && Array.isArray(parsed.fields)) {
                        // Form design
                        var fieldCount = parsed.fields.length;
                        var formHtml = '<table>';
                        if (parsed.title) formHtml += '<tr><td>' + I18N.label_title + '</td><td>' + escHtml(parsed.title) + '</td></tr>';
                        if (parsed.description) formHtml += '<tr><td>' + I18N.label_description + '</td><td>' + escHtml(parsed.description) + '</td></tr>';
                        formHtml += '<tr><td>' + I18N.label_fields + '</td><td>' + fieldCount + ' ' + I18N.label_fields_count + '</td></tr>';
                        parsed.fields.forEach(function(f) {
                            formHtml += '<tr><td class="ai-field-sub">' + escHtml(f.type || '') + '</td><td>' + escHtml(f.label || f.name || '') + (f.required ? ' *' : '') + '</td></tr>';
                        });
                        formHtml += '</table>';
                        resultData = { label: '📋 ' + I18N.result_form_design, html: formHtml };
                    } else if (parsed.content && (parsed.meta_title || parsed.meta_description)) {
                        // Full content generation
                        resultData = { label: '📝 ' + I18N.result_generated_content, html: formatContentResult(parsed) };
                    } else if (parsed.meta_title || parsed.meta_description || parsed.og_title) {
                        // SEO fields
                        resultData = { label: '🔍 ' + I18N.result_seo_fields, html: formatSeoResult(parsed) };
                    }
                    
                    var displayText = aiMessage || I18N.result_done;
                    addMessage('assistant', escHtml(displayText), resultData);
                    conversationHistory.push({ role: 'assistant', text: displayText });
                    
                } else {
                    // Plain text response
                    addMessage('assistant', escHtml(aiText).replace(/\n/g, '<br>'));
                    conversationHistory.push({ role: 'assistant', text: aiText.substring(0, 200) });
                }
            }
        } catch(err) {
            removeTypingIndicator();
            addMessage('assistant', '❌ <strong>' + I18N.connection_error + '</strong> ' + escHtml(err.message));
        }
        
        isProcessing = false;
        sendBtn.disabled = false;
        inputEl.focus();
        messageCount++;
        statusEl.textContent = messageCount + ' ' + I18N.messages_count;
    }
    window.sendMessage = sendMessage;
})();
</script>
{% endblock %}
