<?php
    $isCoachViewer = auth()->user()->isCoach();
    $otherPartyName = $isCoachViewer ? $coachRequest->athlete->user->fullName() : $coachRequest->coach->user->fullName();
    $backRoute = $isCoachViewer ? route('coach.requests.index') : route('athlete.requests.index');
?>

<?php $__env->startSection('title', 'گفتگو با ' . $otherPartyName); ?>

<?php $__env->startSection('content'); ?>
    <a href="<?php echo e($backRoute); ?>" class="text-sm text-blue-600 hover:underline mb-4 inline-block">← بازگشت</a>

    <div class="bg-white rounded-xl shadow-sm flex flex-col" style="height: 70vh;">
        <div class="border-b px-4 py-3 font-semibold"><?php echo e($otherPartyName); ?></div>

        <div id="messages" class="flex-1 overflow-y-auto p-4 space-y-3" data-last-id="<?php echo e($messages->last()?->id ?? 0); ?>">
            <?php $__currentLoopData = $messages; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $message): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <div class="flex <?php echo e($message->sender_id === auth()->id() ? 'justify-end' : 'justify-start'); ?>">
                    <div class="max-w-[75%] rounded-2xl px-4 py-2 text-sm
                        <?php echo e($message->sender_id === auth()->id() ? 'bg-gray-900 text-white' : 'bg-gray-100 text-gray-800'); ?>">
                        <div><?php echo e($message->body); ?></div>
                        <div class="text-[10px] opacity-60 mt-1 text-left" dir="ltr"><?php echo e(verta($message->created_at)->format('H:i')); ?></div>
                    </div>
                </div>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </div>

        <form id="send-form" method="POST" action="<?php echo e(route('chat.messages.store', $coachRequest)); ?>" class="border-t p-3 flex gap-2">
            <?php echo csrf_field(); ?>
            <input type="text" name="body" id="message-input" placeholder="پیام خود را بنویسید..."
                   class="flex-1 border rounded-full px-4 py-2 text-sm" required maxlength="2000" autocomplete="off">
            <button class="bg-gray-900 text-white text-sm px-5 py-2 rounded-full">ارسال</button>
        </form>
    </div>

    <script>
        const messagesEl = document.getElementById('messages');
        const form = document.getElementById('send-form');
        const input = document.getElementById('message-input');
        const pollUrl = "<?php echo e(route('chat.messages.poll', $coachRequest)); ?>";
        const csrfToken = document.querySelector('meta[name=csrf-token]').content;

        function scrollToBottom() {
            messagesEl.scrollTop = messagesEl.scrollHeight;
        }
        scrollToBottom();

        function appendMessage(m) {
            const wrap = document.createElement('div');
            wrap.className = 'flex ' + (m.is_mine ? 'justify-end' : 'justify-start');
            wrap.innerHTML = `
                <div class="max-w-[75%] rounded-2xl px-4 py-2 text-sm ${m.is_mine ? 'bg-gray-900 text-white' : 'bg-gray-100 text-gray-800'}">
                    <div></div>
                    <div class="text-[10px] opacity-60 mt-1 text-left" dir="ltr">${m.created_at}</div>
                </div>`;
            wrap.querySelector('div > div').textContent = m.body; // جلوگیری از XSS — همیشه textContent، نه innerHTML برای متن پیام
            messagesEl.appendChild(wrap);
            messagesEl.dataset.lastId = m.id;
        }

        async function poll() {
            const afterId = messagesEl.dataset.lastId || 0;
            try {
                const res = await fetch(`${pollUrl}?after_id=${afterId}`);
                const newMessages = await res.json();
                if (newMessages.length) {
                    newMessages.forEach(appendMessage);
                    scrollToBottom();
                }
            } catch (e) { /* silent — دوباره در دور بعد تلاش می‌کند */ }
        }

        // AJAX Polling هر ۱۲ ثانیه (طبق تصمیم معماری Phase 1/11 — بدون WebSocket)
        setInterval(poll, 12000);

        form.addEventListener('submit', function (e) {
            e.preventDefault();
            const body = input.value.trim();
            if (!body) return;

            fetch(form.action, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
                body: JSON.stringify({ body }),
            }).then(() => {
                input.value = '';
                poll();
            });
        });
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make(auth()->user()->isCoach() ? 'coach.layouts.app' : 'athlete.layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Users\paradox\Desktop\fresh\abtin-sport-platform\resources\views/chat/show.blade.php ENDPATH**/ ?>