{% extends 'layouts/base.html' %}
{% block extra_css %}
<style>
    .chat-session-item {
        padding: 15px;
        border-bottom: 1px solid #e9ecef;
        cursor: pointer;
        transition: all 0.2s ease;
        border-left: 3px solid transparent;
    }

    .container-fluid {
        background: white;
        padding: 10px;
        border-radius: 13px;
        box-shadow: 0px 0px 3px 0px #80808063;
    }

    .chat-session-item:hover {
        background-color: #f8f9fa;
        border-left-color: #007bff;
    }

    .chat-session-item.active {
        background-color: #e9ecef;
        border-left-color: #0056b3;
    }

    .chat-preview {
        display: flex;
        flex-direction: column;
        gap: 5px;
    }

    .chat-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 5px;
    }

    .chat-date {
        font-size: 0.8em;
        color: #6c757d;
    }

    .chat-last-message {
        font-size: 0.9em;
        color: #495057;
    }

    .message-preview {
        line-height: 1.4;
    }

    .chat-messages-container {
        padding: 0;
        height: calc(100vh - 200px);
    }

    .chat-messages {
        height: 100%;
        overflow-y: auto;
        padding: 20px;
    }

    .message {
        margin: 15px 0;
        max-width: 80%;
    }

    .message.user {
        margin-left: auto;
    }

    .message.assistant {
        margin-right: auto;
    }

    .message-bubble {
        padding: 12px 15px;
        border-radius: 15px;
        position: relative;
    }

    .message.user .message-bubble {
        background-color: #007bff;
        color: white;
    }

    .message.assistant .message-bubble {
        background-color: #f8f9fa;
        border: 1px solid #dee2e6;
    }

    .message-time {
        font-size: 0.75em;
        margin-top: 5px;
        color: #6c757d;
    }

    .message.user .message-time {
        color: rgba(255, 255, 255, 0.8);
    }

    .voice-indicator {
        margin-left: 8px;
        font-size: 0.9em;
    }

    .initial-message {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }

    .message-count {
        font-size: 0.8em;
        color: #6c757d;
        background-color: #e9ecef;
        padding: 2px 8px;
        border-radius: 12px;
    }

    .message-count.badge {
        font-size: 0.8em;
        padding: 0.25em 0.6em;
    }

    .loader-container {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        text-align: center;
    }

    .circular-loader {
        width: 50px;
        height: 50px;
        margin: 0 auto;
        position: relative;
    }

    .loader-circle {
        width: 100%;
        height: 100%;
        border: 4px solid #f3f3f3;
        border-top: 4px solid #3498db;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        position: absolute;
        top: 0;
        left: 0;
    }

    @keyframes spin {
        0% {
            transform: rotate(0deg);
        }

        100% {
            transform: rotate(360deg);
        }
    }

    /* Optional: Add a pulsing effect to the loading text */
    .loader-container .mt-2 {
        animation: pulse 1.5s ease-in-out infinite;
    }

    @keyframes pulse {
        0% {
            opacity: 0.6;
        }

        50% {
            opacity: 1;
        }

        100% {
            opacity: 0.6;
        }
    }
</style>
{% endblock %}
{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-md-4">
            <div class="card">
                <div class="card-header">
                    <h3>Chat Sessions</h3>
                </div>
                <div class="card-body p-0">
                    <div class="chat-sessions-list">
                        {% for session in chat_sessions %}
                        <div class="chat-session-item" data-session-id="{{ session.session_id }}" onclick="void(0)">
                            <div class="chat-preview">
                                <div class="chat-info">
                                    <span class="chat-date">{{ session.last_message_time.strftime('%Y-%m-%d %H:%M')
                                        }}</span>
                                    <span class="message-count badge bg-secondary">{{ session.message_count }}
                                        messages</span>
                                </div>
                                <div class="chat-last-message">
                                    <div class="message-preview">
                                        {% if session.first_message %}
                                        <strong>First Message:</strong> {{ session.first_message[:50] }}
                                        {{ '...' if session.first_message|length > 50 }}
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-8">
            <div class="card">
                <div class="card-header" id="messages-container" style="display: none;">
                    <h5>Chat Messages</h5>
                </div>
                <div class="card-body chat-messages-container">
                    <div id="chat-messages" class="chat-messages">
                        <div class="text-center text-muted initial-message">
                            Select a chat session to view messages
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}



{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function () {
        console.log('DOM loaded');

        const chatMessages = document.getElementById('chat-messages');
        const chatSessions = document.querySelectorAll('.chat-session-item');

        chatSessions.forEach(session => {
            session.style.cursor = 'pointer';
            session.addEventListener('click', async function (e) {
                console.log('Session clicked');

                chatSessions.forEach(s => s.classList.remove('active'));
                session.classList.add('active');

                const sessionId = this.dataset.sessionId;
                console.log('Session ID:', sessionId);

                try {
                    // Show loader
                    chatMessages.innerHTML = `
                        <div class="text-center loader-container">
                            <div class="circular-loader">
                                <div class="loader-circle"></div>
                            </div>
                            <div class="mt-2">Loading messages...</div>
                        </div>
                    `;

                    const timerPromise = new Promise(resolve => setTimeout(resolve, 1000));

                    const response = await fetch(`/company/chat-session/${sessionId}`);
                    const data = await response.json();

                    await timerPromise;

                    if (data.success && data.messages) {
                        document.getElementById('messages-container').style.display = 'block';
                        const messagesHtml = data.messages.map(msg => `
                            <div class="message ${msg.role}">
                                <div class="message-bubble">
                                    <div class="message-content">${msg.content}</div>
                                    <div class="message-time">
                                        ${new Date(msg.created_at).toLocaleString('en-US', {
                            year: 'numeric',
                            month: 'short',
                            day: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit'
                        })}
                                    </div>
                                    ${msg.is_voice_input ? '<span class="voice-indicator"><i class="fas fa-microphone"></i></span>' : ''}
                                </div>
                            </div>
                        `).join('');

                        chatMessages.innerHTML = messagesHtml || '<div class="text-center text-muted">No messages in this chat.</div>';

                        chatMessages.scrollTop = chatMessages.scrollHeight;
                    } else {
                        chatMessages.innerHTML = '<div class="alert alert-danger">Failed to load messages.</div>';
                    }
                } catch (error) {
                    console.error('Error:', error);
                    chatMessages.innerHTML = '<div class="alert alert-danger">Error loading messages.</div>';
                }
            });
        });
    });
</script>
{% endblock %}