
<div id="chat-container" class="mx-3 my-3" data-receiver="{{ $receiver->id }}" data-auth-id="{{ Auth::user()->id }}">
    <div id="messages" class="h-96 border overflow-y-scroll p-4 mb-4 bg-white rounded space-y-2">
        @foreach ($chats as $chat)
            @if ($chat->sender_id === auth()->id())
                <div class="text-right">
                    <div class="inline-block bg-purple-500 text-white px-4 py-2 rounded-lg">
                        {{ $chat->message }}
                    </div>
                </div>
            @else
                <div class="text-left">
                    <div class="inline-block bg-gray-300 text-gray-800 px-4 py-2 rounded-lg">
                        {{ $chat->message }}
                    </div>
                </div>
            @endif
        @endforeach
    </div>

    <div class="flex items-center gap-2">
        <input id="message" type="text" placeholder="Tulis pesan..." class="flex-1 border p-2 rounded">
        <button id="send-btn" class="bg-purple-500 text-white px-4 py-2 rounded">Kirim</button>
    </div>
</div>

@vite(['resources/css/app.css', 'resources/js/app.js'])

<script>
document.addEventListener('DOMContentLoaded', function () {
    const chatContainer = document.getElementById('chat-container');
    const receiverId = chatContainer.dataset.receiver;
    const authId = chatContainer.dataset.authId;
    const messageInput = document.getElementById('message');
    const messagesBox = document.getElementById('messages');
    const sendBtn = document.getElementById('send-btn');

    messagesBox.scrollTop = messagesBox.scrollHeight;

    function appendMessage(message, fromSelf = false) {
        const div = document.createElement('div');
        div.className = fromSelf ? 'w-full text-right mb-2' : 'w-full text-left mb-2';

        const bubble = document.createElement('div');
        bubble.classList.add(
            'inline-block', 'max-w-xs', 'px-4', 'py-2', 'rounded-lg', 'break-words',
            fromSelf ? 'bg-blue-500' : 'bg-gray-300',
            fromSelf ? 'text-white' : 'text-gray-800'
        );
        bubble.innerText = message;
        div.appendChild(bubble);
        messagesBox.appendChild(div);
        messagesBox.scrollTop = messagesBox.scrollHeight;
    }

    function sendMessage() {
        const message = messageInput.value.trim();
        if (!message) return;

        fetch("{{ route('chat.store') }}", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            },
            body: JSON.stringify({
                receiver_id: receiverId,
                message: message
            })
        })
        .then(res => res.json())
        .then(data => {
            appendMessage(message, true);
            messageInput.value = '';
            messageInput.focus();
        })
        .catch(err => console.error('Error sending message:', err));
    }

    sendBtn.addEventListener('click', sendMessage);
    messageInput.addEventListener('keydown', function (e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });


    if (window.Echo) {
        const receiverChannel = `chat.${authId}`;
        window.Echo.channel(receiverChannel)
            .listen('.ChatMessage.sent', (e) => {
                console.log("Broadcast message received:", e); 
                if (e.sender_id !== authId) {
                    appendMessage(e.message, false);
                }
            });
    } else {
        console.error('Echo belum tersedia!');
    }
});
</script>
