<x-cliente-layout title="Mensagens — OPCON Portal">

<div style="margin-bottom:1.5rem;">
    <h1 class="cli-page-title">Mensagens</h1>
    <p class="cli-page-subtitle">Comunique-se diretamente com nossa equipe sobre seu contrato.</p>
</div>

@if($contratos->isEmpty())
    <div class="cli-card" style="padding:3rem; text-align:center;">
        <div style="width:56px;height:56px;border-radius:14px;background:#e8f8f1;display:flex;align-items:center;justify-content:center;margin:0 auto 1rem;">
            <svg style="width:26px;height:26px;color:#25b87e;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"/>
            </svg>
        </div>
        <p style="font-size:0.9375rem; font-weight:600; color:#1e3a5f; margin:0 0 0.5rem;">Nenhum contrato ativo</p>
        <p style="font-size:0.8125rem; color:#94a3b8; margin:0 0 1.25rem;">Entre em contato pelo WhatsApp enquanto isso.</p>
        <a href="https://wa.me/556332197100"
           style="display:inline-flex;align-items:center;gap:0.5rem;padding:0.625rem 1.25rem;background:#25b87e;color:#fff;border-radius:8px;font-size:0.875rem;font-weight:600;text-decoration:none;">
            <svg style="width:15px;height:15px;" fill="currentColor" viewBox="0 0 24 24">
                <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/>
            </svg>
            Falar no WhatsApp
        </a>
    </div>
@else
    <div x-data="mensagensChat()" x-init="init()" class="msg-layout">

        {{-- Sidebar: contract list --}}
        <div class="msg-sidebar cli-card" style="overflow:hidden;">
            <div style="padding:0.75rem 1rem; border-bottom:1px solid #f1f5f9;">
                <p style="font-size:0.6875rem; font-weight:700; text-transform:uppercase; letter-spacing:0.06em; color:#94a3b8; margin:0;">Seus contratos</p>
            </div>
            @foreach($contratos as $c)
                <button @click="selectContrato({{ $c->id }})"
                        :style="contratoId === {{ $c->id }} ? 'background:#f0fdf4;' : ''"
                        style="width:100%; text-align:left; padding:0.875rem 1rem; border:none; border-bottom:1px solid #f8fafc; cursor:pointer; font-family:inherit; transition:background 0.15s; background:transparent; position:relative;"
                        onmouseover="this.style.background='#f8fafc'" onmouseout="if(!this.style.background.includes('240'))this.style.background='transparent'">
                    <span :class="contratoId === {{ $c->id }} ? 'opacity-100' : 'opacity-0'"
                          style="position:absolute;left:0;top:0;bottom:0;width:3px;background:#25b87e;border-radius:0 2px 2px 0;transition:opacity 0.15s;"></span>
                    <p style="font-size:0.8125rem; font-weight:600; color:#1e3a5f; margin:0; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">{{ $c->razao_social }}</p>
                    <p style="font-size:0.6875rem; color:#94a3b8; margin:0.15rem 0 0;">{{ $c->regime_tributario }}</p>
                </button>
            @endforeach
        </div>

        {{-- Chat panel --}}
        <div class="cli-card msg-chat" style="overflow:hidden; display:flex; flex-direction:column;">

            {{-- Chat header --}}
            <div style="padding:0.875rem 1.25rem; border-bottom:1px solid #f1f5f9; display:flex; align-items:center; gap:0.75rem; flex-shrink:0;">
                <div style="width:38px;height:38px;border-radius:10px;background:#1e3a5f;color:#fff;display:flex;align-items:center;justify-content:center;font-size:0.8125rem;font-weight:800;flex-shrink:0;letter-spacing:-0.5px;">OP</div>
                <div style="flex:1;min-width:0;">
                    <p style="font-size:0.875rem; font-weight:700; color:#1e3a5f; margin:0;">OPCON Soluções Contábeis</p>
                    <div style="display:flex;align-items:center;gap:0.375rem;">
                        <span style="width:6px;height:6px;border-radius:50%;background:#25b87e;display:inline-block;"></span>
                        <p style="font-size:0.75rem; color:#25b87e; margin:0;">Respondemos em até 1 dia útil</p>
                    </div>
                </div>
            </div>

            {{-- Messages area --}}
            <div x-ref="chatBox"
                 style="flex:1; overflow-y:auto; padding:1.25rem; display:flex; flex-direction:column; gap:0.75rem; min-height:320px; max-height:460px;">

                <template x-if="loading">
                    <div style="display:flex;align-items:center;justify-content:center;padding:3rem;gap:0.75rem;">
                        <div style="width:20px;height:20px;border:2.5px solid #e2e8f0;border-top-color:#1e3a5f;border-radius:50%;animation:spin 0.7s linear infinite;"></div>
                        <span style="font-size:0.8125rem;color:#94a3b8;">Carregando mensagens…</span>
                    </div>
                </template>

                <template x-if="!loading && mensagens.length === 0">
                    <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;padding:3rem;gap:0.5rem;">
                        <div style="width:48px;height:48px;border-radius:12px;background:#f1f5f9;display:flex;align-items:center;justify-content:center;">
                            <svg style="width:22px;height:22px;color:#cbd5e1;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"/>
                            </svg>
                        </div>
                        <p style="font-size:0.875rem;font-weight:600;color:#1e3a5f;margin:0;">Nenhuma mensagem ainda</p>
                        <p style="font-size:0.8125rem;color:#94a3b8;margin:0;">Inicie a conversa abaixo.</p>
                    </div>
                </template>

                <template x-for="m in mensagens" :key="m.id">
                    <div :style="m.de_cliente ? 'align-self:flex-end;' : 'align-self:flex-start;'"
                         style="max-width:78%;">
                        <div :style="m.de_cliente
                                ? 'background:#1e3a5f; color:#fff; border-radius:14px 14px 3px 14px;'
                                : 'background:#f1f5f9; color:#1e3a5f; border-radius:14px 14px 14px 3px;'"
                             style="padding:0.6875rem 1rem; font-size:0.875rem; line-height:1.55; word-break:break-word;">
                            <span x-text="m.texto"></span>
                        </div>
                        <p :style="m.de_cliente ? 'text-align:right;' : ''"
                           style="font-size:0.6875rem; color:#94a3b8; margin:0.3rem 0.25rem 0;"
                           x-text="(m.de_cliente ? 'Você' : 'OPCON') + ' · ' + m.created_at"></p>
                    </div>
                </template>
            </div>

            {{-- Input --}}
            <div style="padding:0.875rem 1.25rem; border-top:1px solid #f1f5f9; display:flex; gap:0.625rem; align-items:flex-end; flex-shrink:0;">
                <textarea x-model="texto"
                          @keydown.enter.prevent="if(!$event.shiftKey) sendMensagem()"
                          placeholder="Mensagem… (Enter para enviar, Shift+Enter para nova linha)"
                          rows="2"
                          style="flex:1; padding:0.625rem 0.875rem; border:1.5px solid #e2e8f0; border-radius:10px; font-size:0.875rem; font-family:inherit; color:#1e3a5f; resize:none; outline:none; transition:border-color 0.15s; line-height:1.5;"
                          onfocus="this.style.borderColor='#25b87e'" onblur="this.style.borderColor='#e2e8f0'"></textarea>
                <button @click="sendMensagem()"
                        :disabled="!texto.trim() || sending"
                        style="width:42px;height:42px;background:#25b87e;color:#fff;border:none;border-radius:10px;cursor:pointer;transition:background 0.15s,opacity 0.15s;display:flex;align-items:center;justify-content:center;flex-shrink:0;"
                        :style="(!texto.trim() || sending) ? 'opacity:0.5;cursor:not-allowed;' : 'opacity:1;'"
                        onmouseover="if(!this.disabled)this.style.background='#1fa96e'" onmouseout="this.style.background='#25b87e'">
                    <template x-if="!sending">
                        <svg style="width:18px;height:18px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/>
                        </svg>
                    </template>
                    <template x-if="sending">
                        <div style="width:16px;height:16px;border:2px solid rgba(255,255,255,0.4);border-top-color:#fff;border-radius:50%;animation:spin 0.7s linear infinite;"></div>
                    </template>
                </button>
            </div>
        </div>
    </div>
@endif

<style>
@keyframes spin { to { transform: rotate(360deg); } }

.msg-layout {
    display: grid;
    grid-template-columns: 240px 1fr;
    gap: 1rem;
    align-items: start;
}
.msg-sidebar { position: sticky; top: 80px; }

@media (max-width: 767px) {
    .msg-layout {
        grid-template-columns: 1fr;
    }
    .msg-sidebar { position: static; }
    .msg-chat { min-height: 400px; }
}
</style>

<script>
function mensagensChat() {
    return {
        contratoId: {{ $contratoAtivo?->id ?? 'null' }},
        mensagens: [],
        texto: '',
        loading: false,
        sending: false,

        init() {
            if (this.contratoId) this.loadMensagens();
        },

        selectContrato(id) {
            this.contratoId = id;
            this.mensagens  = [];
            this.loadMensagens();
        },

        async loadMensagens() {
            if (!this.contratoId) return;
            this.loading = true;
            try {
                const res  = await fetch(`/cliente/mensagens?contrato_id=${this.contratoId}`, {
                    headers: { 'Accept': 'application/json' }
                });
                const data = await res.json();
                this.mensagens = data.mensagens || [];
                this.$nextTick(() => this.scrollBottom());
            } catch (e) {}
            finally { this.loading = false; }
        },

        async sendMensagem() {
            if (!this.texto.trim() || this.sending) return;
            this.sending = true;
            const msg = this.texto;
            this.texto = '';
            try {
                const res  = await fetch('/cliente/mensagens', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content,
                        'Accept':       'application/json',
                    },
                    body: JSON.stringify({ contrato_id: this.contratoId, texto: msg }),
                });
                const data = await res.json();
                if (data.ok) {
                    this.mensagens.push(data.mensagem);
                    this.$nextTick(() => this.scrollBottom());
                } else {
                    this.texto = msg;
                }
            } catch (e) { this.texto = msg; }
            finally { this.sending = false; }
        },

        scrollBottom() {
            const box = this.$refs.chatBox;
            if (box) box.scrollTop = box.scrollHeight;
        },
    };
}
</script>

</x-cliente-layout>
