// ai_command_bar.js - AI Chat sliding sidebar panel
// Provides an omnipresent AI chat panel accessible from a floating action button (FAB).
// Uses the existing /api/chat endpoint + AiChatSession for persistence.

(function() {
    'use strict';

    let panelEl = null;
    let fabEl = null;
    let isOpen = false;
    let isWaiting = false;
    let commandBarSessionId = null;
    let commandBarMessages = [];
    let commandBarDraftMode = null;  // 'draft' for post/DM generation, null for normal chat

    // ========== FAB ==========

    function createFab() {
        if (fabEl) return;

        const btn = document.createElement('button');
        btn.id = 'aiChatFab';
        btn.className = 'acb-fab';
        btn.title = 'AI Chat';
        btn.innerHTML = getFabIconAI();
        btn.addEventListener('click', function() {
            if (isOpen) {
                lib.hideCommandBar();
            } else {
                lib.showCommandBar();
            }
        });
        document.body.appendChild(btn);
        fabEl = btn;
    }

    function getFabIconAI() {
        return '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="24" height="24"><path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/><path d="M20 3v4"/><path d="M22 5h-4"/></svg>';
    }

    function getFabIconClose() {
        return '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="24" height="24"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
    }

    function updateFabIcon() {
        if (!fabEl) return;
        fabEl.innerHTML = isOpen ? getFabIconClose() : getFabIconAI();
        fabEl.title = isOpen ? 'Close AI Chat' : 'AI Chat';
        // Hide FAB when panel is open to avoid overlapping the send button
        // The panel header already has a close button (×)
        fabEl.style.display = isOpen ? 'none' : '';
    }

    // ========== Panel DOM ==========

    function createPanel() {
        if (panelEl) return;

        const div = document.createElement('div');
        div.id = 'aiChatPanel';
        div.className = 'acb-panel';
        div.innerHTML = `
            <div class="acb-header">
                <div class="acb-header__title">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18" height="18"><path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/><path d="M20 3v4"/><path d="M22 5h-4"/></svg>
                    Ask AI
                </div>
                <div class="acb-header__actions">
                    <a href="/ai-chats.html" class="acb-link" title="Open full AI Chat">Full Chat</a>
                    <button class="acb-close" onclick="lib.hideCommandBar()" title="Close (Esc)">&times;</button>
                </div>
            </div>
            <div class="acb-messages" id="acbMessages">
                <div class="acb-welcome" id="acbWelcome">
                    <div class="acb-welcome__text">Ask anything about your community...</div>
                    <div class="acb-suggestions" id="acbSuggestions">
                        <button class="acb-suggestion" onclick="lib.sendQuickChat('Who are my most active members this week?')">Who are my most active members?</button>
                        <button class="acb-suggestion" onclick="lib.sendQuickChat('Which posts had the most engagement recently?')">Top posts by engagement?</button>
                        <button class="acb-suggestion" onclick="lib.sendQuickChat('Show me new members who joined this week')">New members this week?</button>
                    </div>
                </div>
            </div>
            <div class="acb-input-bar">
                <input type="text" id="acbInput" class="acb-input" placeholder="Ask about your community..." autocomplete="off">
                <button id="acbSendBtn" class="ck-btn ck-btn--primary ck-btn--sm" onclick="lib.sendQuickChat(document.getElementById('acbInput').value)">Send</button>
            </div>
            <div class="acb-footer">
                <span class="acb-footer__hint">Press <kbd>Esc</kbd> to close &middot; <kbd>Enter</kbd> to send</span>
                <a href="/ai-chats.html" class="acb-footer__link" id="acbContinueLink" style="display:none;">Continue in full chat &rarr;</a>
            </div>
        `;
        document.body.appendChild(div);
        panelEl = div;

        const input = document.getElementById('acbInput');
        input.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                lib.sendQuickChat(input.value);
            }
        });

        // Delegated click handler for navigation action buttons
        div.addEventListener('click', function(e) {
            var btn = e.target.closest('.acb-action-nav');
            if (!btn) return;
            var url = btn.getAttribute('data-nav-url');
            if (!url) return;
            var filtersStr = btn.getAttribute('data-nav-filters');
            var filters = null;
            if (filtersStr) { try { filters = JSON.parse(filtersStr); } catch(_) {} }
            lib.navigateWithFilter(url, filters);
        });
    }

    // ========== Show/Hide ==========

    lib.showCommandBar = function(prefillText) {
        createFab();
        createPanel();
        // Force reflow before adding open class for CSS transition
        panelEl.offsetHeight;
        panelEl.classList.add('acb-panel--open');
        isOpen = true;
        updateFabIcon();

        const input = document.getElementById('acbInput');
        if (prefillText) {
            input.value = prefillText;
        }
        setTimeout(function() { input.focus(); }, 50);
    };

    lib.hideCommandBar = function() {
        if (!panelEl) return;
        panelEl.classList.remove('acb-panel--open');
        isOpen = false;
        updateFabIcon();
    };

    // ========== Send Message ==========

    lib.sendQuickChat = async function(text) {
        if (!text || !text.trim() || isWaiting) return;
        const content = text.trim();

        createFab();
        createPanel();
        if (!isOpen) lib.showCommandBar();

        // Hide welcome, show messages
        const welcome = document.getElementById('acbWelcome');
        if (welcome) welcome.style.display = 'none';

        // Auto-create session
        if (!commandBarSessionId) {
            try {
                const session = await AiChatSession.create('Quick Chat');
                commandBarSessionId = session.id;
            } catch (e) {
                console.error('[AI CommandBar] Failed to create session:', e);
                renderQuickError('Failed to create chat session.');
                return;
            }
        }

        // Add user message
        commandBarMessages.push({ role: 'user', content: content });
        renderCommandBarMessages();

        // Clear input
        const input = document.getElementById('acbInput');
        if (input) { input.value = ''; input.focus(); }

        // Show thinking
        isWaiting = true;
        const sendBtn = document.getElementById('acbSendBtn');
        if (sendBtn) sendBtn.disabled = true;
        appendThinking();

        try {
            const apiMessages = commandBarMessages
                .filter(function(m) { return m.role === 'user' || m.role === 'assistant'; })
                .map(function(m) { return { role: m.role, content: m.content }; });

            const res = await fetch('/api/chat', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    messages: apiMessages,
                    session_id: commandBarSessionId
                })
            });

            const data = await res.json();

            const assistantEntry = {
                role: 'assistant',
                content: data.response || data.error || 'No response received.'
            };
            if (data.actions && Array.isArray(data.actions) && data.actions.length > 0) {
                assistantEntry.actions = data.actions;
            }
            commandBarMessages.push(assistantEntry);
        } catch (e) {
            commandBarMessages.push({
                role: 'assistant',
                content: 'Network error: ' + e.message
            });
        } finally {
            isWaiting = false;
            if (sendBtn) sendBtn.disabled = false;
            removeThinking();
            renderCommandBarMessages();

            // Show "continue in full chat" link
            const continueLink = document.getElementById('acbContinueLink');
            if (continueLink && commandBarSessionId) {
                continueLink.href = '/ai-chats.html?session=' + commandBarSessionId;
                continueLink.style.display = '';
            }
        }
    };

    function renderCommandBarMessages() {
        const container = document.getElementById('acbMessages');
        if (!container) return;

        let html = '';
        for (const msg of commandBarMessages) {
            if (msg.role === 'user') {
                html += '<div class="acb-msg acb-msg--user"><div class="acb-bubble acb-bubble--user">' + lib.escapeHtml(msg.displayContent || msg.content) + '</div></div>';
            } else if (msg.role === 'assistant') {
                let bubble = '<div class="acb-msg acb-msg--assistant"><div class="acb-bubble acb-bubble--assistant">' + formatAcbText(msg.content);
                if (msg.actions && msg.actions.length > 0) {
                    bubble += '<div class="acb-actions">';
                    for (var ai = 0; ai < msg.actions.length; ai++) {
                        var action = msg.actions[ai];
                        if (action.type === 'navigate' && action.label && action.url) {
                            bubble += '<button class="acb-action-nav" data-nav-url="' + lib.escapeHtml(action.url) + '"' +
                                (action.filters ? ' data-nav-filters="' + lib.escapeHtml(JSON.stringify(action.filters)) + '"' : '') +
                                '>' +
                                '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="12" height="12"><path d="M5 12h14M12 5l7 7-7 7"/></svg> ' +
                                lib.escapeHtml(action.label) + '</button>';
                        }
                    }
                    bubble += '</div>';
                }
                bubble += '</div></div>';
                html += bubble;
            }
        }
        container.innerHTML = html;
        container.scrollTop = container.scrollHeight;
    }

    function formatAcbText(text) {
        let escaped = lib.escapeHtml(text);
        escaped = escaped.replace(/\*\*(.+?)\*\*/g, '<b>$1</b>');
        escaped = escaped.replace(/`([^`]+)`/g, '<code>$1</code>');
        escaped = escaped.replace(/\n/g, '<br>');
        return escaped;
    }

    function appendThinking() {
        const container = document.getElementById('acbMessages');
        if (!container) return;
        const div = document.createElement('div');
        div.id = 'acbThinking';
        div.className = 'acb-msg acb-msg--assistant';
        div.innerHTML = '<div class="acb-bubble acb-bubble--assistant acb-thinking">Thinking<span class="acb-thinking-dots"></span></div>';
        container.appendChild(div);
        container.scrollTop = container.scrollHeight;
    }

    function removeThinking() {
        const el = document.getElementById('acbThinking');
        if (el) el.remove();
    }

    function renderQuickError(msg) {
        const container = document.getElementById('acbMessages');
        if (!container) return;
        container.innerHTML += '<div class="acb-msg acb-msg--assistant"><div class="acb-bubble acb-bubble--assistant" style="color:var(--color-error);">' + lib.escapeHtml(msg) + '</div></div>';
    }

    // ========== Context-Sensitive Generators ==========

    lib.generateDmSuggestion = async function(memberData) {
        var name = memberData.name || (memberData.first_name + ' ' + (memberData.last_name || '')).trim();
        var skoolId = memberData.skool_id;

        // Open panel and show loading state
        lib.showCommandBar();
        var welcome = document.getElementById('acbWelcome');
        if (welcome) welcome.style.display = 'none';
        appendThinking();

        // Fetch rich context and voice profile in parallel
        var ctx = null;
        var voiceProfile = null;
        var fetches = [];
        if (skoolId) {
            fetches.push(
                fetch('/api/member/dm-context?skool_id=' + encodeURIComponent(skoolId))
                    .then(function(res) { return res.ok ? res.json() : null; })
                    .then(function(data) { ctx = data; })
                    .catch(function(e) { console.warn('[DM Draft] Context fetch failed:', e); })
            );
        }
        fetches.push(
            fetch('/api/content-plan/voice-profile')
                .then(function(res) { return res.ok ? res.json() : null; })
                .then(function(data) { voiceProfile = data; })
                .catch(function(e) { console.warn('[DM Draft] Voice profile fetch failed:', e); })
        );
        await Promise.all(fetches);
        removeThinking();

        // Build prompt with all available context + voice profile
        var prompt = buildDmPrompt(name, memberData, ctx, voiceProfile);
        var displayMsg = 'Draft a personal DM for ' + name;
        if (memberData.outreach_type) displayMsg += ' (' + memberData.outreach_type + ')';

        // Build Skool DM link info
        var skoolInfo = null;
        if (ctx && ctx.community_slug) {
            skoolInfo = { slug: ctx.community_slug, channelId: ctx.channel_id || '' };
        }

        // Send with short display but full context to AI (draft mode = skip system prompt)
        await sendQuickChatWithDisplay(prompt, displayMsg, skoolInfo, true);
    };

    // Send a message where the displayed text differs from the full prompt sent to AI
    // skoolInfo: optional { slug, channelId } for copy+send action bar
    // isDraft: if true, tells backend to skip system prompt (for post/DM generation)
    async function sendQuickChatWithDisplay(fullPrompt, displayText, skoolInfo, isDraft) {
        commandBarDraftMode = isDraft ? 'draft' : null;
        if (isWaiting) return;

        createFab();
        createPanel();
        if (!isOpen) lib.showCommandBar();

        var welcome = document.getElementById('acbWelcome');
        if (welcome) welcome.style.display = 'none';

        if (!commandBarSessionId) {
            try {
                var session = await AiChatSession.create('Quick Chat');
                commandBarSessionId = session.id;
            } catch (e) {
                renderQuickError('Failed to create chat session.');
                return;
            }
        }

        commandBarMessages.push({ role: 'user', content: fullPrompt, displayContent: displayText });
        renderCommandBarMessages();

        var input = document.getElementById('acbInput');
        if (input) { input.value = ''; input.focus(); }

        isWaiting = true;
        var sendBtn = document.getElementById('acbSendBtn');
        if (sendBtn) sendBtn.disabled = true;
        appendThinking();

        try {
            var apiMessages = commandBarMessages
                .filter(function(m) { return m.role === 'user' || m.role === 'assistant'; })
                .map(function(m) { return { role: m.role, content: m.content }; });

            var res = await fetch('/api/chat', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    messages: apiMessages,
                    session_id: commandBarSessionId,
                    mode: commandBarDraftMode || 'chat'
                })
            });

            var data = await res.json();
            var assistantEntry = {
                role: 'assistant',
                content: data.response || data.error || 'No response received.'
            };
            // Skip backend navigate actions for DM drafts (we have our own Skool action bar)
            if (!skoolInfo && data.actions && Array.isArray(data.actions) && data.actions.length > 0) {
                assistantEntry.actions = data.actions;
            }
            commandBarMessages.push(assistantEntry);
        } catch (e) {
            commandBarMessages.push({ role: 'assistant', content: 'Network error: ' + e.message });
        } finally {
            isWaiting = false;
            if (sendBtn) sendBtn.disabled = false;
            removeThinking();
            renderCommandBarMessages();

            // Append action bar after draft generation
            if (commandBarMessages.length > 0) {
                var lastMsg = commandBarMessages[commandBarMessages.length - 1];
                if (lastMsg.role === 'assistant' && lastMsg.content) {
                    if (skoolInfo) {
                        appendDmActionBar(lastMsg.content, skoolInfo);
                    } else if (isDraft) {
                        appendPostCopyBar(lastMsg.content);
                    }
                }
            }

            var continueLink = document.getElementById('acbContinueLink');
            if (continueLink && commandBarSessionId) {
                continueLink.href = '/ai-chats.html?session=' + commandBarSessionId;
                continueLink.style.display = '';
            }
        }
    }

    function appendDmActionBar(dmText, skoolInfo) {
        var container = document.getElementById('acbMessages');
        if (!container) return;

        // Remove existing action bar if any
        var existing = document.getElementById('acbDmActions');
        if (existing) existing.remove();

        var bar = document.createElement('div');
        bar.id = 'acbDmActions';
        bar.className = 'acb-dm-actions';
        bar.innerHTML =
            '<button class="acb-dm-actions__btn acb-dm-actions__btn--copy" onclick="window._acbCopyDm()">' +
                '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">' +
                    '<rect x="9" y="9" width="13" height="13" rx="2"/>' +
                    '<path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/>' +
                '</svg>' +
                ' Copy DM' +
            '</button>';
        container.appendChild(bar);
        container.scrollTop = container.scrollHeight;

        window._acbCopyDm = function() {
            navigator.clipboard.writeText(dmText).then(function() {
                var btn = bar.querySelector('.acb-dm-actions__btn--copy');
                if (btn) {
                    btn.innerHTML =
                        '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">' +
                            '<path d="M20 6L9 17l-5-5"/>' +
                        '</svg>' +
                        ' Copied!';
                    btn.classList.add('acb-dm-actions__btn--success');
                }
                setTimeout(function() {
                    if (btn) {
                        btn.innerHTML =
                            '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">' +
                                '<rect x="9" y="9" width="13" height="13" rx="2"/>' +
                                '<path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/>' +
                            '</svg>' +
                            ' Copy DM';
                        btn.classList.remove('acb-dm-actions__btn--success');
                    }
                }, 2000);
            }).catch(function() {
                prompt('Copy this DM:', dmText);
            });
        };
    }

    function appendPostCopyBar(postText) {
        var container = document.getElementById('acbMessages');
        if (!container) return;

        // Remove existing action bar if any
        var existing = document.getElementById('acbPostActions');
        if (existing) existing.remove();

        var bar = document.createElement('div');
        bar.id = 'acbPostActions';
        bar.className = 'acb-dm-actions';
        bar.innerHTML =
            '<button class="acb-dm-actions__btn acb-dm-actions__btn--copy">' +
                '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">' +
                    '<rect x="9" y="9" width="13" height="13" rx="2"/>' +
                    '<path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/>' +
                '</svg>' +
                ' Copy Post' +
            '</button>';
        container.appendChild(bar);
        container.scrollTop = container.scrollHeight;

        var btn = bar.querySelector('.acb-dm-actions__btn--copy');
        btn.onclick = function() {
            navigator.clipboard.writeText(postText).then(function() {
                btn.innerHTML =
                    '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">' +
                        '<path d="M20 6L9 17l-5-5"/>' +
                    '</svg>' +
                    ' Copied!';
                btn.classList.add('acb-dm-actions__btn--success');
                setTimeout(function() {
                    btn.innerHTML =
                        '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">' +
                            '<rect x="9" y="9" width="13" height="13" rx="2"/>' +
                            '<path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/>' +
                        '</svg>' +
                        ' Copy Post';
                    btn.classList.remove('acb-dm-actions__btn--success');
                }, 2000);
            }).catch(function() {
                prompt('Copy this post:', postText);
            });
        };
    }

    function buildDmPrompt(name, memberData, ctx, voiceProfile) {
        var parts = [];
        parts.push('Draft a short, personal DM from the community owner to ' + name + '.\n');

        // Voice profile - write like the owner
        if (voiceProfile && voiceProfile.has_profile) {
            parts.push(buildVoiceProfileSection(voiceProfile));
            parts.push('');
        }

        // Rich context from backend
        if (ctx && ctx.member_context) {
            parts.push('=== MEMBER PROFILE ===');
            parts.push(ctx.member_context);
        }

        // Churn risk context
        if (ctx && ctx.churn && ctx.churn.score !== undefined && ctx.churn.score !== null) {
            parts.push('=== ENGAGEMENT RISK ===');
            parts.push('Churn score: ' + ctx.churn.score + '/100 (' + ctx.churn.risk_tier + ')');
            parts.push('Activity trend: ' + ctx.churn.trend);
            parts.push('Dominant signal: ' + ctx.churn.dominant_signal);
            if (ctx.churn.loyalty_ratio !== undefined && ctx.churn.loyalty_ratio < 0.3) {
                parts.push('Loyalty ratio: ' + (ctx.churn.loyalty_ratio * 100).toFixed(1) + '% of their Skool activity is here');
            }
        }

        // Top interactions
        if (ctx && ctx.top_interactions && ctx.top_interactions.length > 0) {
            parts.push('=== COMMUNITY CONNECTIONS ===');
            for (var i = 0; i < ctx.top_interactions.length; i++) {
                var ti = ctx.top_interactions[i];
                parts.push('- ' + ti.name + ' (' + ti.total + ' interactions)');
            }
        }

        // Previous outreach history
        if (ctx && ctx.outreach_history && ctx.outreach_history.length > 0) {
            parts.push('=== PREVIOUS OUTREACH ===');
            for (var c = 0; c < ctx.outreach_history.length; c++) {
                var cycle = ctx.outreach_history[c];
                var touchCount = cycle.touches ? cycle.touches.length : 0;
                parts.push('- ' + cycle.outreach_type + ' cycle: ' + cycle.status + ' (' + touchCount + ' touches)');
            }
            parts.push('NOTE: Previous outreach exists. Take a DIFFERENT angle this time.');
        }

        // Outreach type context (from button data)
        var outreachType = memberData.outreach_type || '';
        if (outreachType) {
            parts.push('=== REASON FOR THIS DM ===');
            var reasons = {
                welcome: 'New member welcome - make them feel at home and seen',
                reactivate: 'Was active but went silent - re-engage gently',
                lurker: 'Likes content but never posts - encourage their first contribution',
                cooling: 'Engagement is dropping but still logging in - proactive check-in before they go silent',
                active_elsewhere: 'Active on Skool but not in our community - highlight what makes this community unique'
            };
            parts.push(reasons[outreachType] || outreachType);

            // Add engagement drop details for cooling members
            if (outreachType === 'cooling' && memberData.posts_prior_14d !== undefined) {
                var recent = (memberData.posts_7d || 0) * 3 + (memberData.comments_7d || 0) * 2 + (memberData.likes_given_7d || 0);
                var priorWeekly = ((memberData.posts_prior_14d || 0) * 3 + (memberData.comments_prior_14d || 0) * 2 + (memberData.likes_given_prior_14d || 0)) / 2;
                if (priorWeekly > 0) {
                    var dropPct = Math.round(((priorWeekly - recent) / priorWeekly) * 100);
                    parts.push('Engagement drop: ' + dropPct + '% this week (was ' + Math.round(priorWeekly) + ' weighted actions/wk, now ' + Math.round(recent) + ')');
                    parts.push('Breakdown this week: ' + (memberData.posts_7d || 0) + ' posts, ' + (memberData.comments_7d || 0) + ' comments, ' + (memberData.likes_given_7d || 0) + ' likes');
                    parts.push('Breakdown prior avg/wk: ' + Math.round((memberData.posts_prior_14d || 0) / 2) + ' posts, ' + Math.round((memberData.comments_prior_14d || 0) / 2) + ' comments, ' + Math.round((memberData.likes_given_prior_14d || 0) / 2) + ' likes');
                } else {
                    parts.push('Activity this week: ' + (memberData.posts_7d || 0) + ' posts, ' + (memberData.comments_7d || 0) + ' comments, ' + (memberData.likes_given_7d || 0) + ' likes (no prior baseline available)');
                }
            }
        } else {
            // Fallback context from basic memberData
            if (memberData.inactive_days) {
                parts.push('=== CONTEXT ===');
                parts.push(name + ' has been inactive for ' + memberData.inactive_days + ' days.');
            }
            if (memberData.joined_days_ago) {
                parts.push('=== CONTEXT ===');
                parts.push(name + ' joined ' + memberData.joined_days_ago + ' days ago and hasn\'t posted yet.');
            }
        }

        // Strategy guidance based on dominant churn signal
        parts.push('=== INSTRUCTIONS ===');
        parts.push('Write a short, personal DM (2-3 sentences).');
        parts.push('- Reference something SPECIFIC from their profile, posts, interests, or bio');
        parts.push('- If they have community connections, you can mention shared interests with those people');

        var signal = ctx && ctx.churn ? ctx.churn.dominant_signal : '';
        if (signal && signal !== 'none') {
            var strategies = {
                low_loyalty: '- STRATEGY: Highlight what is unique or exclusive about THIS community',
                activity_decline: '- STRATEGY: Hook with relevant content or discussions they would find valuable',
                social_isolation: '- STRATEGY: Connect them to people in the community they would click with',
                inactivity: '- STRATEGY: Gentle, warm check-in - show you noticed and care',
                tenure_risk: '- STRATEGY: Offer onboarding help, ask what they are looking for',
                no_chat: '- STRATEGY: Invite them to join community discussions or chat'
            };
            if (strategies[signal]) parts.push(strategies[signal]);
        }

        parts.push('- Never mention analytics, scores, data tracking, or that you know their activity patterns');
        parts.push('- Write EXACTLY like the community owner would write a DM - match their tone, vocabulary, sentence structure, and emoji habits from the voice profile above');
        parts.push('- Do NOT sound generic, corporate, or overly polished - sound like a real person writing a quick message');
        parts.push('- Keep it short: 2-3 sentences max, not pushy');
        parts.push('- NEVER use the em dash character (\u2014). Use a normal hyphen (-) or rephrase instead.');

        return parts.join('\n');
    }

    lib.generatePostDraft = async function(context) {
        // Fetch voice profile to match owner's writing style
        var voiceProfile = null;
        try {
            var vpRes = await fetch('/api/content-plan/voice-profile');
            if (vpRes.ok) voiceProfile = await vpRes.json();
        } catch (e) {
            console.warn('[Post Draft] Voice profile fetch failed:', e);
        }

        var parts = [];
        if (voiceProfile && voiceProfile.has_profile) {
            parts.push(buildVoiceProfileSection(voiceProfile));
            parts.push('');
        }
        parts.push('Write a welcome post draft for my community to greet new members.');
        if (context && context.newMemberNames && context.newMemberNames.length > 0) {
            parts.push('New members to welcome: ' + context.newMemberNames.join(', ') + '.');
        }
        parts.push('Keep it warm, friendly, and brief (3-5 sentences). Make each new member feel seen.');
        parts.push('Write in the community owner\'s voice and style as described in the voice profile above.');
        parts.push('');
        parts.push('FORMAT: First line is the post TITLE (max 8-12 words, curiosity-sparking, emojis OK if matching voice profile).');
        parts.push('Then "---" on its own line. Then the post body. End with ONE clear CTA.');

        lib.showCommandBar();
        await lib.sendQuickChat(parts.join('\n'));
    };

    // ========== Content Plan Draft Generation ==========

    function buildVoiceProfileSection(vp) {
        if (!vp || !vp.has_profile) return 'No voice profile available - use a friendly, professional tone.';
        var parts = ['=== COMMUNITY OWNER VOICE PROFILE ==='];
        parts.push('IMPORTANT: Write EXACTLY like this community owner. Match their tone, vocabulary, sentence length, and emoji habits.');
        parts.push('Tone: ' + (vp.tone || 'casual_professional'));
        parts.push('Avg sentence length: ' + (vp.avg_sentence_length || 'unknown') + ' words');
        parts.push('Emoji usage: ' + (vp.emoji_usage || 'moderate'));
        parts.push('Formality: ' + (vp.formality || 0.5) + ' (0=very casual, 1=very formal)');
        if (vp.vocabulary_sample && vp.vocabulary_sample.length > 0) {
            parts.push('');
            parts.push('CHARACTERISTIC PHRASES (use similar vocabulary):');
            for (var i = 0; i < vp.vocabulary_sample.length; i++) {
                parts.push('- "' + vp.vocabulary_sample[i] + '"');
            }
        }
        if (vp.sample_hooks && vp.sample_hooks.length > 0) {
            parts.push('');
            parts.push('EXAMPLE OPENING LINES FROM OWNER (mimic this style):');
            for (var j = 0; j < vp.sample_hooks.length; j++) {
                parts.push('- "' + vp.sample_hooks[j] + '"');
            }
        }
        if (vp.greeting_style) {
            parts.push('Greeting style: "' + vp.greeting_style + '"');
        }
        if (vp.comment_style) {
            parts.push('Comment/reply style: ' + vp.comment_style);
        }
        if (vp.dm_style && vp.dm_style !== 'no data') {
            parts.push('DM style: ' + vp.dm_style);
        }
        if (vp.niche_vocabulary && vp.niche_vocabulary.length > 0) {
            parts.push('');
            parts.push('NICHE VOCABULARY (domain-specific terms they use):');
            parts.push(vp.niche_vocabulary.join(', '));
        }
        if (vp.top_performing_patterns && vp.top_performing_patterns.length > 0) {
            parts.push('');
            parts.push('PATTERNS THAT WORK BEST WITH THIS AUDIENCE (use these):');
            for (var k = 0; k < vp.top_performing_patterns.length; k++) {
                parts.push('- ' + vp.top_performing_patterns[k]);
            }
        }
        if (vp.summary) {
            parts.push('');
            parts.push('WRITING STYLE SUMMARY: ' + vp.summary);
        }
        return parts.join('\n');
    }

    var commonPromptRules = [
        '',
        'OUTPUT FORMAT:',
        '==============',
        'Your response MUST have exactly two parts separated by "---" on its own line:',
        '',
        'TITLE',
        '---',
        'POST BODY',
        '',
        'TITLE RULES (the first line before ---):',
        '- This is what members see in their NOTIFICATION. It decides if they click or ignore.',
        '- Maximum 8-12 words. Shorter is better.',
        '- Must spark curiosity, create urgency, or tease value.',
        '- Use proven patterns: question, bold claim, number, "How I...", "The #1 mistake...", "Stop doing X"',
        '- Do NOT use generic titles like "Weekly Update" or "New Post" - be specific and intriguing.',
        '- Emojis in the title are OK if the voice profile uses them - match the owner\'s style.',
        '',
        'POST BODY RULES (everything after ---):',
        '- Short paragraphs (1-3 sentences max)',
        '- Blank lines between paragraphs',
        '- Bullet points for 3+ items',
        '- 2-5 emojis total, only where they add meaning',
        '- End with exactly ONE clear CTA - one single question or action.',
        '- Do NOT ask multiple questions. Pick the ONE most engaging question.',
        '- The CTA should make it obvious what the member should do (comment, vote, share).',
        '- Suggest a poll with 2-4 options where appropriate.',
        '- 3-5 paragraphs maximum.',
        '',
        'PRIVACY RULES:',
        '- NEVER mention analytics, churn scores, or tracking data',
        '- NEVER label anyone as "lurker", "at-risk", or "inactive"',
        '- NEVER mention which external communities members came from',
        '- NEVER reference DM or chat history',
        '- NEVER reference paying status',
        '- Only reference publicly visible information (names, post titles, bios)',
        '',
        'CRITICAL:',
        '- Write a COMPLETE, ready-to-post draft. Do NOT leave placeholders or blanks for the owner to fill in.',
        '- Do NOT use [PERSONALIZE: ...] markers or any bracketed instructions. The post must be copy-paste ready.',
        '- Write in the community owner\'s EXACT voice and style - match their vocabulary, sentence length, tone, and emoji habits from the voice profile',
        '- Do NOT sound generic or corporate - sound like the actual person behind this community'
    ].join('\n');

    function buildInternalPrompt(ctx) {
        var parts = [];
        var internal = ctx.internal || {};
        var lang = ctx.language || 'en';

        parts.push(buildVoiceProfileSection(ctx.voice_profile));
        parts.push('LANGUAGE: Write the post in ' + (lang === 'de' ? 'German' : 'English') + '.');

        switch (ctx.post_type) {
            case 'welcome': {
                parts.push('POST TYPE: Welcome + Theme Kickoff');
                parts.push('GOAL: Welcome new members by first name, make them feel seen, set the week\'s tone.');
                parts.push('');
                var members = internal.members || [];
                if (members.length > 0) {
                    parts.push('NEW MEMBERS TO WELCOME:');
                    for (var i = 0; i < Math.min(members.length, 10); i++) {
                        var m = members[i];
                        var line = '- ' + m.name + ' (joined ' + m.joined_days_ago + 'd ago)';
                        if (m.bio) line += ' - Bio: ' + m.bio;
                        parts.push(line);
                    }
                }
                parts.push('');
                parts.push('INSTRUCTIONS:');
                parts.push('- Greet each new member by first name');
                parts.push('- If they have a bio, reference one interesting thing about them');
                parts.push('- DO NOT mention where they came from (no external community names)');
                parts.push('- Include a clear first action: "Introduce yourself and tell us [specific question]"');
                parts.push('- Set a theme or question for the week');
                parts.push('- Include a poll related to the week\'s theme');
                break;
            }
            case 'spotlight': {
                parts.push('POST TYPE: Member Spotlight');
                parts.push('GOAL: Celebrate a specific member\'s contribution, make them feel valued, inspire others.');
                parts.push('');
                var topContributors = internal.top_contributors || [];
                var unsungHeroes = internal.unsung_heroes || [];
                if (topContributors.length > 0) {
                    var tc = topContributors[0];
                    parts.push('SPOTLIGHT CANDIDATE:');
                    parts.push('Name: ' + tc.name);
                    parts.push('This week: ' + tc.posts_7d + ' posts, ' + tc.comments_7d + ' comments');
                    if (tc.top_post_title) parts.push('Top post: "' + tc.top_post_title + '"');
                }
                if (unsungHeroes.length > 0) {
                    parts.push('');
                    parts.push('ALTERNATIVE CANDIDATES (Unsung Heroes):');
                    for (var j = 0; j < unsungHeroes.length; j++) {
                        parts.push('- ' + unsungHeroes[j].name + ' (' + unsungHeroes[j].comments_7d + ' comments, ' + unsungHeroes[j].posts_7d + ' posts)');
                    }
                }
                parts.push('');
                parts.push('INSTRUCTIONS:');
                parts.push('- Highlight what this member did specifically (reference a post title or comment)');
                parts.push('- Explain why it matters to the community');
                parts.push('- Extract a lesson for everyone');
                parts.push('- CTA: "Drop some love in the comments" or "Who else has a win to share?"');
                parts.push('- Add a personal observation about this member based on the data provided');
                break;
            }
            case 'engagement': {
                parts.push('POST TYPE: Engagement (Poll / Question)');
                parts.push('GOAL: Maximize comments. Questions > statements. Create a gap that demands a response.');
                parts.push('');
                var topics = internal.trending_topics || [];
                if (topics.length > 0) {
                    parts.push('TRENDING TOPICS IN COMMUNITY:');
                    for (var k = 0; k < topics.length; k++) {
                        parts.push('- "' + topics[k].title + '" (' + topics[k].upvotes + ' upvotes, ' + topics[k].comments + ' comments)');
                    }
                }
                parts.push('');
                parts.push('MEMBER SEGMENTS:');
                parts.push('- ' + (internal.lurker_count || 0) + ' members who like but never post (design low-barrier participation)');
                parts.push('- ' + (internal.active_count || 0) + ' active members (design for deeper discussion)');
                parts.push('');
                parts.push('INSTRUCTIONS:');
                parts.push('- Choose one of: Poll, This-or-That, Fill-in-the-Blank, Hot Take, Open Question');
                parts.push('- Make poll options defensible (no obvious "correct" answer)');
                parts.push('- Keep the prompt short (1-3 sentences + poll)');
                parts.push('- Design so that even lurkers feel comfortable responding (voting is easier than commenting)');
                parts.push('- Topic should connect to what\'s currently being discussed');
                break;
            }
            case 'challenge': {
                parts.push('POST TYPE: Challenge / Behind the Scenes');
                parts.push('GOAL: Drive action and accountability, or build trust through transparency.');
                parts.push('');
                parts.push('Choose ONE approach:');
                parts.push('A) CHALLENGE: A specific, achievable action members can do this week');
                parts.push('B) BEHIND THE SCENES: Transparent sharing, lesson learned, work-in-progress');
                parts.push('');
                parts.push('COMMUNITY CONTEXT:');
                parts.push('- Activity this week: ' + (internal.active_this_week || 0) + ' active members');
                parts.push('- Activity last week: ' + (internal.active_last_week || 0) + ' active members');
                parts.push('- Trend: ' + (internal.activity_trend_pct || 0) + '%');
                var milestones = internal.milestone_members || [];
                if (milestones.length > 0) {
                    parts.push('- Members near milestones: ' + milestones.map(function(m) { return m.name + ' (' + m.points + '/' + m.next_level + ' pts)'; }).join(', '));
                }
                parts.push('');
                parts.push('INSTRUCTIONS FOR CHALLENGE:');
                parts.push('- One clear, specific action (not vague like "work on your goals")');
                parts.push('- Include a check-in mechanism ("Comment DONE when you\'ve completed it")');
                parts.push('- Reference what members have been discussing to make it relevant');
                parts.push('');
                parts.push('INSTRUCTIONS FOR BTS:');
                parts.push('- Write a realistic behind-the-scenes story based on the community context provided');
                parts.push('- Provide a structure: What happened → What you learned → What\'s next');
                parts.push('- Include vulnerability (admitting a mistake or challenge)');
                parts.push('- CTA: "Has this happened to you?" or "What would you have done?"');
                break;
            }
            case 'humor': {
                parts.push('POST TYPE: Humor / Smalltalk / Weekend');
                parts.push('GOAL: Build psychological safety, create community bonding, light and fun.');
                parts.push('');
                parts.push('COMMUNITY STATS FOR FUN CONTENT:');
                parts.push('- Total members: ' + (internal.total_members || 0));
                parts.push('- Total posts: ' + (internal.total_posts || 0));
                if (internal.nearest_milestone > 0) parts.push('- Nearest milestone: ' + internal.nearest_milestone + ' members');
                parts.push('- Month: ' + (internal.current_month || ''));
                parts.push('');
                parts.push('INSTRUCTIONS:');
                parts.push('- Choose one of: Relatable meme text, Absurd hypothetical, Weekend question, Would-you-rather');
                parts.push('- Keep it short (1-3 sentences)');
                parts.push('- Make it niche-relevant to the community\'s topic');
                parts.push('- Keep humor relatable to the community niche, avoid inside jokes');
                parts.push('- This post type is mostly template - owner should heavily edit');
                parts.push('- CTA: Light and fun ("What are your weekend plans?" or "You have to explain [niche] to an alien in 3 words. Go.")');
                break;
            }
        }

        parts.push(commonPromptRules);
        return parts.join('\n');
    }

    lib.generateInternalPostDraft = async function(context) {
        var prompt = buildInternalPrompt(context);
        var displayMsg = 'Generate ' + (context.post_type_label || context.post_type) + ' Post';

        lib.showCommandBar();
        var welcome = document.getElementById('acbWelcome');
        if (welcome) welcome.style.display = 'none';

        await sendQuickChatWithDisplay(prompt, displayMsg, null, true);
    };

    lib.generateExternalPostDraft = async function(context) {
        var lang = context.language || 'en';
        var parts = [];

        parts.push('You are writing a value-first post for an external Skool community. This is NOT your community.');
        parts.push('');
        parts.push('TARGET COMMUNITY:');
        parts.push('Name: ' + (context.community_name || ''));
        parts.push('About: ' + (context.about_summary || 'No description available'));
        parts.push('');
        parts.push('SHARED INTERESTS WITH YOUR COMMUNITY:');
        var interests = context.shared_interests || [];
        if (interests.length > 0) {
            parts.push(interests.join(', '));
        } else {
            parts.push('(none detected)');
        }
        parts.push('');
        parts.push(buildVoiceProfileSection(context.voice_profile));
        parts.push('');
        parts.push('LANGUAGE: Write in ' + (lang === 'de' ? 'German' : 'English') + '.');
        parts.push('');
        parts.push('POST TYPE: Choose the most appropriate:');
        parts.push('1. The Detailed Answer - Thorough, specific answer to a common question in their niche');
        parts.push('2. The "Here\'s My Process" - Share a framework or system, actionable and complete');
        parts.push('3. The Contrarian Insight - Challenge conventional wisdom with your experience');
        parts.push('4. The Story + Lesson - Personal story with extractable lesson');
        parts.push('');
        parts.push('CRITICAL RULES:');
        parts.push('- NEVER include a link to your own community');
        parts.push('- NEVER pitch your product/service/community');
        parts.push('- NEVER say "in my community we..." or "I teach this in my group..."');
        parts.push('- 90% genuine value, 10% subtle positioning through expertise');
        parts.push('- Your profile bio does the selling - the post must only give value');
        parts.push('- Write as a peer, not as a promoter');
        parts.push('- Make the content complete enough to use standalone (don\'t tease)');
        parts.push('- Follow the community\'s likely tone (infer from their about page)');
        parts.push('');
        parts.push('OUTPUT FORMAT:');
        parts.push('Your response MUST have exactly two parts separated by "---" on its own line:');
        parts.push('');
        parts.push('TITLE');
        parts.push('---');
        parts.push('POST BODY');
        parts.push('');
        parts.push('TITLE: Max 8-12 words, spark curiosity. This shows in notifications. Emojis OK if matching voice profile.');
        parts.push('BODY: Hook relevant to THEIR topic, specific actionable content, ONE CTA engaging THEIR community.');
        parts.push('FORMATTING: Short paragraphs, 2-5 emojis max in body, 3-5 paragraphs total.');

        var prompt = parts.join('\n');
        var displayMsg = 'Generate External Post for ' + (context.community_name || 'community');

        lib.showCommandBar();
        var welcome = document.getElementById('acbWelcome');
        if (welcome) welcome.style.display = 'none';

        await sendQuickChatWithDisplay(prompt, displayMsg, null, true);
    };

    lib.generateProfileQuestion = async function(skoolId, memberName) {
        const prompt = 'Tell me everything important about ' + (memberName || 'this member') +
            '. What should I know before reaching out to them? Summarize their activity, interests, and engagement patterns.';

        lib.showCommandBar();
        await lib.sendQuickChat(prompt);
    };

    // ========== Keyboard Shortcut ==========

    lib.initAiCommandBar = function() {
        document.addEventListener('keydown', function(e) {
            // Esc to close
            if (e.key === 'Escape' && isOpen) {
                e.preventDefault();
                lib.hideCommandBar();
            }
        });

        // Inject styles and create FAB
        injectStyles();
        createFab();
    };

    // ========== Styles ==========

    function injectStyles() {
        if (document.getElementById('acbStyles')) return;
        const style = document.createElement('style');
        style.id = 'acbStyles';
        style.textContent = `
            /* ========== Floating Action Button ========== */
            .acb-fab {
                position: fixed;
                bottom: 24px;
                right: 24px;
                z-index: 10001;
                width: 52px;
                height: 52px;
                border-radius: 50%;
                border: none;
                background: var(--brand-primary);
                color: #fff;
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
                box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3), 0 1px 4px rgba(0, 0, 0, 0.2);
                transition: background 0.2s, transform 0.2s, box-shadow 0.2s;
            }
            .acb-fab:hover {
                background: var(--brand-primary-hover, var(--brand-primary));
                transform: scale(1.08);
                box-shadow: 0 6px 20px rgba(0, 0, 0, 0.35), 0 2px 6px rgba(0, 0, 0, 0.2);
            }
            .acb-fab:active {
                transform: scale(0.96);
            }
            .acb-fab svg {
                transition: transform 0.2s;
            }

            /* ========== Sliding Panel ========== */
            .acb-panel {
                position: fixed;
                top: 0;
                right: 0;
                bottom: 0;
                z-index: 10000;
                width: 400px;
                max-width: 100vw;
                background: var(--color-bg-secondary);
                border-left: 1px solid var(--color-border);
                box-shadow: -4px 0 24px rgba(0, 0, 0, 0.25);
                display: flex;
                flex-direction: column;
                transform: translateX(100%);
                transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            }
            .acb-panel--open {
                transform: translateX(0);
            }

            /* Header */
            .acb-header {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: var(--space-3) var(--space-4);
                border-bottom: 1px solid var(--color-border);
                flex-shrink: 0;
            }
            .acb-header__title {
                display: flex;
                align-items: center;
                gap: var(--space-2);
                font-weight: 600;
                font-size: 0.9rem;
                color: var(--color-text-primary);
            }
            .acb-header__title svg {
                color: var(--brand-primary);
            }
            .acb-header__actions {
                display: flex;
                align-items: center;
                gap: var(--space-3);
            }
            .acb-link {
                font-size: 0.75rem;
                color: var(--color-text-secondary);
                text-decoration: none;
            }
            .acb-link:hover {
                color: var(--brand-primary);
            }
            .acb-close {
                background: none;
                border: none;
                color: var(--color-text-secondary);
                font-size: 1.3rem;
                cursor: pointer;
                padding: 0 4px;
                line-height: 1;
            }
            .acb-close:hover {
                color: var(--color-text-primary);
            }

            /* Messages area */
            .acb-messages {
                flex: 1;
                overflow-y: auto;
                padding: var(--space-4);
                min-height: 0;
            }

            /* Welcome */
            .acb-welcome {
                text-align: center;
                padding: var(--space-4) 0;
            }
            .acb-welcome__text {
                color: var(--color-text-secondary);
                font-size: 0.9rem;
                margin-bottom: var(--space-4);
            }
            .acb-suggestions {
                display: flex;
                flex-direction: column;
                gap: var(--space-2);
                align-items: center;
            }
            .acb-suggestion {
                background: var(--color-bg-tertiary);
                border: 1px solid var(--color-border);
                border-radius: var(--radius-sm);
                padding: var(--space-2) var(--space-4);
                color: var(--color-text-primary);
                font-size: 0.8rem;
                cursor: pointer;
                transition: background 0.15s, border-color 0.15s;
                max-width: 100%;
                text-align: left;
            }
            .acb-suggestion:hover {
                background: rgba(var(--brand-primary-rgb), 0.1);
                border-color: var(--brand-primary);
            }

            /* Chat messages */
            .acb-msg {
                margin-bottom: var(--space-3);
            }
            .acb-msg--user {
                display: flex;
                justify-content: flex-end;
            }
            .acb-msg--assistant {
                display: flex;
                justify-content: flex-start;
            }
            .acb-bubble {
                max-width: 85%;
                padding: var(--space-2) var(--space-3);
                border-radius: var(--radius-sm);
                font-size: 0.85rem;
                line-height: 1.5;
                word-break: break-word;
            }
            .acb-bubble--user {
                background: var(--brand-primary);
                color: #fff;
                border-bottom-right-radius: 4px;
            }
            .acb-bubble--assistant {
                background: var(--color-bg-tertiary);
                color: var(--color-text-primary);
                border-bottom-left-radius: 4px;
            }
            .acb-bubble code {
                background: rgba(0,0,0,0.2);
                padding: 1px 4px;
                border-radius: 3px;
                font-size: 0.8rem;
            }

            /* Action buttons in command bar */
            .acb-actions {
                display: flex;
                flex-wrap: wrap;
                gap: 6px;
                margin-top: 8px;
                padding-top: 8px;
                border-top: 1px solid rgba(128,128,128,0.15);
            }
            .acb-action-nav {
                display: inline-flex;
                align-items: center;
                gap: 4px;
                padding: 4px 10px;
                background: rgba(var(--brand-primary-rgb), 0.1);
                border: 1px solid rgba(var(--brand-primary-rgb), 0.25);
                border-radius: var(--radius-sm);
                color: var(--brand-primary);
                font-size: 0.75rem;
                cursor: pointer;
                transition: background 0.15s, border-color 0.15s;
            }
            .acb-action-nav:hover {
                background: rgba(var(--brand-primary-rgb), 0.2);
                border-color: var(--brand-primary);
            }
            .acb-action-nav svg {
                flex-shrink: 0;
            }

            /* Thinking animation */
            .acb-thinking {
                color: var(--color-text-secondary);
                font-style: italic;
            }
            .acb-thinking-dots::after {
                content: '';
                animation: acbDots 1.5s infinite;
            }
            @keyframes acbDots {
                0%   { content: '.'; }
                33%  { content: '..'; }
                66%  { content: '...'; }
            }

            /* Input bar */
            .acb-input-bar {
                display: flex;
                gap: var(--space-2);
                padding: var(--space-3) var(--space-4);
                border-top: 1px solid var(--color-border);
                flex-shrink: 0;
            }
            .acb-input {
                flex: 1;
                background: var(--color-bg-primary);
                border: 1px solid var(--color-border);
                border-radius: var(--radius-sm);
                padding: var(--space-2) var(--space-3);
                color: var(--color-text-primary);
                font-size: 0.85rem;
                outline: none;
            }
            .acb-input:focus {
                border-color: var(--brand-primary);
                box-shadow: 0 0 0 2px rgba(var(--brand-primary-rgb), 0.15);
            }
            .acb-input::placeholder {
                color: var(--color-text-disabled);
            }

            /* Footer */
            .acb-footer {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: var(--space-2) var(--space-4);
                border-top: 1px solid var(--color-border);
                background: var(--color-bg-primary);
                flex-shrink: 0;
            }
            .acb-footer__hint {
                font-size: 0.7rem;
                color: var(--color-text-disabled);
            }
            .acb-footer__hint kbd {
                background: var(--color-bg-tertiary);
                border: 1px solid var(--color-border);
                border-radius: 3px;
                padding: 0 4px;
                font-size: 0.65rem;
                font-family: var(--font-family);
            }
            .acb-footer__link {
                font-size: 0.75rem;
                color: var(--brand-primary);
                text-decoration: none;
            }
            .acb-footer__link:hover {
                text-decoration: underline;
            }

            /* AI action button used on Today and People pages */
            .acb-action-btn {
                display: inline-flex;
                align-items: center;
                gap: 4px;
                padding: 2px 8px;
                background: rgba(var(--brand-primary-rgb), 0.08);
                border: 1px solid rgba(var(--brand-primary-rgb), 0.2);
                border-radius: var(--radius-sm);
                color: var(--brand-primary);
                font-size: 0.7rem;
                font-weight: 500;
                cursor: pointer;
                transition: background 0.15s;
                white-space: nowrap;
            }
            .acb-action-btn:hover {
                background: rgba(var(--brand-primary-rgb), 0.18);
                border-color: var(--brand-primary);
            }
            .acb-action-btn svg {
                width: 12px;
                height: 12px;
            }

            /* DM draft action bar (Copy & Send on Skool) */
            .acb-dm-actions {
                padding: var(--space-2) 0 var(--space-3) 0;
                display: flex;
                justify-content: flex-start;
            }
            .acb-dm-actions__btn {
                display: inline-flex;
                align-items: center;
                gap: 6px;
                padding: 6px 14px;
                background: var(--color-bg-tertiary);
                border: 1px solid var(--color-border);
                border-radius: var(--radius-sm);
                color: var(--color-text-primary);
                font-size: 0.78rem;
                font-weight: 500;
                cursor: pointer;
                transition: background 0.15s, border-color 0.15s, color 0.15s;
            }
            .acb-dm-actions__btn:hover {
                background: rgba(var(--brand-primary-rgb), 0.12);
                border-color: var(--brand-primary);
                color: var(--brand-primary);
            }
            .acb-dm-actions__btn--success {
                background: rgba(34, 197, 94, 0.12);
                border-color: rgba(34, 197, 94, 0.4);
                color: #22c55e;
            }
            .acb-dm-actions__btn svg {
                flex-shrink: 0;
            }
        `;
        document.head.appendChild(style);
    }

})();
