@extends('layouts.app')

@section('title', ($detail->contact->display_name ?: 'Pessoa').' — Timeline')
@section('page-title', 'Histórico da conversa')

@section('content')
    @include('partials.flash')

    <div class="mb-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <a
            href="{{ route('people.inbox') }}"
            class="text-sm font-medium text-emerald-700 hover:text-emerald-800"
        >
            ← Voltar para Caixa de entrada
        </a>
        <a
            href="{{ route('people.index') }}"
            class="inline-flex items-center justify-center rounded-lg border border-emerald-600 bg-white px-3 py-1.5 text-sm font-semibold text-emerald-700 shadow-sm transition hover:bg-emerald-50"
        >
            Ver funil
        </a>
    </div>

    <div class="mb-6 rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
        <div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
            <div>
                <h1 class="text-2xl font-semibold text-slate-900">
                    {{ $detail->contact->display_name ?: $detail->contact->phone ?: 'Pessoa' }}
                </h1>
                @if ($detail->contact->phone)
                    <p class="mt-1 text-sm text-slate-500">{{ $detail->contact->phone }}</p>
                @endif
            </div>
            <div class="flex flex-wrap items-center gap-2">
                @if ($whatsAppUrl)
                    <a
                        href="{{ $whatsAppUrl }}"
                        target="_blank"
                        rel="noopener noreferrer"
                        class="inline-flex items-center rounded-lg bg-emerald-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-emerald-700"
                    >
                        Abrir WhatsApp
                    </a>
                @endif
                <span class="inline-flex rounded-full bg-sky-100 px-3 py-1 text-xs font-medium text-sky-800">
                    {{ $detail->statusLabel }}
                </span>
                @if ($detail->resultLabel)
                    <span class="inline-flex rounded-full bg-slate-100 px-3 py-1 text-xs font-medium text-slate-700">
                        {{ $detail->resultLabel }}
                    </span>
                @endif
            </div>
        </div>

        <dl class="mt-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            <div>
                <dt class="text-xs font-medium uppercase tracking-wide text-slate-500">Última mensagem</dt>
                <dd class="mt-1 text-sm text-slate-800">
                    {{ $detail->lastMessagePreview ?: '—' }}
                </dd>
            </div>
            <div>
                <dt class="text-xs font-medium uppercase tracking-wide text-slate-500">Última interação</dt>
                <dd class="mt-1 text-sm text-slate-800">
                    {{ $detail->lastInteractionAt?->diffForHumans() ?? '—' }}
                </dd>
            </div>
            <div>
                <dt class="text-xs font-medium uppercase tracking-wide text-slate-500">Quem respondeu</dt>
                <dd class="mt-1 text-sm text-slate-800">
                    {{ $detail->lastResponderLabel ?? '—' }}
                </dd>
            </div>
            <div>
                <dt class="text-xs font-medium uppercase tracking-wide text-slate-500">Status</dt>
                <dd class="mt-1 text-sm text-slate-800">
                    {{ $detail->statusLabel }}
                    @if ($detail->resultLabel)
                        · {{ $detail->resultLabel }}
                    @endif
                </dd>
            </div>
        </dl>
    </div>

    <div class="grid gap-6 xl:grid-cols-3">
        <div class="space-y-6 xl:col-span-2">
            @isset($summary)
                @include('conversations.people.partials.conversation-summary', ['summary' => $summary])
            @endisset

            @if ($detail->conversation !== null)
                <section aria-label="Mensagens recentes">
                    <h2 class="mb-4 text-lg font-semibold text-slate-900">Conversa</h2>

                    @if ($thread->isEmpty())
                        <div class="rounded-xl border border-slate-200 bg-white p-6 text-center text-sm text-slate-500 shadow-sm">
                            Nenhuma mensagem registrada ainda.
                        </div>
                    @else
                        <div class="max-h-96 space-y-3 overflow-y-auto rounded-xl border border-slate-200 bg-slate-50 p-4">
                            @foreach ($thread as $message)
                                <div @class([
                                    'flex',
                                    'justify-end' => $message->direction->value === 'outbound',
                                    'justify-start' => $message->direction->value === 'inbound',
                                ])>
                                    <div @class([
                                        'max-w-[85%] rounded-2xl px-4 py-2 text-sm shadow-sm',
                                        'bg-emerald-600 text-white' => $message->direction->value === 'outbound' && $message->senderLabel !== 'Assistente',
                                        'bg-white text-slate-800 ring-1 ring-slate-200' => $message->direction->value === 'inbound',
                                        'bg-sky-100 text-slate-800' => $message->direction->value === 'outbound' && $message->senderLabel === 'Assistente',
                                    ])>
                                        <p class="mb-1 text-[10px] font-semibold uppercase tracking-wide opacity-80">
                                            {{ $message->senderLabel }} · {{ $message->occurredAt->format('d/m H:i') }}
                                        </p>
                                        <p class="whitespace-pre-wrap">{{ $message->body }}</p>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    @endif

                    @if ($canReply)
                        <form
                            method="POST"
                            action="{{ route('people.reply', $contact) }}"
                            class="mt-4 rounded-xl border border-slate-200 bg-white p-4 shadow-sm"
                            x-data="brokerReplyForm({
                                suggestUrl: @js(route('people.suggest-reply', $contact)),
                                conversationId: @js((string) $detail->conversation->id),
                                csrfToken: @js(csrf_token()),
                            })"
                        >
                            @csrf
                            <input type="hidden" name="conversation_id" value="{{ $detail->conversation->id }}">
                            <input type="hidden" name="suggestion_id" x-model="suggestionId">
                            <div class="mb-2 flex flex-wrap items-center justify-between gap-2">
                                <label for="reply-body" class="text-sm font-medium text-slate-700">Responder pelo painel</label>
                                <button
                                    type="button"
                                    @click="suggest()"
                                    :disabled="loading"
                                    class="inline-flex items-center gap-1.5 rounded-lg border border-violet-200 bg-violet-50 px-3 py-1.5 text-sm font-medium text-violet-800 hover:bg-violet-100 disabled:cursor-not-allowed disabled:opacity-60"
                                >
                                    <span aria-hidden="true">✨</span>
                                    <span x-text="loading ? 'Gerando…' : 'Sugerir resposta'"></span>
                                </button>
                            </div>
                            <textarea
                                id="reply-body"
                                name="body"
                                x-model="body"
                                rows="5"
                                required
                                maxlength="4000"
                                placeholder="Sua mensagem será enviada pelo WhatsApp da imobiliária…"
                                class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-emerald-500 focus:outline-none focus:ring-2 focus:ring-emerald-500/20"
                            >{{ old('body') }}</textarea>
                            <p x-show="error" x-cloak class="mt-2 text-sm text-red-600" x-text="error"></p>
                            @error('body')<p class="mt-1 text-sm text-red-600">{{ $message }}</p>@enderror
                            <p class="mt-1 text-xs text-slate-500">
                                A automação está pausada — edite a sugestão à vontade antes de enviar.
                            </p>
                            <div class="mt-3 flex justify-end">
                                <button type="submit" class="rounded-lg bg-emerald-600 px-4 py-2 text-sm font-semibold text-white hover:bg-emerald-700">
                                    Enviar mensagem
                                </button>
                            </div>
                        </form>

                        @push('scripts')
                            <script>
                                document.addEventListener('alpine:init', () => {
                                    Alpine.data('brokerReplyForm', ({ suggestUrl, conversationId, csrfToken }) => ({
                                        body: @js(old('body', '')),
                                        suggestionId: @js(old('suggestion_id', '')),
                                        loading: false,
                                        error: '',
                                        async suggest() {
                                            this.loading = true;
                                            this.error = '';

                                            try {
                                                const response = await fetch(suggestUrl, {
                                                    method: 'POST',
                                                    headers: {
                                                        'Content-Type': 'application/json',
                                                        'Accept': 'application/json',
                                                        'X-CSRF-TOKEN': csrfToken,
                                                    },
                                                    body: JSON.stringify({ conversation_id: conversationId }),
                                                });

                                                const data = await response.json();

                                                if (! response.ok) {
                                                    this.error = data.message ?? 'Não foi possível gerar a sugestão.';
                                                    return;
                                                }

                                                this.body = data.suggestion ?? '';
                                                this.suggestionId = data.suggestion_id ?? '';
                                            } catch (e) {
                                                this.error = 'Não foi possível gerar a sugestão. Tente novamente.';
                                            } finally {
                                                this.loading = false;
                                            }
                                        },
                                    }));
                                });
                            </script>
                        @endpush
                    @endif
                </section>
            @endif

            <section aria-label="Timeline da conversa">
                <h2 class="mb-4 text-lg font-semibold text-slate-900">Linha do tempo</h2>

                @if ($detail->timeline->isEmpty())
                    <div class="rounded-xl border border-slate-200 bg-white p-8 text-center text-slate-500 shadow-sm">
                        Ainda não há eventos registrados para esta pessoa.
                    </div>
                @else
                    <ol class="relative space-y-0 border-l-2 border-slate-200 pl-6">
                        @php
                            $currentDay = null;
                        @endphp
                        @foreach ($detail->timeline as $item)
                            @php
                                $dayKey = $item->occurredAt->format('Y-m-d');
                                $dayLabel = $item->occurredAt->isToday()
                                    ? 'Hoje'
                                    : ($item->occurredAt->isYesterday() ? 'Ontem' : $item->occurredAt->translatedFormat('d/m/Y'));
                            @endphp
                            @if ($currentDay !== $dayKey)
                                @php $currentDay = $dayKey; @endphp
                                <li class="mb-4 -ml-[1.6rem] list-none">
                                    <span class="inline-flex rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-600">
                                        {{ $dayLabel }}
                                    </span>
                                </li>
                            @endif
                            <li class="relative mb-6 list-none">
                                <span
                                    @class([
                                        'absolute -left-[1.85rem] top-1.5 h-3 w-3 rounded-full ring-4 ring-slate-100',
                                        'bg-emerald-500' => $item->actor->value === 'client',
                                        'bg-sky-500' => $item->actor->value === 'assistant',
                                        'bg-violet-500' => $item->actor->value === 'broker',
                                        'bg-slate-400' => $item->actor->value === 'system',
                                    ])
                                    aria-hidden="true"
                                ></span>
                                <div class="rounded-lg border border-slate-100 bg-white p-4 shadow-sm">
                                    <div class="flex flex-wrap items-center gap-2">
                                        <p class="font-medium text-slate-900">{{ $item->label }}</p>
                                        <span class="rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-600">
                                            {{ $item->actor->label() }}
                                            @if ($item->actorName)
                                                · {{ $item->actorName }}
                                            @endif
                                        </span>
                                        <time class="text-xs text-slate-400" datetime="{{ $item->occurredAt->toIso8601String() }}">
                                            {{ $item->occurredAt->format('H:i') }}
                                        </time>
                                    </div>
                                    @if ($item->detail)
                                        <p class="mt-2 whitespace-pre-wrap text-sm text-slate-600">{{ $item->detail }}</p>
                                    @endif
                                </div>
                            </li>
                        @endforeach
                    </ol>
                @endif
            </section>
        </div>

        <aside class="space-y-6 xl:col-span-1 xl:sticky xl:top-6 xl:max-h-[calc(100vh-5rem)] xl:self-start xl:overflow-y-auto">
            @include('conversations.people.partials.broker-notes-panel', [
                'brokerNotes' => $brokerNotes,
                'contact' => $contact,
                'detail' => $detail,
            ])
            @include('conversations.people.partials.related-properties-panel', ['relatedProperties' => $relatedProperties])
        </aside>
    </div>
@endsection
