@php $aiProvider = site_setting('ai_provider', 'openrouter'); @endphp
<style>
    .ai-fab {
        position: fixed; right: 22px; bottom: 22px; z-index: 1050;
        width: 56px; height: 56px; border-radius: 50%; border: none;
        background: linear-gradient(135deg, var(--loot-green, #22c55e), var(--loot-blue, #86efac));
        color: #06100c; display: flex; align-items: center; justify-content: center;
        box-shadow: 0 10px 30px rgba(0,0,0,.4); cursor: pointer; transition: transform .18s ease;
    }
    .ai-fab:hover { transform: translateY(-2px) scale(1.04); }
    .ai-panel {
        position: fixed; right: 22px; bottom: 90px; z-index: 1050;
        width: min(400px, calc(100vw - 32px)); height: min(560px, calc(100vh - 130px));
        background: var(--loot-surface, #0f1a15); border: 1px solid var(--loot-border, rgba(255,255,255,.09));
        border-radius: 18px; box-shadow: 0 24px 60px rgba(0,0,0,.5);
        display: none; flex-direction: column; overflow: hidden;
    }
    .ai-panel.open { display: flex; animation: aiPop .18s ease; }
    @keyframes aiPop { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: none; } }
    .ai-head { display: flex; align-items: center; gap: 10px; padding: 14px 16px; border-bottom: 1px solid var(--loot-border, rgba(255,255,255,.08)); }
    .ai-head .ai-title { font-weight: 800; color: var(--loot-text, #eafff5); font-size: 14px; }
    .ai-head .ai-sub { color: #9fb6ac; font-size: 11px; }
    .ai-head .ai-close { margin-left: auto; background: none; border: none; color: #9fb6ac; cursor: pointer; }
    .ai-model-row { padding: 8px 12px; border-bottom: 1px solid var(--loot-border, rgba(255,255,255,.08)); }
    .ai-model-row select { width: 100%; background: rgba(255,255,255,.05); border: 1px solid var(--loot-border, rgba(255,255,255,.1)); color: var(--loot-text, #eafff5); border-radius: 8px; padding: 6px 8px; font-size: 12px; }
    .ai-body { flex: 1; overflow-y: auto; padding: 14px; display: flex; flex-direction: column; gap: 10px; }
    .ai-msg { max-width: 88%; padding: 9px 12px; border-radius: 12px; font-size: 13px; line-height: 1.45; white-space: pre-wrap; word-wrap: break-word; }
    .ai-msg.user { align-self: flex-end; background: var(--loot-green, #22c55e); color: #031107; font-weight: 500; }
    .ai-msg.assistant { align-self: flex-start; background: rgba(255,255,255,.06); color: var(--loot-text, #eafff5); }
    .ai-msg.error { align-self: flex-start; background: rgba(255,107,107,.15); color: #ffb0b0; border: 1px solid rgba(255,107,107,.3); }
    .ai-hint { color: #9fb6ac; font-size: 12px; text-align: center; margin: auto 0; }
    .ai-foot { padding: 10px; border-top: 1px solid var(--loot-border, rgba(255,255,255,.08)); display: flex; gap: 8px; }
    .ai-foot textarea { flex: 1; resize: none; background: rgba(255,255,255,.05); border: 1px solid var(--loot-border, rgba(255,255,255,.1)); color: var(--loot-text, #eafff5); border-radius: 10px; padding: 9px 11px; font-size: 13px; max-height: 90px; }
    .ai-foot button { background: var(--loot-green, #22c55e); border: none; color: #031107; border-radius: 10px; padding: 0 14px; font-weight: 800; cursor: pointer; }
    .ai-foot button:disabled { opacity: .5; cursor: default; }
    .ai-typing { align-self: flex-start; color: #9fb6ac; font-size: 12px; }
</style>

<button class="ai-fab" id="aiFab" type="button" title="AI assistant" aria-label="Open AI assistant">
    <i data-feather="message-circle"></i>
</button>

<div class="ai-panel" id="aiPanel" role="dialog" aria-label="AI admin assistant">
    <div class="ai-head">
        <div>
            <div class="ai-title">Admin AI assistant</div>
            <div class="ai-sub">{{ ucfirst($aiProvider) }} · read-only insights</div>
        </div>
        <button class="ai-close" id="aiClose" aria-label="Close">&times;</button>
    </div>
    <div class="ai-model-row">
        <select id="aiModel" aria-label="Model">
            <option value="">Default model ({{ site_setting('ai_model', 'openai/gpt-4o-mini') }})</option>
            @if($aiProvider === 'nvidia')
                <option value="meta/llama-3.1-70b-instruct">meta/llama-3.1-70b-instruct</option>
                <option value="nvidia/llama-3.1-nemotron-70b-instruct">nvidia/llama-3.1-nemotron-70b-instruct</option>
                <option value="mistralai/mixtral-8x22b-instruct-v0.1">mistralai/mixtral-8x22b</option>
            @else
                <option value="openai/gpt-4o-mini">openai/gpt-4o-mini</option>
                <option value="openai/gpt-4o">openai/gpt-4o</option>
                <option value="anthropic/claude-3.5-sonnet">anthropic/claude-3.5-sonnet</option>
                <option value="google/gemini-flash-1.5">google/gemini-flash-1.5</option>
                <option value="meta-llama/llama-3.1-70b-instruct">meta-llama/llama-3.1-70b-instruct</option>
                <option value="deepseek/deepseek-chat">deepseek/deepseek-chat</option>
            @endif
        </select>
    </div>
    <div class="ai-body" id="aiBody">
        <div class="ai-hint">Ask about your users, revenue, pending cashouts, fraud, offers, or how to do something in the admin panel.</div>
    </div>
    <div class="ai-foot">
        <textarea id="aiInput" rows="1" placeholder="Ask the assistant…"></textarea>
        <button id="aiSend" type="button">Send</button>
    </div>
</div>

<script>
    (function () {
        const fab = document.getElementById('aiFab');
        const panel = document.getElementById('aiPanel');
        const closeBtn = document.getElementById('aiClose');
        const body = document.getElementById('aiBody');
        const input = document.getElementById('aiInput');
        const send = document.getElementById('aiSend');
        const modelSel = document.getElementById('aiModel');
        const endpoint = @json(route('admin.ai.chat'));
        const csrf = document.querySelector('meta[name="csrf-token"]').content;
        const history = [];
        let busy = false;

        function toggle(open) {
            panel.classList.toggle('open', open);
            if (open) { input.focus(); if (window.feather) window.feather.replace(); }
        }
        fab.addEventListener('click', () => toggle(!panel.classList.contains('open')));
        closeBtn.addEventListener('click', () => toggle(false));

        function addMsg(role, text) {
            const hint = body.querySelector('.ai-hint');
            if (hint) hint.remove();
            const el = document.createElement('div');
            el.className = 'ai-msg ' + role;
            el.textContent = text;
            body.appendChild(el);
            body.scrollTop = body.scrollHeight;
            return el;
        }

        function autoGrow() { input.style.height = 'auto'; input.style.height = Math.min(90, input.scrollHeight) + 'px'; }
        input.addEventListener('input', autoGrow);

        function sendMessage() {
            const text = input.value.trim();
            if (!text || busy) return;
            busy = true; send.disabled = true;
            addMsg('user', text);
            history.push({ role: 'user', content: text });
            input.value = ''; autoGrow();

            const typing = document.createElement('div');
            typing.className = 'ai-typing'; typing.textContent = 'Thinking…';
            body.appendChild(typing); body.scrollTop = body.scrollHeight;

            fetch(endpoint, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf, 'Accept': 'application/json' },
                body: JSON.stringify({ messages: history.slice(-20), model: modelSel.value || undefined })
            })
                .then(r => r.json().then(d => ({ ok: r.ok, d })))
                .then(({ ok, d }) => {
                    typing.remove();
                    if (ok && d.reply) {
                        addMsg('assistant', d.reply);
                        history.push({ role: 'assistant', content: d.reply });
                    } else {
                        addMsg('error', d.error || 'Something went wrong. Please try again.');
                    }
                })
                .catch(() => { typing.remove(); addMsg('error', 'Network error. Please try again.'); })
                .finally(() => { busy = false; send.disabled = false; input.focus(); });
        }

        send.addEventListener('click', sendMessage);
        input.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }
        });
    })();
</script>
