<!-- AI Assistant Floating Widget -->
<div id="ai-chatbot-widget">
    <!-- Chat Button -->
    <button id="ai-chat-btn" class="ai-pulse-btn" aria-label="Open AI Assistant">
        <i class="fas fa-sparkles"></i>
    </button>

    <!-- Chat Window -->
    <div id="ai-chat-window" class="ai-glassmorphism d-none">
        
        <div class="ai-chat-header d-flex align-items-center justify-content-between">
            <div class="d-flex align-items-center gap-2">
                <div class="ai-avatar"><i class="fas fa-robot"></i></div>
                <div>
                    <h6 class="mb-0 text-white" style="font-weight:700">SwiftPOS AI</h6>
                    <small class="text-white-50" style="font-size:0.7rem">Assistant</small>
                </div>
            </div>
            <button id="ai-close-btn" class="btn btn-sm text-white"><i class="fas fa-times"></i></button>
        </div>

        <div id="ai-chat-body" class="ai-chat-body">
            <!-- Messages go here -->
            <div class="ai-message ai-bot">
                Hello {{ user.get_full_name|default:user.username }}! Ask me anything about your sales, inventory, or customers.
            </div>
        </div>

        <!-- Prompts / Chips -->
        <div id="ai-prompt-chips" class="ai-prompt-chips px-2 py-1">
            <!-- Injected via JS -->
        </div>

        <div class="ai-chat-footer">
            <form id="ai-chat-form" class="d-flex align-items-center bg-white p-1" style="border-radius: 12px;">
                <input type="text" id="ai-chat-input" class="form-control border-0 shadow-none bg-transparent" placeholder="Ask a question..." autocomplete="off">
                <button type="submit" class="btn btn-primary ai-send-btn p-2 rounded-circle d-flex align-items-center justify-content-center" disabled>
                    <i class="fas fa-paper-plane"></i>
                </button>
            </form>
        </div>
    </div>
</div>

<style>
/* CSS Variables & Keyframes */
:root {
    --ai-primary: #8b5cf6;
    --ai-secondary: #6d28d9;
    --ai-gradient: linear-gradient(135deg, #a78bfa, #8b5cf6);
}

@keyframes aiPulse {
    0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(139, 92, 246, 0.4); }
    70% { transform: scale(1.05); box-shadow: 0 0 0 10px rgba(139, 92, 246, 0); }
    100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(139, 92, 246, 0); }
}

@keyframes aiFadeInUp {
    from { opacity: 0; transform: translateY(20px) scale(0.95); }
    to { opacity: 1; transform: translateY(0) scale(1); }
}

#ai-chatbot-widget {
    position: fixed;
    bottom: 24px;
    right: 24px;
    z-index: 1050;
    font-family: 'Inter', system-ui, sans-serif;
}

.ai-pulse-btn {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background: var(--ai-gradient);
    color: white;
    border: none;
    font-size: 1.5rem;
    cursor: pointer;
    box-shadow: 0 8px 24px rgba(139, 92, 246, 0.4);
    animation: aiPulse 2s infinite;
    transition: transform 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
}

.ai-pulse-btn:hover {
    transform: scale(1.1);
}

.ai-glassmorphism {
    position: absolute;
    bottom: 80px;
    right: 0;
    width: 360px;
    max-width: calc(100vw - 40px);
    height: 550px;
    max-height: calc(100vh - 120px);
    background: rgba(255, 255, 255, 0.85);
    backdrop-filter: blur(16px);
    border: 1px solid rgba(255, 255, 255, 0.5);
    border-radius: 20px;
    box-shadow: 0 20px 40px rgba(0,0,0,0.15), 0 4px 12px rgba(139, 92, 246, 0.2);
    display: flex;
    flex-direction: column;
    overflow: hidden;
    transform-origin: bottom right;
    animation: aiFadeInUp 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;
}

.ai-chat-header {
    background: var(--ai-gradient);
    padding: 16px;
    color: white;
}

.ai-avatar {
    width: 36px;
    height: 36px;
    background: rgba(255,255,255,0.2);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(4px);
}

.ai-chat-body {
    flex-grow: 1;
    padding: 16px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.ai-chat-body::-webkit-scrollbar {
    width: 6px;
}
.ai-chat-body::-webkit-scrollbar-thumb {
    background: rgba(139, 92, 246, 0.3);
    border-radius: 10px;
}

.ai-message {
    max-width: 85%;
    padding: 12px 16px;
    border-radius: 16px;
    font-size: 0.9rem;
    line-height: 1.4;
    word-break: break-word;
}

.ai-message.ai-bot {
    align-self: flex-start;
    background: white;
    color: #1f2937;
    border-bottom-left-radius: 4px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}

.ai-message.ai-user {
    align-self: flex-end;
    background: var(--ai-gradient);
    color: white;
    border-bottom-right-radius: 4px;
    box-shadow: 0 2px 8px rgba(139, 92, 246, 0.2);
}

.ai-prompt-chips {
    white-space: nowrap;
    overflow-x: auto;
    border-top: 1px solid rgba(0,0,0,0.05);
}
.ai-prompt-chips::-webkit-scrollbar { height: 4px; }
.ai-prompt-chips::-webkit-scrollbar-thumb { background: #ddd; border-radius: 4px; }

.ai-chip {
    display: inline-block;
    padding: 6px 12px;
    background: #f3f4f6;
    border-radius: 50px;
    font-size: 0.75rem;
    color: #4b5563;
    margin-right: 8px;
    cursor: pointer;
    border: 1px solid #e5e7eb;
    transition: all 0.2s;
}
.ai-chip:hover {
    background: var(--ai-primary);
    color: white;
    border-color: var(--ai-primary);
}

.ai-typing-indicator {
    display:flex; gap:4px; padding:12px; align-self: flex-start; background: white; border-radius:16px;
}
.ai-dot { width:6px; height:6px; background:#a78bfa; border-radius:50%; animation: aiTyping 1.4s infinite ease-in-out both; }
.ai-dot:nth-child(1) { animation-delay: -0.32s; }
.ai-dot:nth-child(2) { animation-delay: -0.16s; }
@keyframes aiTyping { 0%, 80%, 100% { transform: scale(0); } 40% { transform: scale(1); } }

.ai-chat-footer {
    padding: 12px;
    background: rgba(255,255,255,0.9);
    border-top: 1px solid rgba(0,0,0,0.05);
}

.ai-send-btn {
    background: var(--ai-gradient);
    border: none;
    width: 36px;
    height: 36px;
    transition: transform 0.2s;
}
.ai-send-btn:hover:not([disabled]) {
    transform: scale(1.1);
}
</script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const chatBtn = document.getElementById('ai-chat-btn');
    const chatWindow = document.getElementById('ai-chat-window');
    const closeBtn = document.getElementById('ai-close-btn');
    const chatForm = document.getElementById('ai-chat-form');
    const chatInput = document.getElementById('ai-chat-input');
    const chatBody = document.getElementById('ai-chat-body');
    const sendBtn = chatForm.querySelector('.ai-send-btn');
    const promptChipsContainer = document.getElementById('ai-prompt-chips');

    // Get CSRF dynamically (from Django cookie)
    function getCsrfToken() {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, 10) === ('csrftoken=')) {
                    cookieValue = decodeURIComponent(cookie.substring(10));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // Toggle logic
    chatBtn.addEventListener('click', () => {
        chatWindow.classList.toggle('d-none');
        if(!chatWindow.classList.contains('d-none')){
            chatInput.focus();
            loadPrompts();
        }
    });

    closeBtn.addEventListener('click', () => {
        chatWindow.classList.add('d-none');
    });

    chatInput.addEventListener('input', () => {
        sendBtn.disabled = chatInput.value.trim() === '';
    });

    // Helper: append message
    function appendMessage(text, sender) {
        const div = document.createElement('div');
        div.className = `ai-message ${sender === 'user' ? 'ai-user' : 'ai-bot'}`;
        div.textContent = text;
        chatBody.appendChild(div);
        chatBody.scrollTop = chatBody.scrollHeight;
    }

    function showTyping() {
        const div = document.createElement('div');
        div.className = 'ai-typing-indicator ai-message ai-bot';
        div.id = 'ai-typing';
        div.innerHTML = '<div class="ai-dot"></div><div class="ai-dot"></div><div class="ai-dot"></div>';
        chatBody.appendChild(div);
        chatBody.scrollTop = chatBody.scrollHeight;
    }

    function removeTyping() {
        const typing = document.getElementById('ai-typing');
        if(typing) typing.remove();
    }

    // Load Prompts
    function loadPrompts() {
        if(promptChipsContainer.children.length > 0) return; // already loaded
        fetch('/ai/prompts/')
            .then(res => res.json())
            .then(data => {
                promptChipsContainer.innerHTML = '';
                if(data && data.length) {
                    data.forEach(item => {
                        const chip = document.createElement('span');
                        chip.className = 'ai-chip';
                        chip.textContent = item.text;
                        chip.addEventListener('click', () => {
                            chatInput.value = item.text;
                            chatForm.dispatchEvent(new Event('submit'));
                        });
                        promptChipsContainer.appendChild(chip);
                    });
                } else {
                    promptChipsContainer.innerHTML = '<span class="text-muted" style="font-size:0.75rem;">No shortcuts available</span>';
                }
            })
            .catch(() => console.log('Failed to fetch AI prompts.'));
    }

    // Form submit
    chatForm.addEventListener('submit', function(e) {
        e.preventDefault();
        const text = chatInput.value.trim();
        if(!text) return;

        appendMessage(text, 'user');
        chatInput.value = '';
        sendBtn.disabled = true;
        showTyping();

        fetch('/ai/chat/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCsrfToken()
            },
            body: JSON.stringify({ prompt: text })
        })
        .then(res => {
            if(!res.ok) {
                return res.json().then(data => { throw new Error(data.error || 'Request failed') });
            }
            return res.json();
        })
        .then(data => {
            removeTyping();
            appendMessage(data.response, 'bot');
        })
        .catch(err => {
            removeTyping();
            appendMessage("Error: " + err.message, 'bot');
            // Give it a red-tint if error
            chatBody.lastElementChild.style.color = 'red';
        });
    });
});
</script>
