<style>
.chat-container {
    display: flex;
    flex-direction: column;
    height: 400px;
    border: 1px solid #ddd;
    border-radius: 8px;
    background-color: #f5f5f5;
    overflow: hidden;
}

.chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 15px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.message {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    margin-bottom: 8px;
    max-width: 80%;
}

.message.own {
    align-items: flex-end;
    margin-left: auto;
}


.message.own .message-bubble {
    background-color: #007bff;
    color: white;
    border-radius: 18px 18px 4px 18px;
}

.message.other .message-bubble {
    background-color: #e9ecef;
    color: #333;
    border-radius: 18px 18px 18px 4px;
}

.message-sender {
    font-size: 12px;
    color: #666;
    margin-bottom: 2px;
    margin-left: 4px;
    font-weight: 500;
}

.message-bubble {
    display: inline-flex;
    align-items: flex-end;
    gap: 6px;
    padding: 6px 14px 20px 14px; 
    line-height: 1.25;
    white-space: pre-wrap;
    position: relative;
}

.message-time {
    position: absolute;
    right: 8px;
    bottom: 2px;
    font-size: 10px;
    line-height: 1;
    white-space: nowrap;
    opacity: 0.6;
}
.message-text {
    display: block;
}

.message.other .message-time {
    left: 8px;
    right: auto;
    bottom: 2px;
}

.message.own .message-time {
    color: #cce0ff;
    right: 8px;
    left: auto;
    bottom: 2px;
}

.chat-input-container {
    border-top: 1px solid #ddd;
    padding: 12px;
    background-color: white;
    display: flex;
    gap: 8px;
}

.chat-input-container form {
    display: flex;
    gap: 8px;
    width: 100%;
}

.chat-input-container textarea {
    flex: 1;
    resize: none;
    border: 1px solid #ddd;
    border-radius: 20px;
    padding: 8px 12px;
    font-size: 14px;
    font-family: inherit;
    max-height: 80px;
}

.chat-input-container button {
    padding: 8px 16px;
    border: none;
    background-color: #007bff;
    color: white;
    border-radius: 20px;
    cursor: pointer;
    transition: background-color 0.2s;
    font-size: 14px;
}

.chat-input-container button:hover {
    background-color: #0056b3;
}

.empty-chat {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #999;
    text-align: center;
}

.message-actions {
    display: none;
    margin-left: 5px;
}

.message:hover .message-actions {
    display: block;
}

.message-delete-btn {
    font-size: 11px;
    color: #999;
    cursor: pointer;
    background: none;
    border: none;
    padding: 0;
}

.message-delete-btn:hover {
    color: #e74c3c;
}
</style>

<div class="chat-container">
    <div class="chat-messages" id="chatMessages">
        <!-- tady se načtou zprávy pře js -->
    </div>

    <div class="chat-input-container">
        <form id="messageForm" onsubmit="sendMessage(event, <?= $team['id'] ?>)">
            <textarea 
                id="messageInput" 
                name="message" 
                placeholder="Napiš zprávu..."
                rows="1"
                required
                style="resize: none;"></textarea>
            <button type="submit">
                <i class="ti ti-send fs-5"></i>
            </button>
        </form>
    </div>
</div>

<script>
const currentUserId = <?= \App\Core\Auth::user()['id'] ?>;

// načte zprávy
document.addEventListener('DOMContentLoaded', function() {
    loadMessages();
    // refreshne po 3 sekundách
    setInterval(loadMessages, 3000);

    const textarea = document.getElementById('messageInput');
    textarea.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = Math.min(this.scrollHeight, 80) + 'px';
    });
});

function loadMessages() {
    fetch('<?= BASE_URL ?>/chat/zpravy?team_id=<?= $team['id'] ?>')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderMessages(data.messages);
            }
        })
        .catch(error => console.error('Chyba při načítání zpráv:', error));
}

function renderMessages(messages) {
    const container = document.getElementById('chatMessages');
    
    if (messages.length === 0) {
        container.innerHTML = '<div class="empty-chat">Zatím zde nejsou žádné zprávy. Buď první, kdo něco napíše!</div>';
        return;
    }

    container.innerHTML = messages.map(msg => {
        const isOwn = msg.uzivatel_id == currentUserId;
        const date = new Date(msg.datum);
        const time = date.toLocaleTimeString('cs-CZ', { hour: '2-digit', minute: '2-digit' });
        const senderName = `${msg.jmeno} ${msg.prijmeni}`;
        return `
            <div class="message ${isOwn ? 'own' : 'other'}">
                ${!isOwn ? `<div class="message-sender">${senderName}</div>` : ''}
                <div class="message-bubble">
                    <span class="message-text">${escapeHtml(msg.obsah)}</span>
                    <span class="message-time">${time}</span>
                </div>
                ${isOwn ? `<div class="message-actions"><button class="message-delete-btn" onclick="deleteMessage(${msg.id})" title="Smazat"><i class="ti ti-trash"></i></button></div>` : ''}
            </div>
        `;
    }).join('');

    // hodí chat dolů
    const chatMessages = document.getElementById('chatMessages');
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

function sendMessage(event, teamId) {
    event.preventDefault();

    const textarea = document.getElementById('messageInput');
    const content = textarea.value.trim();

    if (!content) return;

    fetch('<?= BASE_URL ?>/chat/odeslat', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            team_id: teamId,
            content: content
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            textarea.value = '';
            textarea.style.height = 'auto';
            loadMessages();
        }
    })
    .catch(error => console.error('Chyba při odesílání:', error));
}

function deleteMessage(messageId) {
    if (!confirm('Opravdu smazat zprávu?')) return;

    fetch('<?= BASE_URL ?>/chat/delete', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            message_id: messageId
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            loadMessages();
        }
    })
    .catch(error => console.error('Chyba při mazání:', error));
}

function escapeHtml(text) {
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, m => map[m]);
}
</script>
