@extends('layouts.landing')

@section('title',"Chat")

@section('content')

<div class="container-fluid">
    <div class="card shadow mb-4">

        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">
                Mensajes
            </h6>
        </div>

        <div class="card-body">

            {{-- CONTENEDOR CHAT --}}
            <div id="chat-app"
                 data-conversation-id="{{ $conversation->id }}">

                {{-- MENSAJES --}}
                <div id="messages"
                     style="height:400px;overflow-y:auto;padding:10px;background:#f5f5f5;border-radius:10px;">

                    @foreach($conversation->messages as $message)

                        <div class="message {{ $message->user_id == auth()->id() ? 'mine' : 'theirs' }}">
                            <div class="bubble">
                                <strong>{{ $message->user->name }}</strong><br>
                                {{ $message->message }}
                            </div>
                        </div>

                    @endforeach

                </div>

                {{-- INPUT --}}
                <div style="margin-top:10px;display:flex;gap:10px;">
                    <input id="messageInput"
                           class="form-control"
                           placeholder="Escribe mensaje...">

                    <button onclick="sendMessage()"
                            class="btn btn-primary">
                        Enviar
                    </button>
                </div>

            </div>

        </div>
    </div>
</div>

@endsection


@push('scripts')

<script>
window.USER_ID = {{ auth()->id() }};
</script>

<script>

document.addEventListener('DOMContentLoaded', function () {

    const chatApp = document.getElementById('chat-app');
    const messagesDiv = document.getElementById('messages');

    if (!chatApp || !messagesDiv) {
        console.error('Chat DOM no encontrado');
        return;
    }

    const conversationId =
        chatApp.dataset.conversationId;

    console.log('Chat conectado a:', conversationId);

    /*
    |--------------------------------------------------------------------------
    | ESCUCHAR MENSAJES REALTIME
    |--------------------------------------------------------------------------
    */

    window.Echo.private(`chat.${conversationId}`)
        .listen('.ChatMessageSent', (e) => {

            console.log('Nuevo mensaje:', e);

            let mine =
                e.message.user_id == window.USER_ID;

            let div = document.createElement('div');

            div.className =
                'message ' + (mine ? 'mine' : 'theirs');

            div.innerHTML = `
                <div class="bubble">
                    <strong>${e.message.user.name}</strong><br>
                    ${e.message.message}
                </div>
            `;

            messagesDiv.appendChild(div);

            scrollChat();
        });

    scrollChat();
});


/*
|--------------------------------------------------------------------------
| ENVIAR MENSAJE
|--------------------------------------------------------------------------
*/

function sendMessage() {

    let input = document.getElementById('messageInput');

    if (!input.value.trim()) return;

    axios.post('/chat/send', {
        conversation_id:
            document
                .getElementById('chat-app')
                .dataset.conversationId,

        message: input.value
    });

    input.value = '';
}


/*
|--------------------------------------------------------------------------
| AUTO SCROLL
|--------------------------------------------------------------------------
*/

function scrollChat() {

    const container =
        document.getElementById('messages');

    container.scrollTop =
        container.scrollHeight;
}

</script>

@endpush
