<div id="ticket-viewers-{{ $ticket_id }}" class="mt-3 mb-3" style="display: none;">
    <div class="flex items-center gap-2 p-3 bg-blue-50 rounded-lg border border-neutral-200 dark:!bg-gray-900 dark:border-neutral-700">
        <svg class="w-5 h-5 text-blue-600 dark:text-indigo-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
        </svg>
        <span class="text-sm font-medium text-gray-700 dark:text-gray-200">
            <span id="viewer-count-{{ $ticket_id }}">0</span> {{ __('viewing now') }}
        </span>
        <div id="viewer-avatars-{{ $ticket_id }}" class="flex -space-x-2 ml-2">
            <!-- Viewer avatars will be inserted here dynamically -->
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const ticketId = {{ $ticket_id }};
            const containerEl = document.getElementById('ticket-viewers-' + ticketId);
            const viewerCountEl = document.getElementById('viewer-count-' + ticketId);
            const viewerAvatarsEl = document.getElementById('viewer-avatars-' + ticketId);

            // Check if Echo is available
            if (typeof window.Echo === 'undefined') {
                return; // Silently fail - component stays hidden
            }

            // Initialize global channel storage
            window.ticketChannels = window.ticketChannels || {};

            // Try to join the presence channel (or reuse existing)
            try {
                // Create and store the channel instance for reuse by other components
                if (!window.ticketChannels[ticketId]) {
                    window.ticketChannels[ticketId] = window.Echo.join('ticket.' + ticketId);
                }
                const channel = window.ticketChannels[ticketId];

                // Listen for successful connection
                channel.here((users) => {
                    // Show the component only when successfully connected
                    containerEl.style.display = 'block';
                    updateViewers(users);
                })
                .joining((user) => {
                    setTimeout(() => {
                        if (channel.subscription && channel.subscription.members) {
                            const members = Object.values(channel.subscription.members.members);
                            updateViewers(members);
                        }
                    }, 100);
                })
                .leaving((user) => {
                    setTimeout(() => {
                        if (channel.subscription && channel.subscription.members) {
                            const members = Object.values(channel.subscription.members.members);
                            updateViewers(members);
                        }
                    }, 100);
                })
                .error((error) => {
                    // Keep component hidden on error
                });

                // Update viewer list periodically
                setInterval(() => {
                    if (channel.subscription && channel.subscription.members) {
                        const members = Object.values(channel.subscription.members.members);
                        if (members.length > 0) {
                            updateViewers(members);
                        }
                    }
                }, 2000);

            } catch (error) {
                // Component stays hidden
            }

            function updateViewers(users) {
                viewerCountEl.textContent = users.length;

                // Clear existing avatars
                viewerAvatarsEl.innerHTML = '';

                // Add avatar for each user
                users.forEach(user => {
                    const avatarDiv = document.createElement('div');
                    avatarDiv.className = 'relative group';
                    avatarDiv.title = user.name;

                    const img = document.createElement('img');
                    img.className = 'w-8 h-8 rounded-full border-2 border-white dark:border-gray-800';

                    // Use profile photo if available, otherwise use Gravatar
                    if (user.profile_photo_path) {
                        img.src = '{{ config('app.url') }}/storage/' + user.profile_photo_path;
                    } else {
                        // Use email hash from server for Gravatar
                        const emailHash = user.email_hash || 'default';
                        img.src = 'https://gravatar.com/avatar/' + emailHash + '.png?d=monsterid&s=80';
                    }

                    img.alt = user.name;

                    // Add tooltip
                    const tooltip = document.createElement('div');
                    tooltip.className = 'absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-2 py-1 bg-gray-900 text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap pointer-events-none z-10';
                    tooltip.textContent = user.name;

                    avatarDiv.appendChild(img);
                    avatarDiv.appendChild(tooltip);
                    viewerAvatarsEl.appendChild(avatarDiv);
                });
            }
        });
    </script>
</div>
