<div class="container py-4">
    <div class="row g-4">
        <!-- Sidebar: Conversations List -->
        <div class="col-md-4">
            <div class="card border-0 shadow-sm overflow-hidden" style="height: 600px; display: flex; flex-direction: column;">
                <div class="card-header bg-white border-0 py-3">
                    <h5 class="fw-bold font-outfit text-dark m-0"><i class="fa-regular fa-comments text-primary me-2"></i>My Chats</h5>
                </div>
                <div class="list-group list-group-flush flex-grow-1 overflow-y-auto" id="conversations-sidebar-list">
                    <?php if (!empty($conversations)): ?>
                        <?php foreach ($conversations as $conv): ?>
                            <?php
                            $cName = Auth::isStudent()
                                ? $conv['mentor_first'] . ' ' . $conv['mentor_last']
                                : $conv['student_first'] . ' ' . $conv['student_last'];
                            $cAvatar = Auth::isStudent() ? $conv['mentor_avatar'] : $conv['student_avatar'];
                            $isActive = $conv['id'] === $conversation_id;
                            ?>
                            <a href="<?= APP_URL ?>/messages/<?= $conv['id'] ?>" class="list-group-item list-group-item-action border-0 py-3 px-3 d-flex align-items-center justify-content-between <?= $isActive ? 'active bg-light-subtle' : '' ?>">
                                <div class="d-flex align-items-center">
                                    <img src="<?= avatarUrl($cAvatar, $cName) ?>" alt="Avatar" class="avatar-sm rounded-circle me-3">
                                    <div>
                                        <h6 class="fw-bold text-dark mb-1 text-truncate" style="max-width: 150px;"><?= htmlspecialchars($cName) ?></h6>
                                        <small class="text-muted text-xs d-block text-truncate" style="max-width: 180px;"><?= htmlspecialchars($conv['last_message'] ?: 'No messages yet') ?></small>
                                    </div>
                                </div>
                                <div class="text-end">
                                    <?php if ($conv['unread_count'] > 0 && !$isActive): ?>
                                        <span class="badge bg-danger rounded-pill px-2 text-2xs mb-1"><?= $conv['unread_count'] ?></span>
                                    <?php endif; ?>
                                    <small class="text-muted text-3xs d-block"><?= $conv['last_message_at'] ? timeAgo($conv['last_message_at']) : '' ?></small>
                                </div>
                            </a>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Main Chat Pane -->
        <div class="col-md-8">
            <div class="card border-0 shadow-sm overflow-hidden" style="height: 600px; display: flex; flex-direction: column;">
                <?php
                $activeName = Auth::isStudent()
                    ? $active_conv['m_first'] . ' ' . $active_conv['m_last']
                    : $active_conv['s_first'] . ' ' . $active_conv['s_last'];
                $activeAvatar = Auth::isStudent() ? $active_conv['m_avatar'] : $active_conv['s_avatar'];
                ?>
                <!-- Chat Header -->
                <div class="card-header bg-white border-bottom py-3 d-flex align-items-center justify-content-between">
                    <div class="d-flex align-items-center">
                        <img src="<?= avatarUrl($activeAvatar, $activeName) ?>" alt="Avatar" class="avatar-sm rounded-circle me-3">
                        <div>
                            <h6 class="fw-bold text-dark mb-0"><?= htmlspecialchars($activeName) ?></h6>
                            <small class="text-xs text-muted">Active Consultation</small>
                        </div>
                    </div>
                </div>

                <!-- Messages Window -->
                <div class="chat-messages-box p-4 flex-grow-1 overflow-y-auto bg-light-subtle" id="chat-messages-container" style="display: flex; flex-direction: column; gap: 15px;">
                    <?php if (!empty($messages)): ?>
                        <?php foreach ($messages as $msg): ?>
                            <?php
                            $isMe = $msg['sender_id'] === Auth::id();
                            ?>
                            <div class="d-flex <?= $isMe ? 'justify-content-end' : 'justify-content-start' ?>">
                                <div class="chat-bubble p-3 rounded-3 max-w-lg shadow-2xs <?= $isMe ? 'bg-primary text-white rounded-end-0' : 'bg-white text-dark rounded-start-0' ?>" style="max-width: 70%; border-radius: 12px;">
                                    <p class="mb-1 text-sm leading-relaxed" style="white-space: pre-wrap;"><?= htmlspecialchars($msg['body']) ?></p>
                                    <div class="text-end" style="font-size: 0.65rem; opacity: 0.7;">
                                        <?= date('h:i A', strtotime($msg['created_at'])) ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="text-center py-5 text-muted my-auto" id="no-messages-prompt">
                            <i class="fa-regular fa-comments display-6 mb-2"></i>
                            <p class="text-xs">Send a message to open the conversation.</p>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Input Footer -->
                <div class="card-footer bg-white border-top p-3">
                    <form id="chat-form" class="d-flex gap-2">
                        <input type="text" id="chat-input" class="form-control rounded-pill border px-4 text-sm" placeholder="Write a message..." required autocomplete="off">
                        <button type="submit" class="btn btn-primary rounded-circle p-0 d-flex align-items-center justify-content-center" style="width: 44px; height: 44px; flex-shrink: 0;"><i class="fa-solid fa-paper-plane fs-6"></i></button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const chatContainer = document.getElementById('chat-messages-container');
    const chatForm = document.getElementById('chat-form');
    const chatInput = document.getElementById('chat-input');
    const noMsgPrompt = document.getElementById('no-messages-prompt');
    const activeUserId = <?= Auth::id() ?>;

    // Scroll to bottom immediately
    function scrollToBottom() {
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }
    scrollToBottom();

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

        chatInput.value = '';

        const formData = new FormData();
        formData.append('conversation_id', "<?= $conversation_id ?>");
        formData.append('body', body);

        fetch(APP_URL + '/api/messages/send', {
            method: 'POST',
            headers: {
                'X-CSRF-Token': CSRF_TOKEN,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: formData
        })
        .then(res => res.json())
        .then(json => {
            if (json.success && json.message) {
                if (noMsgPrompt) noMsgPrompt.remove();
                
                const msg = json.message;
                const div = document.createElement('div');
                div.className = 'd-flex justify-content-end';
                
                // Parse date
                const timeString = new Date(msg.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
                
                div.innerHTML = `
                    <div class="chat-bubble p-3 rounded-3 shadow-2xs bg-primary text-white rounded-end-0" style="max-width: 70%; border-radius: 12px;">
                        <p class="mb-1 text-sm leading-relaxed" style="white-space: pre-wrap;">${msg.body}</p>
                        <div class="text-end" style="font-size: 0.65rem; opacity: 0.7;">
                            ${timeString}
                        </div>
                    </div>
                `;
                chatContainer.appendChild(div);
                scrollToBottom();
            } else {
                alert('Failed to send message: ' + json.message);
            }
        })
        .catch(err => {
            alert('An error occurred while sending the message.');
            console.error(err);
        });
    });
});
</script>
