<?php $__env->startSection('content'); ?>
    <section class="page flush">
        <?php if(session('status')): ?>
            <div class="flash"><?php echo e(session('status')); ?></div>
        <?php endif; ?>

        <div class="panel inbox-shell" style="--inbox-list-w: <?php echo e($_COOKIE['inbox-list-w'] ?? '366'); ?>px; --inbox-context-w: <?php echo e($_COOKIE['inbox-context-w'] ?? '294'); ?>px">
            <aside class="inbox-list" style="position: relative;">
                <div class="resizer" data-target="inbox-list-w" data-edge="right" data-default="366" data-min="200" data-max="600"></div>
                <?php echo $__env->make('conversations.partials.inbox-header', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

                <div class="list-scroll">
                    <?php echo $__env->make('conversations.partials.sidebar-list', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                </div>
            </aside>

            <section class="inbox-thread">
                <div class="thread-toolbar" style="flex-direction: column; align-items: stretch; padding: 16px; gap: 12px;">
                    <div style="display: flex; justify-content: space-between; align-items: center; position: relative;">
                        <div style="font-weight: 700; font-size: 16px; color: var(--text);">Conversation</div>
                        
                        <!-- Toolbar Actions -->
                        <div style="align-items: center; display: flex; gap: 8px;">
                            <?php if($conversation->trashed()): ?>
                                <form action="<?php echo e(route('conversations.restore', $conversation)); ?>" method="POST" style="display: inline;">
                                    <?php echo csrf_field(); ?>
                                    <?php echo method_field('PUT'); ?>
                                    <button class="icon-button" type="submit" title="Restore"><i class="ph ph-arrow-counter-clockwise" style="font-size: 20px;"></i></button>
                                </form>
                                <form action="<?php echo e(route('conversations.forceDestroy', $conversation)); ?>" method="POST" style="display: inline;" data-confirm="Are you sure you want to delete this conversation forever? This cannot be undone." data-confirm-title="Delete Conversation" data-confirm-btn="Yes, delete forever" data-cancel-btn="No, keep it">
                                    <?php echo csrf_field(); ?>
                                    <?php echo method_field('DELETE'); ?>
                                    <button class="icon-button" type="submit" title="Delete Forever" style="color: var(--red);"><i class="ph ph-trash" style="font-size: 20px;"></i></button>
                                </form>
                            <?php else: ?>
                                <button class="icon-button" type="button" title="Call"><i class="ph ph-phone" style="font-size: 20px;"></i></button>
                                
                                <?php if($conversation->status === 'archived'): ?>
                                    <form action="<?php echo e(route('conversations.unarchive', $conversation)); ?>" method="POST" style="display: inline;">
                                        <?php echo csrf_field(); ?>
                                        <?php echo method_field('PUT'); ?>
                                        <button class="icon-button" type="submit" title="Unarchive"><i class="ph ph-tray-arrow-up" style="font-size: 20px;"></i></button>
                                    </form>
                                <?php else: ?>
                                    <form action="<?php echo e(route('conversations.archive', $conversation)); ?>" method="POST" style="display: inline;">
                                        <?php echo csrf_field(); ?>
                                        <?php echo method_field('PUT'); ?>
                                        <button class="icon-button" type="submit" title="Archive"><i class="ph ph-archive" style="font-size: 20px;"></i></button>
                                    </form>
                                <?php endif; ?>

                                <form action="<?php echo e(route('conversations.destroy', $conversation)); ?>" method="POST" style="display: inline;">
                                    <?php echo csrf_field(); ?>
                                    <?php echo method_field('DELETE'); ?>
                                    <button class="icon-button" type="submit" title="Move to Trash" style="color: var(--red);"><i class="ph ph-trash" style="font-size: 20px;"></i></button>
                                </form>
                                
                                <button class="icon-button" type="button" title="More Options"><i class="ph ph-dots-three" style="font-size: 20px;"></i></button>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Customer Profile Info -->
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <div style="position: relative; display: inline-block; width: 38px; height: 38px;">
                            <span class="row-avatar" style="width: 38px; height: 38px; font-size: 16px; display: inline-flex; align-items: center; justify-content: center; background: #1da4f2; color: #fff; border-radius: 50%; font-weight: bold;">
                                <?php echo e(strtoupper(substr($conversation->contact->name ?? $conversation->contact->phone ?? 'U', 0, 1))); ?>

                            </span>
                            <div style="position: absolute; bottom: -2px; right: -2px; width: 18px; height: 18px; background: #ffffff; border-radius: 50%; display: flex; align-items: center; justify-content: center; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
                                <?php if($conversation->channel === 'facebook' || $conversation->channel === 'fb'): ?>
                                    <i class="ph-fill ph-facebook-logo" style="color: #1877F2; font-size: 12px;"></i>
                                <?php elseif($conversation->channel === 'whatsapp'): ?>
                                    <i class="ph-fill ph-whatsapp-logo" style="color: #25D366; font-size: 12px;"></i>
                                <?php elseif($conversation->channel === 'instagram'): ?>
                                    <i class="ph-fill ph-instagram-logo" style="color: #e4405f; font-size: 12px;"></i>
                                <?php elseif($conversation->channel === 'web'): ?>
                                    <i class="ph-fill ph-globe" style="color: #3d8bff; font-size: 12px;"></i>
                                <?php else: ?>
                                    <i class="ph-fill ph-question" style="color: var(--muted); font-size: 12px;"></i>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div style="min-width: 0; display: flex; flex-direction: column; line-height: 1.2;">
                            <strong style="font-size: 14px; color: var(--text);"><?php echo e($conversation->contact->name ?? $conversation->contact->phone ?? 'Unknown contact'); ?></strong>
                            <span class="muted" style="font-size: 11px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 180px;"><?php echo e($conversation->contact->email ?? 'customer@example.com'); ?></span>
                        </div>
                        
                        <div style="margin-left: auto; display: flex; align-items: center; position: relative;">
                            <?php
                                $predefinedLabels = ['Lead', 'Hot Lead', 'Customer', 'Repeat Customer'];
                                $allLabels = collect($predefinedLabels)->merge($existingLabels ?? [])->unique()->filter()->values();
                            ?>
                            <form id="label-form" action="<?php echo e(route('conversations.label.update', $conversation)); ?>" method="POST" style="display: none; align-items: center;">
                                <?php echo csrf_field(); ?>
                                <?php echo method_field('PUT'); ?>
                                <input list="label-suggestions" name="label" class="form-control" style="padding: 2px 8px; font-size: 12px; height: 24px; min-height: 0; width: 150px; border-radius: 4px;" value="<?php echo e($conversation->label); ?>" placeholder="Type label..." onblur="if(this.value !== '<?php echo e($conversation->label); ?>') this.form.submit(); else { document.getElementById('label-form').style.display='none'; document.getElementById('label-badge-container').style.display='block'; }">
                                <datalist id="label-suggestions">
                                    <?php $__currentLoopData = $allLabels; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $lbl): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($lbl); ?>">
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </datalist>
                            </form>
                            
                            <div id="label-badge-container" style="cursor: pointer; padding-left: 20px;" onclick="document.getElementById('label-badge-container').style.display='none'; document.getElementById('label-form').style.display='flex'; document.querySelector('#label-form input').focus();">
                                <?php if($conversation->label): ?>
                                    <span class="badge" style="background: #fdf4ff; color: #a21caf; border: 1px solid #f5d0fe; font-size: 11px; padding: 2px 6px;">
                                        <i class="ph ph-tag" style="margin-right: 4px;"></i><?php echo e($conversation->label); ?>

                                    </span>
                                <?php else: ?>
                                    <span class="badge" style="background: transparent; color: var(--muted); border: 1px dashed var(--border); font-size: 11px; padding: 2px 6px;">
                                        <i class="ph ph-plus" style="margin-right: 4px;"></i>Add label
                                    </span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="thread-scroll">
                    <?php $__empty_1 = true; $__currentLoopData = $conversation->messages; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $message): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                        <article data-message-id="<?php echo e($message->id); ?>" class="<?php echo \Illuminate\Support\Arr::toCssClasses(['message', 'bot' => in_array($message->sender_type, ['bot', 'human']), 'customer' => $message->sender_type === 'customer']); ?>">
                            <?php if($message->metadata && isset($message->metadata['reply_to'])): ?>
                                <div class="message-quoted">
                                    <i class="ph-fill ph-quotes" style="color: var(--blue);"></i>
                                    <?php echo e($message->metadata['reply_to']['body']); ?>

                                </div>
                            <?php endif; ?>
                            <?php echo e($message->body); ?>

                            <div class="message-time"><?php echo e($message->sent_at->timezone('Asia/Dhaka')->format('H:i')); ?></div>
                            <div class="message-actions">
                                <a href="#" class="reply-button" title="Reply" data-message-id="<?php echo e($message->id); ?>" data-message-preview="<?php echo e(\Illuminate\Support\Str::limit($message->body, 60)); ?>" onclick="replyToMessage(this.dataset.messageId, this.dataset.messagePreview); return false;">
                                    <i class="ph ph-arrow-u-down-left"></i>
                                </a>
                            </div>
                        </article>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                        <div class="empty-state">No messages yet.</div>
                    <?php endif; ?>
                </div>

                <form method="POST" action="<?php echo e(route('conversations.messages.store', $conversation)); ?>" class="composer" style="position: relative;">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="reply_to_message_id" id="reply_to_message_id" value="">
                    
                    <div id="reply-preview-box" class="reply-preview-box" style="display: none;">
                        <div style="display: flex; gap: 8px; align-items: center;">
                            <i class="ph-fill ph-quotes" style="color: var(--blue);"></i>
                            <span id="reply-preview-text" style="flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 12px;"></span>
                        </div>
                        <button type="button" class="reply-cancel-btn" onclick="cancelReply()">x</button>
                    </div>

                    <textarea class="form-control" name="body" placeholder="Reply to customer..." rows="1" required style="width: 100%; border: 0; padding: 12px 14px; resize: none; background: transparent; min-height: 44px;"></textarea>
                    
                    <div style="display: flex; justify-content: flex-end; padding: 8px 12px; border-top: 1px solid var(--border);">
                        <button class="button" type="submit">Send</button>
                    </div>
                </form>
                <script>
                    function replyToMessage(id, text) {
                        document.getElementById('reply_to_message_id').value = id;
                        document.getElementById('reply-preview-text').textContent = text;
                        document.getElementById('reply-preview-box').style.display = 'block';
                        document.querySelector('.composer textarea[name="body"]').focus();
                    }
                    function cancelReply() {
                        document.getElementById('reply_to_message_id').value = '';
                        document.getElementById('reply-preview-box').style.display = 'none';
                    }

                    // Real-time polling
                    let lastMessageId = null;
                    function updateLastMessageId() {
                        const articles = document.querySelectorAll('article.message[data-message-id]');
                        if (articles.length > 0) {
                            lastMessageId = articles[articles.length - 1].getAttribute('data-message-id');
                        }
                    }

                    function pollNewMessages() {
                        if (!lastMessageId) return;
                        
                        fetch(`<?php echo e(route('conversations.messages.index', $conversation)); ?>?after_id=${lastMessageId}`, {
                            headers: {
                                'Accept': 'application/json'
                            }
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.messages && data.messages.length > 0) {
                                data.messages.forEach(msg => {
                                    appendSingleMessage(msg);
                                });
                            }

                            if (data.current_page) {
                                updateLiveDeviceMockup(data.current_page);
                            }
                        })
                        .catch(err => console.error('Error polling messages:', err));
                    }

                    function appendSingleMessage(msg) {
                        if (document.querySelector(`article.message[data-message-id="${msg.id}"]`)) return;

                        const threadScroll = document.querySelector('.thread-scroll');
                        const emptyState = threadScroll.querySelector('.empty-state');
                        if (emptyState) emptyState.remove();

                        const article = document.createElement('article');
                        article.setAttribute('data-message-id', msg.id);
                        
                        const isOurSide = msg.sender_type === 'bot' || msg.sender_type === 'human';
                        article.className = 'message ' + (isOurSide ? 'bot' : 'customer');

                        let html = '';
                        if (msg.metadata && msg.metadata.reply_to) {
                            html += `
                                <div class="message-quoted">
                                    <i class="ph-fill ph-quotes" style="color: var(--blue);"></i>
                                    ${escapeHtml(msg.metadata.reply_to.body)}
                                </div>
                            `;
                        }
                        
                        html += escapeHtml(msg.body);
                        html += `<div class="message-time">${escapeHtml(msg.sent_at)}</div>`;
                        
                        html += `
                            <div class="message-actions">
                                <a href="#" class="reply-button" title="Reply" onclick="replyToMessage(${msg.id}, ${escapeJsString(msg.body)}); return false;">
                                    <i class="ph ph-arrow-u-down-left"></i>
                                </a>
                            </div>
                        `;

                        article.innerHTML = html;
                        threadScroll.appendChild(article);
                        updateLastMessageId();
                        threadScroll.scrollTop = threadScroll.scrollHeight;
                    }

                    let isSubmitting = false;
                    function submitMessageAJAX(form) {
                        if (isSubmitting) return;

                        const textarea = form.querySelector('textarea[name="body"]');
                        const body = textarea.value.trim();
                        if (body === '') return;

                        const replyToMessageId = document.getElementById('reply_to_message_id').value;
                        const token = form.querySelector('input[name="_token"]').value;
                        const tempLocalId = 'temp_' + Date.now();

                        isSubmitting = true;
                        textarea.disabled = true;

                        // Optimistic append
                        const optimisticMsg = {
                            id: tempLocalId,
                            sender_type: 'human',
                            body: body,
                            sent_at: new Date().toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit' }),
                            metadata: replyToMessageId ? { reply_to: { body: document.getElementById('reply-preview-text').textContent } } : null
                        };
                        appendSingleMessage(optimisticMsg);

                        const formData = {
                            body: body,
                            reply_to_message_id: replyToMessageId
                        };

                        fetch(form.action, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'Accept': 'application/json',
                                'X-CSRF-TOKEN': token
                            },
                            body: JSON.stringify(formData)
                        })
                        .then(response => {
                            if (!response.ok) throw new Error('Failed to send message');
                            return response.json();
                        })
                        .then(data => {
                            isSubmitting = false;
                            textarea.disabled = false;
                            textarea.value = '';
                            textarea.style.height = 'auto';
                            cancelReply();

                            // Sync optimistic bubble with database message ID
                            const optimisticBubble = document.querySelector(`article.message[data-message-id="${tempLocalId}"]`);
                            if (optimisticBubble && data.message) {
                                optimisticBubble.setAttribute('data-message-id', data.message.id);
                                const replyBtn = optimisticBubble.querySelector('.reply-button');
                                if (replyBtn) {
                                    replyBtn.setAttribute('onclick', `replyToMessage(${data.message.id}, ${escapeJsString(data.message.body)}); return false;`);
                                }
                            }
                            updateLastMessageId();
                            textarea.focus();
                        })
                        .catch(err => {
                            isSubmitting = false;
                            textarea.disabled = false;
                            
                            // Style optimistic bubble as failed
                            const optimisticBubble = document.querySelector(`article.message[data-message-id="${tempLocalId}"]`);
                            if (optimisticBubble) {
                                optimisticBubble.classList.add('failed-send');
                                optimisticBubble.style.border = '1px solid #ff4d4f';
                                optimisticBubble.style.opacity = '0.9';
                                
                                const failedIndicator = document.createElement('div');
                                failedIndicator.className = 'failed-text';
                                failedIndicator.style.color = '#ff4d4f';
                                failedIndicator.style.fontSize = '10px';
                                failedIndicator.style.marginTop = '4px';
                                failedIndicator.style.textAlign = 'right';
                                failedIndicator.innerHTML = '<i class="ph ph-warning-circle"></i> Failed. Click to retry.';
                                failedIndicator.style.cursor = 'pointer';
                                failedIndicator.style.fontWeight = 'bold';
                                
                                failedIndicator.addEventListener('click', function() {
                                    optimisticBubble.remove();
                                    textarea.value = body;
                                    document.getElementById('reply_to_message_id').value = replyToMessageId;
                                    submitMessageAJAX(form);
                                });
                                
                                optimisticBubble.appendChild(failedIndicator);
                            }
                            console.error(err);
                        });
                    }

                    function escapeHtml(text) {
                        if (!text) return '';
                        return text
                            .replace(/&/g, "&amp;")
                            .replace(/</g, "&lt;")
                            .replace(/>/g, "&gt;")
                            .replace(/"/g, "&quot;")
                            .replace(/'/g, "&#039;");
                    }

                    function escapeJsString(str) {
                        if (!str) return '""';
                        return JSON.stringify(str.substring(0, 60));
                    }

                    function updateLiveDeviceMockup(currentPage) {
                        try {
                            const url = new URL(currentPage);
                            const hostSpan = document.querySelector('.live-device-mockup div[style*="background: #f1f5f9"] span');
                            if (hostSpan) hostSpan.textContent = url.hostname;
                            
                            const pathSpan = document.querySelector('.live-device-mockup span.muted[style*="word-break: break-all"]');
                            if (pathSpan) pathSpan.textContent = url.pathname || '/';
                            
                            document.querySelectorAll('.activity-row').forEach(row => {
                                const span = row.querySelector('span.muted');
                                if (span && span.textContent.trim() === 'Active Page') {
                                    const strong = row.querySelector('strong');
                                    if (strong) {
                                        strong.textContent = currentPage.length > 24 ? currentPage.substring(0, 21) + '...' : currentPage;
                                        strong.title = currentPage;
                                    }
                                }
                            });
                        } catch (e) {}
                    }

                     function pollSidebar() {
                        fetch('<?php echo e(route("conversations.sidebar")); ?>?active_id=<?php echo e($conversation->id); ?>')
                            .then(response => response.text())
                            .then(html => {
                                document.querySelector('.inbox-list .list-scroll').innerHTML = html;
                            })
                            .catch(err => console.error('Error polling sidebar:', err));
                    }

                    document.addEventListener("DOMContentLoaded", function() {
                        const threadScroll = document.querySelector('.thread-scroll');
                        if (threadScroll) {
                            threadScroll.scrollTop = threadScroll.scrollHeight;
                        }
                        updateLastMessageId();
                        setInterval(pollNewMessages, 3000);
                        setInterval(pollSidebar, 5000);

                        // AJAX form submit event
                        const form = document.querySelector('.composer');
                        if (form) {
                            form.addEventListener('submit', function(e) {
                                e.preventDefault();
                                submitMessageAJAX(form);
                            });
                        }

                        // Enter key to send message (Shift+Enter for new lines)
                        const textarea = document.querySelector('.composer textarea[name="body"]');
                        if (textarea) {
                            textarea.addEventListener('keydown', function(e) {
                                if (e.key === 'Enter' && !e.shiftKey) {
                                    e.preventDefault();
                                    const form = textarea.closest('form');
                                    if (form && textarea.value.trim() !== '') {
                                        submitMessageAJAX(form);
                                    }
                                }
                            });

                            textarea.addEventListener('input', function() {
                                this.style.height = 'auto';
                                this.style.height = Math.min(this.scrollHeight, 150) + 'px';
                            });
                        }
                    });
                </script>
            </section>

            <aside class="inbox-context" style="position: relative;">
                <div class="resizer" data-target="inbox-context-w" data-edge="left" data-default="294" data-min="0" data-max="500"></div>
                <div class="panel-header" style="padding: 16px;">
                    <div style="font-weight: 700; font-size: 16px; color: var(--text);">Context</div>
                </div>
                <div class="context-scroll" style="flex: 1; min-height: 0; padding-bottom: 24px;">
                    <?php
                        $isMobile = preg_match('/Mobile|Android|iPhone|iPad|iPod/i', $conversation->user_agent ?? '');
                    ?>
                    <section class="context-block">
                        <div class="context-title">
                            <h2>Device</h2>
                        </div>

                            <!-- Live Session Replay Container -->
                            <div id="live-browsing-container" style="margin: 14px 0; border-radius: 8px; overflow: hidden; border: 1px solid #cbd5e1; box-shadow: 0 4px 12px rgba(0,0,0,0.05); min-height: 250px; background: #0f172a; display: flex; align-items: center; justify-content: center; color: #cbd5e1; font-size: 12px;">
                                <div id="live-browsing-placeholder">
                                    <i class="ph ph-spinner-gap" style="animation: spin 1s linear infinite; margin-right: 8px;"></i>
                                    Waiting for live session data...
                                </div>
                            </div>

                        <div class="activity-row">
                            <span class="muted">Browser</span>
                            <strong>Website chat</strong>
                        </div>
                        <div class="activity-row">
                            <span class="muted">Active Page</span>
                            <strong style="word-break: break-all; max-width: 140px; text-align: right; font-size: 11px;" title="<?php echo e($conversation->current_page ?? 'Home'); ?>">
                                <?php echo e($conversation->current_page ? (strlen($conversation->current_page) > 24 ? substr($conversation->current_page, 0, 21) . '...' : $conversation->current_page) : 'Home'); ?>

                            </strong>
                        </div>
                        <div class="activity-row">
                            <span class="muted">Contact phone</span>
                            <strong><?php echo e($conversation->contact->phone ?? 'Needed'); ?></strong>
                        </div>
                    </section>
                    <section class="context-block">
                        <div class="context-title">
                            <h2>Routing</h2>
                        </div>
                        <div class="activity-row">
                            <span class="muted">Assignee</span>
                            <strong><?php echo e($conversation->assignedUser?->name ?? 'None assigned'); ?></strong>
                        </div>
                        <?php if($canAssignConversation): ?>
                            <form method="POST" action="<?php echo e(route('conversations.assignment.update', $conversation)); ?>" class="stack" style="margin-top: 12px;">
                                <?php echo csrf_field(); ?>
                                <?php echo method_field('PUT'); ?>
                                <label>
                                    <span class="field-label">Assign to</span>
                                    <select class="form-control" name="assigned_user_id">
                                        <option value="">No assignee</option>
                                        <?php $__currentLoopData = $assignableMembers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $membership): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($membership->user_id); ?>" <?php if($conversation->assigned_user_id === $membership->user_id): echo 'selected'; endif; ?>>
                                                <?php echo e($membership->user->name); ?> - <?php echo e(ucfirst($membership->role)); ?>

                                            </option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </label>
                                <button class="button" type="submit" style="width: 100%;">Update</button>
                            </form>
                        <?php else: ?>
                            <p class="muted" style="font-size: 13px; margin: 12px 0 0;">You can monitor this thread. Assignment requires handoff privileges.</p>
                        <?php endif; ?>
                    </section>

                    <section class="context-block">
                        <div class="context-title">
                            <h2>Details</h2>
                        </div>
                        <div class="activity-row">
                            <span class="muted">Location</span>
                            <strong><?php echo e($conversation->contact->email ? 'Known' : 'Bangladesh'); ?></strong>
                        </div>
                        <div class="activity-row">
                            <span class="muted">Local time</span>
                            <strong><?php echo e(now('Asia/Dhaka')->format('g:ia')); ?></strong>
                        </div>
                        <div class="activity-row">
                            <span class="muted">Channel</span>
                            <strong><?php echo e(ucfirst($conversation->channel)); ?></strong>
                        </div>
                    </section>



                    <section class="context-block">
                        <h2>Callbacks</h2>
                        <?php $__empty_1 = true; $__currentLoopData = $conversation->callbackRequests; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $callbackRequest): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                            <div class="activity-row">
                                <span><?php echo e($callbackRequest->phone ?? 'Phone needed'); ?></span>
                                <span class="<?php echo \Illuminate\Support\Arr::toCssClasses(['badge', 'warning' => in_array($callbackRequest->status, ['needs_phone', 'requested'], true)]); ?>">
                                    <?php echo e(str_replace('_', ' ', ucfirst($callbackRequest->status))); ?>

                                </span>
                            </div>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                            <p class="muted" style="margin: 12px 0 0;">No callback requests.</p>
                        <?php endif; ?>
                    </section>
                </div>
            </aside>
        </div>
    </section>
    <?php echo $__env->make('conversations.partials.inbox-scripts', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
    
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/rrweb-player@latest/dist/style.css" />
    <script src="https://cdn.jsdelivr.net/npm/rrweb-player@latest/dist/index.js"></script>
    <script src="https://js.pusher.com/8.2.0/pusher.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/laravel-echo@1.16.1/dist/echo.iife.js"></script>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            window.Pusher = Pusher;
            window.Echo = new Echo({
                broadcaster: 'reverb',
                key: '<?php echo e(env("REVERB_APP_KEY")); ?>',
                wsHost: window.location.hostname,
                wsPort: <?php echo e(env("REVERB_PORT", 8080)); ?>,
                wssPort: <?php echo e(env("REVERB_PORT", 8080)); ?>,
                forceTLS: (window.location.protocol === 'https:'),
                enabledTransports: ['ws', 'wss'],
            });

            let replayer = null;
            let container = document.getElementById('live-browsing-container');
            let placeholder = document.getElementById('live-browsing-placeholder');
            
            window.Echo.private('conversation.<?php echo e($conversation->id); ?>')
                .listen('VisitorScreenUpdated', (e) => {
                    if (!replayer && e.events && e.events.length > 0) {
                        if (placeholder) placeholder.remove();
                        container.style.background = '#fff';
                        
                        // Wait slightly for DOM to settle
                        setTimeout(() => {
                            replayer = new rrwebPlayer({
                                target: container,
                                props: {
                                    events: e.events,
                                    liveMode: true,
                                    autoPlay: true,
                                    width: container.clientWidth,
                                    height: 250,
                                },
                            });
                        }, 100);
                    } else if (replayer && e.events && e.events.length > 0) {
                        e.events.forEach((ev) => replayer.addEvent(ev));
                    }
                });
        });
    </script>
    <style>
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
    </style>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', [
    'title' => 'Conversation | VejalNai',
    'topbarTitle' => 'Shared Inbox',
    'topbarSubtitle' => ($conversation->contact->name ?? $conversation->contact->phone ?? 'Unknown contact').' on '.ucfirst($conversation->channel),
    'hideTopbar' => true,
], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/ecom123/public_html/chat.shunnointernational.com/resources/views/conversations/show.blade.php ENDPATH**/ ?>