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

{% block title %}Chat{% endblock %}

{% block content %}
<div class="chat-container">
    <!-- Sidebar -->
    <aside class="chat-sidebar">
        <a href="{% url 'conversation_list' %}" class="new-chat-btn">+ New Chat</a>
        
        <ul class="conversation-list">
            {% for conv in conversation_list %}
                <a href="{% url 'conversation_detail' conv.id %}" class="{% if selected_conversation.id == conv.id %}active{% endif %}">
                    {{ conv.title }}
                </a>
            {% empty %}
                <li>No conversations yet.</li>
            {% endfor %}
        </ul>
    </aside>

    <!-- Main Chat Area -->
    <main class="chat-main">
        {% if selected_conversation %}
            <header class="chat-header">
                <h3>{{ selected_conversation.title }}</h3>
            </header>

            <div class="chat-messages" id="chat-messages">
                {% for message in selected_conversation.messages.all %}
                    <div class="message {{ message.sender_type }}">
                        <div class="message-content">
                            <div class="message-author">{% if message.sender_type == 'user' %}You{% else %}AI{% endif %}</div>
                            <p>{{ message.text }}</p>
                        </div>
                    </div>
                {% endfor %}
            </div>

            <div class="chat-form-container">
                <form method="post" action="{% url 'conversation_detail' selected_conversation.id %}" class="chat-form">
                    {% csrf_token %}
                    <textarea name="text" placeholder="Send a message..." rows="1"></textarea>
                    <button type="submit">Send</button>
                </form>
            </div>

        {% else %}
            <div class="no-conversation-selected">
                <div>
                    <h2>Gemini Chat</h2>
                    <p>Select a conversation or start a new one.</p>
                </div>
            </div>
        {% endif %}
    </main>
</div>

<script>
    // Auto-scroll to the latest message
    const messagesContainer = document.getElementById('chat-messages');
    if (messagesContainer) {
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    // Auto-resize textarea
    const textarea = document.querySelector('.chat-form textarea');
    if (textarea) {
        textarea.addEventListener('input', () => {
            textarea.style.height = 'auto';
            textarea.style.height = (textarea.scrollHeight) + 'px';
        });
    }
</script>

{% endblock %}
