{% extends "base.html" %}
{% load static %}

{% block content %}
<div class="container mt-4">
    <div class="row align-items-center mb-5 pb-5">
        <div class="col-lg-6">
            <h1 class="display-3 fw-extrabold mb-4 lh-sm">Find your perfect <span class="text-primary">Inventory</span> match.</h1>
            <p class="lead text-secondary mb-5 fs-4">Ask our AI assistant about costs, installment plans, features, and locations to find exactly what you need in seconds.</p>
            <div class="d-flex gap-3">
                <a href="#chat-section" class="btn btn-primary btn-lg px-5">Start Chatting</a>
                <a href="/admin/" class="btn btn-link text-decoration-none text-dark fw-bold px-0">Manage Inventory &rarr;</a>
            </div>
        </div>
        <div class="col-lg-5 offset-lg-1 d-none d-lg-block">
            <div class="glass-card p-5 text-center">
                <div class="py-5">
                    <div class="display-1 text-primary mb-3">📦</div>
                    <h3 class="fw-bold">Smart Filtering</h3>
                    <p class="text-muted">No more endless scrolling. Just talk to the agent.</p>
                </div>
            </div>
        </div>
    </div>

    <div id="chat-section" class="row justify-content-center pt-5">
        <div class="col-lg-8">
            <div class="glass-card shadow-lg p-0 overflow-hidden" style="height: 600px; display: flex; flex-direction: column;">
                <div class="bg-primary text-white p-4">
                    <div class="d-flex align-items-center">
                        <div class="bg-white rounded-circle p-2 me-3" style="width: 48px; height: 48px; display: flex; align-items: center; justify-content: center;">
                            🤖
                        </div>
                        <div>
                            <h5 class="mb-0 fw-bold">Inventory Concierge</h5>
                            <small class="opacity-75">AI Assistant • Online</small>
                        </div>
                    </div>
                </div>
                
                <div id="chat-messages" class="p-4 flex-grow-1 overflow-auto bg-white bg-opacity-50">
                    <div class="chat-bubble bot mb-4">
                        <div class="bg-white p-3 rounded-4 shadow-sm d-inline-block" style="max-width: 80%;">
                            Hello! I can help you find items from our inventory. What are you looking for today? 
                            <br><small class="text-muted mt-2 d-block">Try: "Show me items under $500 with installment options"</small>
                        </div>
                    </div>
                </div>

                <div class="p-4 bg-white border-top">
                    <form id="chat-form" class="d-flex gap-2">
                        {% csrf_token %}
                        <input type="text" id="chat-input" class="form-control form-control-lg rounded-pill border-light-subtle bg-light" placeholder="Type your request here..." autocomplete="off">
                        <button type="submit" class="btn btn-primary rounded-circle p-0" style="width: 54px; height: 54px;">
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-send-fill" viewBox="0 0 16 16">
                                <path d="M15.964.686a.5.5 0 0 0-.65-.65L.767 5.855H.766l-.452.18a.5.5 0 0 0-.082.887l.41.26.001.002 4.995 3.178 3.178 4.995.002.001.26.41a.5.5 0 0 0 .886-.083l6-15Zm-1.833 1.89L6.637 10.07l-.215-.338a.5.5 0 0 0-.154-.154l-.338-.215 7.494-7.494 1.178-.471-.47 1.178Z"/>
                            </svg>
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    .chat-bubble.user {
        text-align: right;
    }
    .chat-bubble.user > div {
        background-color: var(--primary) !important;
        color: white;
    }
    .item-card {
        border-radius: 1rem;
        transition: all 0.2s;
    }
    .item-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0,0,0,0.1) !important;
    }
</style>
{% endblock %}

{% block scripts %}
<script>
    const chatForm = document.getElementById('chat-form');
    const chatInput = document.getElementById('chat-input');
    const chatMessages = document.getElementById('chat-messages');

    function addMessage(text, type = 'bot', items = []) {
        const div = document.createElement('div');
        div.className = `chat-bubble ${type} mb-4 animate__animated animate__fadeInUp`;
        
        let html = `
            <div class="${type === 'user' ? 'bg-primary text-white' : 'bg-white'} p-3 rounded-4 shadow-sm d-inline-block" style="max-width: 85%;">
                ${text}
            </div>
        `;

        if (items.length > 0) {
            html += `<div class="row g-3 mt-2">`;
            items.forEach(item => {
                html += `
                    <div class="col-sm-6">
                        <div class="card item-card border-0 shadow-sm h-100 p-3 bg-white">
                            <h6 class="fw-bold mb-1">${item.name}</h6>
                            <div class="text-primary fw-bold mb-2">$${item.cost}</div>
                            <small class="text-muted d-block mb-1">📍 ${item.store} (${item.location})</small>
                            <small class="text-muted d-block mb-1">💳 ${item.installments}</small>
                            <small class="text-muted d-block">🚚 Lead time: ${item.lead_time}</small>
                        </div>
                    </div>
                `;
            });
            html += `</div>`;
        }

        div.innerHTML = html;
        chatMessages.appendChild(div);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    chatForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const message = chatInput.value.trim();
        if (!message) return;

        addMessage(message, 'user');
        chatInput.value = '';

        try {
            const response = await fetch('/api/chat/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                },
                body: json.stringify({ message })
            });

            const data = await response.json();
            if (data.reply) {
                addMessage(data.reply, 'bot', data.items || []);
            }
        } catch (error) {
            console.error('Error:', error);
            addMessage('Sorry, I encountered an error. Please try again later.', 'bot');
        }
    });
</script>
{% endblock %}
