

<?php $__env->startSection('title', $room->name); ?>

<?php $__env->startSection('styles'); ?>
<style>
.chat-wrapper {
    max-width: 900px;
    margin: 0 auto;
    padding: 20px 16px 32px;
}
.chat-card {
    background: white;
    border: 1px solid #e5e7eb;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 4px 24px rgba(0,0,0,0.07);
    display: flex;
    flex-direction: column;
    height: 600px;
}
.chat-messages-area {
    flex: 1;
    overflow-y: auto;
    padding: 24px;
    background: #f8fafc;
    display: flex;
    flex-direction: column;
    gap: 4px;
}
.chat-messages-area::-webkit-scrollbar {
    width: 6px;
}
.chat-messages-area::-webkit-scrollbar-track {
    background: transparent;
}
.chat-messages-area::-webkit-scrollbar-thumb {
    background: #d1d5db;
    border-radius: 10px;
}
.chat-msg {
    display: flex;
    gap: 10px;
    margin-bottom: 12px;
    animation: fadeSlideIn 0.2s ease;
}
.chat-msg.own {
    flex-direction: row-reverse;
}
.chat-msg-avatar {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    flex-shrink: 0;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.chat-msg-body {
    max-width: 60%;
}
.chat-msg-meta {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-bottom: 5px;
    font-size: 12px;
}
.chat-msg.own .chat-msg-meta {
    justify-content: flex-end;
}
.chat-msg-name {
    font-weight: 600;
    color: #374151;
}
.chat-msg-time {
    color: #9ca3af;
}
.chat-msg-bubble {
    padding: 11px 16px;
    border-radius: 18px;
    border-bottom-left-radius: 5px;
    background: white;
    border: 1px solid #e5e7eb;
    font-size: 14px;
    line-height: 1.55;
    color: #374151;
    word-break: break-word;
    box-shadow: 0 1px 2px rgba(0,0,0,0.04);
}
.chat-msg.own .chat-msg-bubble {
    background: linear-gradient(135deg, #1e40af, #2563eb);
    color: white;
    border-color: transparent;
    border-bottom-left-radius: 18px;
    border-bottom-right-radius: 5px;
    box-shadow: 0 2px 8px rgba(30,64,175,0.2);
}
.chat-msg.bot .chat-msg-bubble {
    background: linear-gradient(135deg, #0891b2, #06b6d4);
    color: white;
    border-color: transparent;
    box-shadow: 0 2px 8px rgba(8,145,178,0.2);
}
.chat-msg.bot .chat-msg-name {
    color: #0891b2;
    font-weight: 700;
}
.chat-msg.flagged .chat-msg-bubble {
    border-left: 3px solid #f59e0b;
    opacity: 0.95;
}
.chat-msg-actions {
    margin-top: 4px;
    opacity: 0;
    transition: opacity 0.2s;
}
.chat-msg:hover .chat-msg-actions {
    opacity: 1;
}
.chat-msg-del-btn {
    background: none;
    border: none;
    color: #9ca3af;
    cursor: pointer;
    font-size: 11px;
    padding: 0;
}
.chat-msg-del-btn:hover {
    color: #dc2626;
}
.chat-input-wrapper {
    padding: 16px 20px;
    background: white;
    border-top: 1px solid #f3f4f6;
    display: flex;
    gap: 10px;
    align-items: flex-end;
}
.chat-textarea {
    flex: 1;
    padding: 12px 16px;
    border: 1.5px solid #e5e7eb;
    border-radius: 14px;
    font-size: 14px;
    resize: none;
    min-height: 48px;
    max-height: 120px;
    font-family: inherit;
    color: #374151;
    transition: border-color 0.2s, box-shadow 0.2s;
    background: #f9fafb;
    line-height: 1.5;
}
.chat-textarea:focus {
    outline: none;
    border-color: #1e40af;
    background: white;
    box-shadow: 0 0 0 3px rgba(30,64,175,0.08);
}
.chat-send-btn {
    background: linear-gradient(135deg, #1e40af, #2563eb);
    color: white;
    border: none;
    padding: 12px 22px;
    border-radius: 14px;
    font-weight: 600;
    cursor: pointer;
    min-height: 48px;
    font-size: 14px;
    box-shadow: 0 2px 8px rgba(30,64,175,0.25);
    transition: all 0.2s;
    display: flex;
    align-items: center;
    gap: 6px;
}
.chat-send-btn:hover:not(:disabled) {
    transform: translateY(-1px);
    box-shadow: 0 4px 14px rgba(30,64,175,0.35);
}
.chat-send-btn:disabled {
    background: #d1d5db;
    box-shadow: none;
    cursor: not-allowed;
    transform: none;
}
.empty-chat {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #9ca3af;
    gap: 12px;
}
@keyframes fadeSlideIn {
    from { opacity: 0; transform: translateY(8px); }
    to { opacity: 1; transform: translateY(0); }
}

/* Chat page header */
.chat-page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 12px;
}
.chat-page-header-left { flex: 1; min-width: 0; }
.chat-back-link {
    color: #6b7280;
    text-decoration: none;
    font-size: 13px;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    margin-bottom: 6px;
    transition: color 0.15s;
}
.chat-back-link:hover { color: #374151; }
.chat-room-title {
    font-size: 22px;
    font-weight: 700;
    color: #111827;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
}
.chat-room-desc {
    color: #6b7280;
    font-size: 13px;
    margin: 4px 0 0;
}
.chat-admin-actions {
    display: flex;
    gap: 12px;
    align-items: center;
}
.chat-admin-edit {
    color: #1e40af;
    text-decoration: none;
    font-size: 13px;
    font-weight: 600;
    transition: color 0.15s;
}
.chat-admin-edit:hover { color: #1e3a8a; }
.chat-admin-delete {
    background: none;
    border: none;
    color: #dc2626;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    padding: 0;
    transition: color 0.15s;
}
.chat-admin-delete:hover { color: #b91c1c; }
.chat-guest-notice {
    background: #fef9ec;
    border: 1px solid #fde68a;
    color: #78350f;
    padding: 12px 18px;
    border-radius: 10px;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 14px;
}
.chat-guest-notice a {
    color: #1e40af;
    font-weight: 600;
    text-decoration: none;
}
.chat-guest-notice a:hover { text-decoration: underline; }
.chat-guest-footer {
    padding: 24px;
    text-align: center;
    background: white;
    border-top: 1px solid #f3f4f6;
}
.chat-guest-footer p {
    color: #6b7280;
    font-size: 14px;
    margin-bottom: 14px;
}
.chat-guest-login {
    background: linear-gradient(135deg, #1e40af, #2563eb);
    color: white;
    padding: 10px 24px;
    border-radius: 10px;
    text-decoration: none;
    font-weight: 600;
    font-size: 14px;
    box-shadow: 0 2px 8px rgba(30,64,175,0.25);
    display: inline-block;
    transition: all 0.2s;
}
.chat-guest-login:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 14px rgba(30,64,175,0.35);
}

@media (max-width: 640px) {
    .chat-wrapper { padding: 12px 12px 24px; }
    .chat-card { height: 520px; }
    .chat-msg-body { max-width: 80%; }
    .chat-room-title { font-size: 18px; }
    .chat-send-btn span { display: none; }
    .chat-send-btn { padding: 12px 16px; }
}
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div class="chat-wrapper">

    
    <div class="chat-page-header">
        <div class="chat-page-header-left">
            <a href="<?php echo e(route('chat.index')); ?>" class="chat-back-link">← Sohbet Odaları</a>
            <h1 class="chat-room-title">💬 <?php echo e($room->name); ?></h1>
            <?php if($room->description): ?>
                <p class="chat-room-desc"><?php echo e($room->description); ?></p>
            <?php endif; ?>
        </div>
        <?php if(auth()->check() && auth()->user()->isAdmin()): ?>
            <div class="chat-admin-actions">
                <a href="<?php echo e(route('chat.edit', $room)); ?>" class="chat-admin-edit">Düzenle</a>
                <form action="<?php echo e(route('chat.destroy', $room)); ?>" method="POST" onsubmit="return confirm('Bu odayı silmek istediğinizden emin misiniz?');">
                    <?php echo csrf_field(); ?>
                    <?php echo method_field('DELETE'); ?>
                    <button type="submit" class="chat-admin-delete">Sil</button>
                </form>
            </div>
        <?php endif; ?>
    </div>

    <?php if(!auth()->check()): ?>
        <div class="chat-guest-notice">
            🔒
            <div>
                Mesaj göndermek için
                <a href="<?php echo e(route('login')); ?>">giriş yap</a> veya
                <a href="<?php echo e(route('register')); ?>">üye ol</a>
            </div>
        </div>
    <?php endif; ?>

    
    <div class="chat-card">

        
        <div class="chat-messages-area" id="chatMessages">
            <?php if($messages->count()): ?>
                <?php $__currentLoopData = $messages; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $message): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <?php
                        $isOwn = auth()->check() && $message->user_id === auth()->id();
                        $isBot = $message->is_bot_message ?? false;
                        $isFlagged = $message->is_flagged ?? false;
                    ?>
                    <div class="chat-msg <?php echo e($isOwn ? 'own' : ''); ?> <?php echo e($isBot ? 'bot' : ''); ?> <?php echo e($isFlagged ? 'flagged' : ''); ?>" data-message-id="<?php echo e($message->id); ?>">
                        <?php if($isBot): ?>
                            <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 36 36'%3E%3Crect fill='%2306b6d4' width='36' height='36'/%3E%3Ctext x='50%25' y='50%25' font-size='20' text-anchor='middle' dominant-baseline='middle' fill='white' font-family='system-ui'%3E🤖%3C/text%3E%3C/svg%3E"
                                 alt="<?php echo e($message->user_name); ?>"
                                 class="chat-msg-avatar">
                        <?php else: ?>
                            <img src="<?php echo e($message->user?->avatar_url ?? 'https://ui-avatars.com/api/?name=' . urlencode($message->user_name) . '&background=1e40af&color=fff&bold=true&size=36'); ?>"
                                 alt="<?php echo e($message->user_name); ?>"
                                 class="chat-msg-avatar">
                        <?php endif; ?>
                        <div class="chat-msg-body">
                            <div class="chat-msg-meta">
                                <span class="chat-msg-name"><?php echo e($message->user_name); ?></span>
                                <span class="chat-msg-time"><?php echo e($message->created_at->format('H:i')); ?></span>
                            </div>
                            <div class="chat-msg-bubble"
                                 <?php if(auth()->check() && auth()->user()->isAdmin() && $message->is_flagged && $message->original_message): ?>
                                    data-original="<?php echo e($message->original_message); ?>"
                                 <?php endif; ?>>
                                <?php if($message->is_bot_message ?? false): ?>
                                    <?php echo $message->message; ?>

                                <?php else: ?>
                                    <?php echo e($message->message); ?>

                                <?php endif; ?>
                                <?php if(auth()->check() && auth()->user()->isAdmin() && $message->is_flagged && $message->original_message): ?>
                                    <div style="font-size: 11px; color: #f59e0b; margin-top: 6px; border-top: 1px solid #f59e0b; padding-top: 4px;">
                                        📝 Orijinal: <?php echo e(Str::limit($message->original_message, 80)); ?>

                                    </div>
                                <?php endif; ?>
                            </div>
                            <?php if($isFlagged && !auth()->user()?->isAdmin()): ?>
                                <div style="font-size: 10px; color: #f59e0b; margin-top: 4px;">⚠️ İçerik Kontrol Edilmiştir</div>
                            <?php endif; ?>
                            <?php if(auth()->check() && ($message->user_id === auth()->id() || auth()->user()->isAdmin()) && !$isBot): ?>
                                <div class="chat-msg-actions <?php echo e($isOwn ? 'text-right' : ''); ?>">
                                    <button class="chat-msg-del-btn" onclick="deleteMessage(<?php echo e($message->id); ?>)">🗑 Sil</button>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            <?php else: ?>
                <div class="empty-chat">
                    <div style="font-size: 48px;">💬</div>
                    <p style="font-size: 15px;">Henüz mesaj yok. İlk mesajı siz gönderin!</p>
                </div>
            <?php endif; ?>
        </div>

        
        <?php if(auth()->check()): ?>
            <form class="chat-input-wrapper" id="chatForm">
                <?php echo csrf_field(); ?>
                <textarea
                    class="chat-textarea"
                    id="messageInput"
                    placeholder="Bir şeyler yazın..."
                    rows="1"
                    maxlength="500"
                    required
                ></textarea>
                <button type="submit" class="chat-send-btn" id="sendBtn">
                    <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/>
                    </svg>
                    Gönder
                </button>
            </form>
        <?php else: ?>
            <div class="chat-guest-footer">
                <p>Sohbete katılmak için giriş yapın</p>
                <a href="<?php echo e(route('login')); ?>" class="chat-guest-login">Giriş Yap</a>
            </div>
        <?php endif; ?>

    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script>
    const currentUserId = <?php echo e(auth()->check() ? auth()->id() : 'null'); ?>;
    let lastMessageId = <?php echo e($messages->last()?->id ?? 0); ?>;

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

        messageInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                document.getElementById('chatForm').dispatchEvent(new Event('submit'));
            }
        });

        document.getElementById('chatForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            const message = messageInput.value.trim();
            if (!message) return;

            const sendBtn = document.getElementById('sendBtn');
            sendBtn.disabled = true;

            try {
                const roomSlug = '<?php echo e($room->slug); ?>';
                const sendUrl = '<?php echo e(url("/sohbet/" . $room->slug . "/mesaj-gonder")); ?>';
                const response = await fetch(sendUrl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({ message })
                });

                // 419 CSRF hatası - sayfayı yenile
                if (response.status === 419) {
                    alert('Oturum süresi doldu. Sayfa yenileniyor...');
                    window.location.reload();
                    return;
                }

                const data = await response.json();
                if (data.success) {
                    appendMessage(data.message);
                    
                    // Bot mesajı varsa ekle
                    if (data.bot_message) {
                        setTimeout(() => {
                            appendMessage(data.bot_message);
                            lastMessageId = data.bot_message.id;
                            scrollToBottom();
                        }, 500);
                    }
                    
                    messageInput.value = '';
                    messageInput.style.height = 'auto';
                    lastMessageId = data.message.id;
                    scrollToBottom();
                } else {
                    alert(data.error || 'Mesaj gönderilemedi.');
                }
            } catch (err) {
                console.error('Chat send error:', err);
                alert('Bir hata oluştu: ' + err.message);
            } finally {
                sendBtn.disabled = false;
            }
        });
    }

    function appendMessage(msg) {
        const container = document.getElementById('chatMessages');
        const isOwn = msg.user_id === currentUserId;
        const isBot = msg.is_bot || false;
        const isFlagged = msg.is_flagged || false;

        // Remove empty state if present
        const emptyState = container.querySelector('.empty-chat');
        if (emptyState) emptyState.remove();

        const div = document.createElement('div');
        div.className = `chat-msg ${isOwn ? 'own' : ''} ${isBot ? 'bot' : ''} ${isFlagged ? 'flagged' : ''}`;
        div.dataset.messageId = msg.id;
        
        // Bot avatarı
        let avatarUrl = msg.avatar;
        if (isBot) {
            avatarUrl = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36"%3E%3Crect fill="%2306b6d4" width="36" height="36"/%3E%3Ctext x="50%25" y="50%25" font-size="20" text-anchor="middle" dominant-baseline="middle" fill="white" font-family="system-ui"%3E🤖%3C/text%3E%3C/svg%3E';
        } else if (!avatarUrl) {
            avatarUrl = 'https://ui-avatars.com/api/?name=' + encodeURIComponent(msg.user_name) + '&background=1e40af&color=fff&bold=true&size=36';
        }
        
        // Silme butonu - sadece kendi ve bot olmayan mesajlar
        let deleteBtn = '';
        if (isOwn && !isBot) {
            deleteBtn = `<div class="chat-msg-actions"><button class="chat-msg-del-btn" onclick="deleteMessage(${msg.id})">🗑 Sil</button></div>`;
        }
        
        // Bayraklı mesaj göstergesi
        let flagNotice = '';
        if (isFlagged) {
            flagNotice = `<div style="font-size: 10px; color: #f59e0b; margin-top: 4px;">⚠️ İçerik Kontrol Edilmiştir</div>`;
        }

        div.innerHTML = `
            <img src="${avatarUrl}"
                 alt="${msg.user_name}" class="chat-msg-avatar">
            <div class="chat-msg-body">
                <div class="chat-msg-meta">
                    <span class="chat-msg-name">${msg.user_name}</span>
                    <span class="chat-msg-time">${msg.created_at}</span>
                </div>
                <div class="chat-msg-bubble">${isBot ? msg.message : escapeHtml(msg.message)}</div>
                ${flagNotice}
                ${deleteBtn}
            </div>`;
        container.appendChild(div);
    }

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

    async function deleteMessage(messageId) {
        if (!confirm('Bu mesajı silmek istediğinizden emin misiniz?')) return;
        try {
            const deleteUrl = '<?php echo e(url("/sohbet/mesajlar")); ?>' + `/${messageId}`;
            const res = await fetch(deleteUrl, {
                method: 'DELETE',
                headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content }
            });
            const data = await res.json();
            if (data.success) {
                document.querySelector(`[data-message-id="${messageId}"]`)?.remove();
            }
        } catch (err) {
            console.error(err);
        }
    }

    async function fetchNewMessages() {
        try {
            const fetchUrl = '<?php echo e(url("/sohbet/" . $room->slug . "/mesajlar")); ?>' + `?since_id=${lastMessageId}`;
            const res = await fetch(fetchUrl);
            const data = await res.json();
            if (data.messages?.length) {
                data.messages.forEach(msg => {
                    appendMessage(msg);
                    lastMessageId = msg.id;
                });
                scrollToBottom();
            }
        } catch (err) {}
    }

    function scrollToBottom() {
        const el = document.getElementById('chatMessages');
        el.scrollTop = el.scrollHeight;
    }

    scrollToBottom();
    // Polling aktif
    const poll = setInterval(fetchNewMessages, 3000);
    window.addEventListener('beforeunload', () => clearInterval(poll));
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.public', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\askeribilgiler\resources\views\chat\show.blade.php ENDPATH**/ ?>