{% extends "core/base.html" %}
{% load static %}
{% block topbar_title %}SwiftPOS AI Assistant{% endblock %}

{% block content %}
<div class="chat-wrapper">
    <div id="ai-chat-window" class="ai-glassmorphism-page d-flex flex-column">
            <div class="ai-chat-header d-flex align-items-center justify-content-between p-3 rounded-top">
                <div class="d-flex align-items-center gap-3">
                    <div class="ai-avatar"><i class="fas fa-robot fs-4"></i></div>
                    <div>
                        <h5 class="mb-0 text-white" style="font-weight:700">SwiftPOS AI Brain</h5>
                        <small class="text-white-50" style="font-size:0.8rem">Connected to {{ request.company.name }} Database</small>
                    </div>
                </div>
                <button class="btn btn-outline-light btn-sm fw-bold shadow-sm" type="button" data-bs-toggle="offcanvas" data-bs-target="#chatHistoryOffcanvas" aria-controls="chatHistoryOffcanvas">
                    <i class="fas fa-history me-1"></i> Admin Log
                </button>
            </div>

            <div id="ai-chat-body" class="ai-chat-body flex-grow-1 p-4">
                <div class="ai-message ai-bot">
                    Hello {{ user.get_full_name|default:user.username }}! I am your AI Assistant. You can ask me questions about your sales, inventory levels, and overall business metrics based on today's data. How can I help you today?
                </div>
            </div>

            <div id="ai-prompt-chips" class="ai-prompt-chips px-4 py-2">
                <!-- Injected via JS -->
                 <span class="text-muted" style="font-size:0.8rem;">Loading prompt shortcuts...</span>
            </div>

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

<!-- History Offcanvas -->
<div class="offcanvas offcanvas-end" tabindex="-1" id="chatHistoryOffcanvas" aria-labelledby="chatHistoryOffcanvasLabel">
  <div class="offcanvas-header bg-light">
    <h5 class="offcanvas-title fw-bold" id="chatHistoryOffcanvasLabel"><i class="fas fa-history text-primary me-2"></i>AI Knowledge Log</h5>
    <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body">
    <div class="text-muted small mb-3">Recent administrative requests to the AI Brain.</div>
    <div class="list-group list-group-flush">
      {% for log in chat_history %}
      <div class="list-group-item bg-transparent px-0 py-3">
          <div class="d-flex w-100 justify-content-between mb-1">
              <strong class="text-dark small">{{ log.user.get_full_name|default:log.user.username }}</strong>
              <small class="text-muted" style="font-size:0.65rem;">{{ log.created_at|date:"M j, g:i A" }}</small>
          </div>
          <div class="bg-primary bg-opacity-10 rounded p-2 mb-2 text-primary small fw-semibold">
              <i class="fas fa-user-circle me-1"></i> {{ log.prompt }}
          </div>
          <div class="bg-light rounded p-3 text-dark history-md-content shadow-sm" style="font-size: 0.85rem; max-height: 250px; overflow-y: auto;">{{ log.response }}</div>
      </div>
      {% empty %}
      <div class="text-center text-muted small py-5">
          <i class="fas fa-comment-slash fs-4 mb-2 d-block"></i> No logs found.
      </div>
      {% endfor %}
    </div>
  </div>
</div>

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

.chat-wrapper {
    height: calc(100vh - 160px); /* Fill space between header and footer */
    display: flex;
    justify-content: center;
}

.ai-glassmorphism-page {
    width: 100%;
    max-width: 900px;
    height: 100%; /* Forces chat window to fill the wrapper */
    background: rgba(255, 255, 255, 0.95);
    border: 1px solid rgba(0, 0, 0, 0.05);
    border-radius: 20px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.05);
    overflow: hidden;
}

.ai-chat-header {
    background: var(--ai-gradient);
    color: white;
    flex-shrink: 0;
}

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

.ai-chat-body {
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 16px;
    background-color: #f9fafb;
    /* Flex grow pushes the input footer to the bottom */
}

.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: 80%;
    padding: 14px 20px;
    border-radius: 18px;
    font-size: 1rem;
    line-height: 1.5;
    word-break: break-word;
}

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

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

.ai-prompt-chips {
    white-space: nowrap;
    overflow-x: auto;
    background-color: white;
    border-bottom: 1px solid #f3f4f6;
}
.ai-prompt-chips::-webkit-scrollbar { height: 4px; }
.ai-prompt-chips::-webkit-scrollbar-thumb { background: #ddd; border-radius: 4px; }

.ai-chip {
    display: inline-block;
    padding: 8px 16px;
    background: #f3f4f6;
    border-radius: 50px;
    font-size: 0.85rem;
    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:6px; padding:16px; align-self: flex-start; background: white; border-radius:18px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.03); border-bottom-left-radius: 4px;
}
.ai-dot { width:8px; height:8px; 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 {
    background: white;
}

.ai-send-btn {
    background: var(--ai-gradient);
    border: none;
    transition: transform 0.2s;
}
.ai-send-btn:hover:not([disabled]) {
    transform: scale(1.05);
}

/* Mobile Responsiveness */
@media (max-width: 767.98px) {
    .chat-wrapper {
        height: calc(100vh - 120px);
        margin: -16px; /* Offset container-fluid padding from base.html */
    }
    .ai-glassmorphism-page {
        border-radius: 0;
        border: none;
        box-shadow: none;
    }
    .ai-message {
        max-width: 90%;
        font-size: 0.95rem;
    }
}
</style>

{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    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;
    }

    // Render history markdown
    document.querySelectorAll('.history-md-content').forEach(el => {
        const raw = el.textContent || el.innerText;
        el.innerHTML = '<div class="text-success small fw-bold mb-2"><i class="fas fa-robot"></i> AI Response:</div>' + marked.parse(raw);
        el.querySelectorAll('table').forEach(tbl => {
            tbl.classList.add('table', 'table-bordered', 'table-sm', 'mt-2', 'small', 'bg-white');
        });
    });

    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'}`;
        if (sender === 'bot') {
            div.innerHTML = marked.parse(text);
            // Quick styling for tables if any
            div.querySelectorAll('table').forEach(tbl => {
                tbl.classList.add('table', 'table-bordered', 'table-sm', 'mt-2', 'small');
            });
            div.querySelectorAll('img').forEach(img => {
                img.classList.add('img-fluid', 'rounded', 'mt-2');
            });
        } else {
            div.textContent = text;
        }
        chatBody.appendChild(div);
        chatBody.scrollTop = chatBody.scrollHeight;
    }

    function showTyping() {
        const div = document.createElement('div');
        div.className = 'ai-typing-indicator';
        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() {
        fetch('{% url "web_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.85rem;">No shortcuts available</span>';
                }
            })
            .catch(() => {
                promptChipsContainer.innerHTML = '<span class="text-muted" style="font-size:0.85rem;">Failed to load shortcuts.</span>';
            });
    }

    loadPrompts();

    // 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('{% url "web_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');
            chatBody.lastElementChild.style.color = '#e11d48'; // red highlight
        });
    });
});
</script>
{% endblock %}
