<div class="box">
    <h1>Messenger</h1>
    <?php $this->renderFeedbackMessages(); ?>

    <meta name="user-id" content="<?= Session::get('user_id') ?>">
    
    <script src="<?= Config::get('URL') ?>public/js/messaging.js"></script>

    <div class="messenger-container">
        <div style="width: 300px;" class="messaging-sidebar">
            <div class="sidebar-section">
                <h3>Channels</h3>
                <div onclick="loadGlobalChat()" class="chat-item" id="global-chat-link">
                    <div class="chat-item-title">
                        <span class="chat-item-icon" style="color: #2196F3;">#</span>
                        <strong>Global Chat</strong>
                    </div>
                    <div class="chat-item-meta">Public chatroom</div>
                </div>
            </div>

            <div class="sidebar-section">
                <h3>Direct Messages</h3>
                <?php if (empty($this->conversations)): ?>
                    <p class="chat-item" style="text-align: center; cursor: default;">No conversations yet</p>
                <?php else: ?>
                    <?php foreach ($this->conversations as $conv): ?>
                        <div onclick="loadConversation(<?= $conv->other_user_id ?>, '<?= htmlspecialchars(addslashes($conv->user_name)) ?>')"
                             class="chat-item"
                             id="conversation-<?= $conv->other_user_id ?>">
                            <div class="chat-item-header">
                                <div class="chat-item-title">
                                    <span class="chat-item-icon" style="color: #4CAF50;">@</span>
                                    <strong><?= htmlspecialchars($conv->user_name) ?></strong>
                                </div>
                                <?php if ($conv->unread_count > 0): ?>
                                    <span class="unread-badge"><?= $conv->unread_count ?></span>
                                <?php endif; ?>
                            </div>
                            <div class="chat-item-meta"><?= date('M j, H:i', strtotime($conv->last_message_time)) ?></div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <div class="sidebar-section">
                <h3>New Message</h3>
                <form action="<?= Config::get('URL') ?>message/send" method="post" id="message-form" class="new-message-form">
                    <select name="receiver_id" required>
                        <option value="">Select user</option>
                        <?php foreach ($this->all_users as $user): ?>
                            <option value="<?= $user->user_id ?>"><?= htmlspecialchars($user->user_name) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <input type="hidden" name="subject" value="Direct Message">
                    <textarea name="message" placeholder="Type your message..." required></textarea>
                    <button type="submit" class="button" style="width: 100%;">Send Message</button>
                </form>
            </div>
        </div>

        <div style="flex: 1;" class="chat-main-area">
            <div id="chat-content">
                <div id="default-state">
                    <div class="default-welcome">
                        <h3>Welcome to Messenger</h3>
                        <p>Select Global Chat or a conversation to start messaging</p>
                        <small>Click on any channel or conversation in the sidebar</small>
                    </div>
                </div>

                <div id="chat-interface">
                    <div id="chat-header">
                        <div id="chat-title"></div>
                        <div id="chat-actions"></div>
                    </div>

                    <div id="messages-container"></div>

                    <div id="message-input-area"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.messenger-container {
    display: flex;
    gap: 20px;
    margin-top: 20px;
    align-items: flex-start;
}

.messaging-sidebar {
    width: 300px;
    flex-shrink: 0;
}

.sidebar-section {
    margin-bottom: 20px;
    padding: 15px;
    background: linear-gradient(135deg, #f8f9fa 0%, #f0f2f5 100%);
    border: 1px solid #e0e0e0;
    border-radius: 8px;
}

.sidebar-section h3 {
    margin: 0 0 15px 0;
    font-size: 14px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: #555;
}

.chat-main-area {
    flex: 1;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    border: 1px solid #e0e0e0;
    background: white;
}

#chat-content {
    height: 600px;
    display: flex;
    flex-direction: column;
}

#default-state {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(180deg, #f5f7fa 0%, #fafbfc 100%);
}

#chat-interface {
    display: none;
    flex-direction: column;
    height: 100%;
}

#chat-header {
    padding: 15px;
    border-bottom: 1px solid #e0e0e0;
    background: linear-gradient(135deg, #f8f9fa 0%, #fff 100%);
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0;
}

#message-input-area {
    padding: 15px;
    border-top: 1px solid #e0e0e0;
    background: linear-gradient(180deg, #fff 0%, #f8f9fa 100%);
    flex-shrink: 0;
}

#messages-container {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: linear-gradient(180deg, #f5f7fa 0%, #fafbfc 100%);
    scroll-behavior: smooth;
}

.chat-item {
    display: block;
    padding: 12px;
    margin-bottom: 8px;
    background: white;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    text-decoration: none;
    color: #333;
    cursor: pointer;
    transition: all 0.2s ease;
}

.chat-item:hover {
    background: #f5f8ff;
    border-color: #2196F3;
    transform: translateX(3px);
}

.chat-item.active {
    background: #e3f2fd;
    border-color: #2196F3;
    box-shadow: 0 2px 4px rgba(33,150,243,0.2);
}

.chat-item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.chat-item-title {
    display: flex;
    align-items: center;
    gap: 8px;
}

.chat-item-icon {
    font-size: 16px;
    width: 24px;
    text-align: center;
}

.unread-badge {
    background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%);
    color: white;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 600;
}

.chat-item-meta {
    font-size: 11px;
    color: #888;
    margin-top: 4px;
}

.message-bubble {
    display: inline-block;
    max-width: 70%;
    padding: 12px 16px;
    border-radius: 18px;
    margin-bottom: 4px;
    word-wrap: break-word;
    line-height: 1.5;
    box-shadow: 0 1px 2px rgba(0,0,0,0.08);
}

.message-bubble.sent {
    background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%);
    color: white;
    border-bottom-right-radius: 6px;
}

.message-bubble.received {
    background: white;
    color: #333;
    border: 1px solid #e8e8e8;
    border-bottom-left-radius: 6px;
}

.message-time {
    font-size: 11px;
    color: #999;
    margin-top: 4px;
}

.message-row {
    margin-bottom: 16px;
    display: flex;
}

.message-row.sent {
    justify-content: flex-end;
}

.message-row.received {
    justify-content: flex-start;
}

.global-message {
    margin-bottom: 16px;
    padding: 16px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
    border: 1px solid #eee;
    transition: transform 0.2s ease;
}

.global-message:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.global-message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
}

.global-message-sender {
    display: flex;
    align-items: center;
    gap: 8px;
}

.sender-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: 600;
    font-size: 14px;
}

.global-message-bubble {
    color: #444;
    line-height: 1.6;
    word-wrap: break-word;
}

.message-input {
    flex: 1;
    padding: 12px 18px;
    border: 2px solid #e0e0e0;
    border-radius: 25px;
    font-size: 14px;
    transition: border-color 0.2s ease, box-shadow 0.2s ease;
}

.message-input:focus {
    outline: none;
    border-color: #2196F3;
    box-shadow: 0 0 0 3px rgba(33,150,243,0.1);
}

.send-button {
    border-radius: 25px;
    padding: 12px 24px;
    font-weight: 600;
    transition: all 0.2s ease;
}

.send-button:hover {
    transform: scale(1.02);
}

.default-welcome {
    text-align: center;
    padding: 80px 20px;
    color: #666;
}

.default-welcome h3 {
    margin: 0 0 12px 0;
    color: #333;
    font-size: 20px;
}

.default-welcome p {
    margin: 0 0 8px 0;
    color: #666;
}

.default-welcome small {
    color: #999;
}

.new-message-form select,
.new-message-form textarea {
    width: 100%;
    padding: 10px 12px;
    margin-bottom: 10px;
    border: 2px solid #e0e0e0;
    border-radius: 8px;
    font-size: 14px;
    box-sizing: border-box;
    transition: border-color 0.2s ease;
}

.new-message-form select:focus,
.new-message-form textarea:focus {
    outline: none;
    border-color: #2196F3;
}

.new-message-form textarea {
    height: 80px;
    resize: vertical;
}

@media (max-width: 768px) {
    .messenger-container {
        flex-direction: column;
    }

    .messaging-sidebar {
        width: 100% !important;
    }

    #chat-content {
        height: 500px;
    }

    .message-bubble {
        max-width: 85%;
    }
}
</style>

<script>
let currentChatType = null;
let currentChatId = null;
let messagePollingInterval = null;
let isFirstLoad = true;

function scrollToBottom() {
    const container = document.getElementById('messages-container');
    if (container) {
        setTimeout(() => {
            container.scrollTop = container.scrollHeight;
        }, 100);
    }
}

document.addEventListener('DOMContentLoaded', function() {
    const hash = window.location.hash.substring(1);

    if (hash === 'load-global') {
        setTimeout(() => loadGlobalChat(), 100);
    } else if (hash.startsWith('load-conversation-')) {
        const userId = hash.split('-')[2];
        if (userId) {
            setTimeout(() => {
                const conversationEl = document.querySelector('#conversation-' + userId);
                if (conversationEl) {
                    const userName = conversationEl.querySelector('strong').textContent;
                    loadConversation(userId, userName);
                }
            }, 100);
        }
    }
});

function loadGlobalChat() {
    currentChatType = 'global';
    currentChatId = 'global';
    isFirstLoad = true;

    document.getElementById('default-state').style.display = 'none';
    document.getElementById('chat-interface').style.display = 'flex';

    document.getElementById('chat-title').innerHTML = `
        <div style="display: flex; align-items: center; gap: 8px;">
            <span style="color: #2196F3; font-size: 18px;">#</span>
            <strong>Global Chat</strong>
        </div>
        <small style="color: #666;">Public chatroom</small>
    `;

    document.getElementById('chat-actions').innerHTML = `
        <span style="font-size: 12px; color: #666;">
            <i class="fa fa-users"></i> Public
        </span>
    `;

    highlightActiveChat('global');
    loadGlobalMessages();
    setTimeout(scrollToBottom, 300);
    setupGlobalMessageInput();
    startMessagePolling();
}

function loadConversation(userId, userName) {
    currentChatType = 'conversation';
    currentChatId = userId;
    isFirstLoad = true;

    document.getElementById('default-state').style.display = 'none';
    document.getElementById('chat-interface').style.display = 'flex';

    document.getElementById('chat-title').innerHTML = `
        <div style="display: flex; align-items: center; gap: 8px;">
            <span style="color: #4CAF50; font-size: 18px;">@</span>
            <strong>${userName}</strong>
        </div>
        <small style="color: #666;">Direct message</small>
    `;

    document.getElementById('chat-actions').innerHTML = `
        <span style="font-size: 12px; color: #666;">
            <i class="fa fa-user"></i> Private
        </span>
    `;

    highlightActiveChat(userId);
    loadConversationMessages(userId);
    setTimeout(scrollToBottom, 300);
    setupConversationMessageInput(userId);
    startMessagePolling();
}

function highlightActiveChat(chatId) {
    document.querySelectorAll('.chat-item').forEach(el => el.classList.remove('active'));

    const activeEl = chatId === 'global' ?
        document.getElementById('global-chat-link') :
        document.getElementById('conversation-' + chatId);

    if (activeEl) activeEl.classList.add('active');
}

function loadGlobalMessages(silent = false) {
    const container = document.getElementById('messages-container');

    if (isFirstLoad && !silent) {
        container.innerHTML = '<div style="text-align: center; padding: 40px; color: #666;">Loading messages...</div>';
    }

    fetch('<?= Config::get('URL') ?>message/getGlobalMessages')
        .then(response => {
            if (!response.ok) throw new Error('HTTP error: ' + response.status);
            return response.json();
        })
        .then(data => {
            if (data.success && data.messages) {
                const wasAtBottom = container.scrollHeight - container.scrollTop <= container.clientHeight + 50;
                displayGlobalMessages(data.messages);
                if (wasAtBottom) scrollToBottom();
                isFirstLoad = false;
            } else if (isFirstLoad) {
                container.innerHTML = '<div style="text-align: center; padding: 40px; color: #f44336;">Error loading messages</div>';
            }
        })
        .catch(error => {
            console.error('Error loading global messages:', error);
            if (isFirstLoad) {
                container.innerHTML = '<div style="text-align: center; padding: 40px; color: #f44336;">Network error</div>';
            }
        });
}

function loadConversationMessages(userId, silent = false) {
    const container = document.getElementById('messages-container');

    if (isFirstLoad && !silent) {
        container.innerHTML = '<div style="text-align: center; padding: 40px; color: #666;">Loading messages...</div>';
    }

    fetch(`<?= Config::get('URL') ?>message/getConversationMessages/${userId}`)
        .then(response => {
            if (!response.ok) throw new Error('HTTP error: ' + response.status);
            return response.json();
        })
        .then(data => {
            if (data.success && data.messages) {
                const wasAtBottom = container.scrollHeight - container.scrollTop <= container.clientHeight + 50;
                displayConversationMessages(data.messages);
                if (wasAtBottom) scrollToBottom();
                isFirstLoad = false;
            } else if (isFirstLoad) {
                container.innerHTML = '<div style="text-align: center; padding: 40px; color: #f44336;">Error loading messages</div>';
            }
        })
        .catch(error => {
            console.error('Error loading conversation messages:', error);
            if (isFirstLoad) {
                container.innerHTML = '<div style="text-align: center; padding: 40px; color: #f44336;">Network error</div>';
            }
        });
}

function displayGlobalMessages(messages) {
    const container = document.getElementById('messages-container');

    if (messages.length === 0) {
        container.innerHTML = `
            <div class="default-welcome">
                <h3>No messages yet</h3>
                <p>Start the conversation!</p>
            </div>
        `;
        return;
    }

    container.innerHTML = messages.map(message => {
        const timeString = new Date(message.created_at).toLocaleString('en-US', {
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });

        const isOwn = message.sender_id == document.querySelector('meta[name="user-id"]').content;
        const initial = message.sender_name.charAt(0).toUpperCase();

        return `
            <div class="global-message">
                <div class="global-message-header">
                    <div class="global-message-sender">
                        <div class="sender-avatar" style="${isOwn ? 'background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%);' : ''}">${initial}</div>
                        <strong style="color: ${isOwn ? '#2196F3' : '#333'}">
                            ${escapeHtml(message.sender_name)}
                        </strong>
                        ${isOwn ? '<span style="font-size: 10px; background: #2196F3; color: white; padding: 2px 6px; border-radius: 4px;">You</span>' : ''}
                    </div>
                    <span class="message-time">${timeString}</span>
                </div>
                <div class="global-message-bubble">
                    ${escapeHtml(message.message)}
                </div>
            </div>
        `;
    }).join('');

    container.scrollTop = container.scrollHeight;
}

function displayConversationMessages(messages) {
    const container = document.getElementById('messages-container');
    const currentUserId = document.querySelector('meta[name="user-id"]').content;

    if (messages.length === 0) {
        container.innerHTML = `
            <div class="default-welcome">
                <h3>No messages yet</h3>
                <p>Send a message to start the conversation!</p>
            </div>
        `;
        return;
    }

    container.innerHTML = messages.map(message => {
        const isSent = message.sender_id == currentUserId;
        const timeString = new Date(message.created_at).toLocaleString('en-US', {
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });

        return `
            <div class="message-row ${isSent ? 'sent' : 'received'}">
                <div>
                    <div class="message-bubble ${isSent ? 'sent' : 'received'}">
                        ${escapeHtml(message.message)}
                    </div>
                    <div class="message-time" style="text-align: ${isSent ? 'right' : 'left'}">
                        ${timeString}
                    </div>
                </div>
            </div>
        `;
    }).join('');

    container.scrollTop = container.scrollHeight;
}

function setupGlobalMessageInput() {
    const inputArea = document.getElementById('message-input-area');
    inputArea.innerHTML = `
        <form id="global-message-form" onsubmit="sendGlobalMessage(event)">
            <div style="display: flex; gap: 10px;">
                <input type="text"
                       name="message"
                       placeholder="Type your global message..."
                       class="message-input"
                       required>
                <button type="submit" class="button send-button">Send</button>
            </div>
        </form>
    `;
}

function setupConversationMessageInput(userId) {
    const inputArea = document.getElementById('message-input-area');
    inputArea.innerHTML = `
        <form id="conversation-message-form" onsubmit="sendConversationMessage(event, ${userId})">
            <div style="display: flex; gap: 10px;">
                <input type="text"
                       name="message"
                       placeholder="Type your message..."
                       class="message-input"
                       required>
                <button type="submit" class="button send-button">Send</button>
            </div>
        </form>
    `;
}

function sendGlobalMessage(event) {
    event.preventDefault();
    const form = event.target;
    const message = form.message.value;
    const submitButton = form.querySelector('button[type="submit"]');
    const originalText = submitButton.textContent;

    submitButton.textContent = 'Sending...';
    submitButton.disabled = true;

    fetch('<?= Config::get('URL') ?>message/sendToGlobal', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: 'message=' + encodeURIComponent(message)
    })
    .then(response => {
        if (!response.ok) throw new Error('HTTP error: ' + response.status);
        return response.json();
    })
    .then(data => {
        if (data.success) {
            form.reset();
            loadGlobalMessages(true);
            setTimeout(scrollToBottom, 300);
        } else {
            alert('Failed to send message: ' + (data.message || 'Unknown error'));
        }
    })
    .catch(error => {
        alert('Network error. Please try again.');
    })
    .finally(() => {
        submitButton.textContent = originalText;
        submitButton.disabled = false;
    });
}

function sendConversationMessage(event, userId) {
    event.preventDefault();
    const form = event.target;
    const message = form.message.value;
    const submitButton = form.querySelector('button[type="submit"]');
    const originalText = submitButton.textContent;

    submitButton.textContent = 'Sending...';
    submitButton.disabled = true;

    fetch('<?= Config::get('URL') ?>message/reply', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: 'receiver_id=' + userId + '&message=' + encodeURIComponent(message)
    })
    .then(response => {
        if (!response.ok) throw new Error('HTTP error: ' + response.status);
        return response.json();
    })
    .then(data => {
        if (data.success) {
            form.reset();
            loadConversationMessages(userId, true);
            setTimeout(scrollToBottom, 300);
        } else {
            alert('Failed to send message: ' + (data.message || 'Unknown error'));
        }
    })
    .catch(error => {
        alert('Network error. Please try again.');
    })
    .finally(() => {
        submitButton.textContent = originalText;
        submitButton.disabled = false;
    });
}

function startMessagePolling() {
    if (messagePollingInterval) clearInterval(messagePollingInterval);

    messagePollingInterval = setInterval(() => {
        if (currentChatType === 'global') {
            loadGlobalMessages(true);
        } else if (currentChatType === 'conversation') {
            loadConversationMessages(currentChatId, true);
        }
    }, 3000);
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

document.getElementById('message-form').addEventListener('submit', function(e) {
    e.preventDefault();

    const formData = new FormData(this);
    const submitButton = this.querySelector('button[type="submit"]');
    const originalText = submitButton.textContent;

    submitButton.textContent = 'Sending...';
    submitButton.disabled = true;

    fetch(this.action, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            this.reset();
            showFeedback('Message sent successfully!', 'success');
        } else {
            showFeedback(data.message || 'Failed to send message', 'error');
        }
    })
    .catch(error => {
        showFeedback('Network error. Please try again.', 'error');
    })
    .finally(() => {
        submitButton.textContent = originalText;
        submitButton.disabled = false;
    });
});

function showFeedback(message, type) {
    const feedback = document.createElement('div');
    feedback.textContent = message;
    feedback.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        background: ${type === 'success' ? '#4caf50' : '#f44336'};
        color: white;
        border-radius: 4px;
        z-index: 1000;
        box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        animation: slideIn 0.3s ease;
    `;

    document.body.appendChild(feedback);

    setTimeout(() => {
        feedback.style.animation = 'slideOut 0.3s ease';
        setTimeout(() => feedback.remove(), 300);
    }, 3000);
}

const animationStyle = document.createElement('style');
animationStyle.textContent = `
    @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    @keyframes slideOut {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
    }
`;
document.head.appendChild(animationStyle);
</script>

<?php $this->render('_templates/footer'); ?>
