{{-- CSRF Token --}}
<input type="text" name="content" id="content" placeholder="Write your message" />
<input type="hidden" name="forum_id" id="forum_id" value="1" />
<meta name="csrf-token" content="{{ csrf_token() }}">
<button type="button" id="send">Send</button>

<ul id="messages"></ul>

<!-- Pusher JS CDN -->
<script src="https://js.pusher.com/8.4.0/pusher.min.js"></script>
<script>
    // Enviar mensaje al backend
    document.getElementById('send').addEventListener('click', function() {
        var content = document.getElementById('content').value;
        var forumId = document.getElementById('forum_id').value;
        var csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

        fetch('/sendMessage', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                },
                body: JSON.stringify({
                    content: content,
                    forum_id: forumId
                })
            })
            .then(response => response.json())
            .then(data => {
                console.log('Success:', data);
                document.getElementById('content').value = '';
            })
            .catch((error) => {
                console.error('Error:', error);
            });
    });

    // Pusher config
    var pusher = new Pusher('{{ env('PUSHER_APP_KEY') }}', {
        cluster: '{{ env('PUSHER_APP_CLUSTER') }}',
        forceTLS: true
    });

    var channel = pusher.subscribe('forum.' + forumId);

    channel.bind('new-message', function(data) {
        // Renderiza el mensaje en el DOM
        var li = document.createElement('li');
        li.innerHTML = '<strong>' + data.user.name + ':</strong> ' + data.content;
        document.getElementById('messages').appendChild(li);
    });
</script>