@php
    $chatsPayload = ($chats instanceof \Illuminate\Support\Collection ? $chats : collect($chats ?? []))
        ->values()
        ->all();
    $diskFilesPayload = ($diskFiles instanceof \Illuminate\Support\Collection ? $diskFiles : collect($diskFiles ?? []))
        ->values()
        ->all();
    $chatSidebarUrlTemplate = $chatSidebarUrlTemplate ?? route('chat.sidebar', ['member' => '__MEMBER__'], false);
    $userSidebarUrlTemplate = $userSidebarUrlTemplate ?? route('users.show', ['member' => '__USER__'], false);
@endphp

<div
    class="flex h-full min-h-0 overflow-hidden rounded-xl border border-slate-200 bg-white"
    data-sidepanel-scope
    data-chat-component
    x-data="rightRailChat({
        chats: @js($chatsPayload),
        showUrlTemplate: @js($conversationShowUrlTemplate),
        storeUrlTemplate: @js($conversationStoreUrlTemplate),
        diskFiles: @js($diskFilesPayload),
        sidebarUrlTemplate: @js($chatSidebarUrlTemplate),
        userSidebarUrlTemplate: @js($userSidebarUrlTemplate),
        initialChatId: @js((int) ($initialChatId ?? 0)),
        sidebarMode: true,
        pollInterval: 5000
    })"
    x-init="init()"
>
    <aside class="flex h-full w-80 shrink-0 flex-col border-r border-slate-200 bg-slate-50">
        <div class="border-b border-slate-200 px-4 py-3">
            <div class="flex items-center justify-between gap-3">
                <div>
                    <h3 class="text-sm font-semibold text-slate-900">Chat history</h3>
                    <p class="text-xs text-slate-500">All employee conversations</p>
                </div>
                <span class="rounded-full bg-white px-2 py-1 text-[11px] font-semibold text-slate-700" x-text="chats.length"></span>
            </div>
            <div class="mt-2 inline-flex items-center gap-2 rounded-full bg-white px-3 py-1 text-[11px] font-semibold text-slate-700">
                <x-menu-icon name="fa-solid fa-comments" class="h-3.5 w-3.5" />
                <span x-text="`${chatUnreadCount} unread`"></span>
            </div>
        </div>

        <div class="min-h-0 flex-1 space-y-2 overflow-y-auto p-3">
            <template x-if="chats.length === 0">
                <div class="rounded-lg border border-slate-200 bg-white px-3 py-3 text-xs text-slate-500">
                    No users found.
                </div>
            </template>

            @foreach ($chatsPayload as $chat)
                <button
                    type="button"
                    @click="selectChat({{ (int) $chat['id'] }})"
                    :class="selectedChatId === {{ (int) $chat['id'] }} ? 'border-indigo-300 bg-indigo-50' : 'border-slate-200 bg-white hover:border-indigo-200 hover:bg-indigo-50'"
                    class="w-full rounded-lg border px-3 py-2 text-left transition"
                >
                    <div class="flex items-start gap-3">
                        <span class="relative inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-slate-200 text-xs font-semibold text-slate-700">
                            @if ($chat['photo_url'])
                                <span class="h-full w-full overflow-hidden rounded-full">
                                    <img src="{{ $chat['photo_url'] }}" alt="{{ $chat['name'] }}" class="h-full w-full object-cover" style="{{ $chat['photo_style'] }}">
                                </span>
                            @else
                                {{ $chat['initials'] }}
                            @endif
                            <span class="absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full {{ $chat['is_online'] ? 'bg-emerald-400' : 'bg-slate-300' }} ring-2 ring-white"></span>
                        </span>

                        <div class="min-w-0 flex-1">
                            <div class="flex items-start justify-between gap-2">
                                <span
                                    class="block cursor-pointer truncate text-sm font-medium text-slate-900 hover:text-indigo-600 hover:underline"
                                    title="Open employee profile"
                                    @click.stop.prevent="openUserSidebar({{ (int) $chat['id'] }})"
                                >
                                    {{ $chat['name'] }}
                                </span>
                                <template x-if="chatUnreadFor({{ (int) $chat['id'] }}) > 0">
                                    <span class="inline-flex h-5 min-w-[1.25rem] items-center justify-center rounded-full bg-indigo-600 px-1 text-[10px] font-semibold text-white" x-text="chatUnreadFor({{ (int) $chat['id'] }})"></span>
                                </template>
                            </div>
                            <p class="truncate text-[11px] text-slate-500" x-text="chatSubtitle({{ (int) $chat['id'] }}, @js($chat['role_label']), @js($chat['last_message_human']))">{{ $chat['role_label'] }} · {{ $chat['last_message_human'] }}</p>
                            <p class="mt-0.5 truncate text-[11px] text-slate-500">{{ $chat['last_message'] }}</p>
                        </div>
                    </div>
                </button>
            @endforeach
        </div>
    </aside>

    <section class="flex min-w-0 flex-1 flex-col">
        <div class="border-b border-slate-200 px-4 py-3">
            <template x-if="selectedChat()">
                <div class="min-w-0">
                    <button
                        type="button"
                        class="truncate text-sm font-semibold text-slate-900 hover:text-indigo-600 hover:underline"
                        @click="openUserSidebar(selectedChatId)"
                        x-text="selectedChat().name"
                    ></button>
                    <p class="truncate text-[11px] text-slate-500" x-text="selectedChat().is_online ? 'online' : selectedChat().last_seen"></p>
                </div>
            </template>
            <template x-if="!selectedChat()">
                <p class="text-xs text-slate-500">{{ __('Select a person to talk to') }}</p>
            </template>
        </div>

        <div class="min-h-0 flex-1 overflow-y-auto bg-slate-50 px-4 py-3" x-ref="messagesBox">
            <template x-if="loadingMessages">
                <div class="text-center text-xs text-slate-500">{{ __('Loading dialogue...') }}</div>
            </template>

            <template x-if="!loadingMessages && messages.length === 0">
                <div class="text-center text-xs text-slate-500">{{ __('No messages yet.') }}</div>
            </template>

            <div class="space-y-2">
                <template x-for="message in messages" :key="message.id">
                    <div class="flex" :class="message.is_own ? 'justify-end' : 'justify-start'">
                        <div class="max-w-[86%] rounded-lg px-3 py-2 text-xs" :class="message.is_own ? 'bg-indigo-600 text-white' : 'bg-white text-slate-800 border border-slate-200'">
                            <template x-if="message.disk_attachment">
                                <a
                                    :href="message.disk_attachment.preview_url || message.disk_attachment.download_url"
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    class="mb-1 flex items-center gap-2 rounded-md border px-2 py-1.5 text-[11px] transition"
                                    :class="message.is_own ? 'border-indigo-200/60 bg-indigo-500/30 hover:bg-indigo-500/40' : 'border-slate-200 bg-slate-50 hover:bg-slate-100'"
                                >
                                    <span class="inline-flex h-3.5 w-3.5 items-center justify-center">
                                        <i class="text-[12px] leading-none" :class="message.disk_attachment.icon || 'fa-solid fa-file'"></i>
                                    </span>
                                    <span class="truncate" x-text="message.disk_attachment.name"></span>
                                </a>
                            </template>

                            <template x-if="message.body">
                                <p class="whitespace-pre-wrap break-words" x-text="message.body"></p>
                            </template>
                            <div class="mt-1 flex items-center justify-end gap-1 text-[10px] opacity-80">
                                <span x-text="message.sent_at_time"></span>
                                <template x-if="message.is_own">
                                    <span
                                        class="inline-flex items-center leading-none"
                                        :class="message.is_read ? 'text-sky-200' : 'text-white/80'"
                                        :title="message.is_read ? @js(__('Read')) : @js(__('Sent'))"
                                    >
                                        <template x-if="message.is_read">
                                            <x-menu-icon name="fa-solid fa-check-double" class="h-3 w-3" />
                                        </template>
                                        <template x-if="!message.is_read">
                                            <x-menu-icon name="fa-solid fa-check" class="h-3 w-3" />
                                        </template>
                                    </span>
                                </template>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
        </div>

        <div class="mt-auto shrink-0 border-t border-slate-200 bg-white p-3">
            <form @submit.prevent="sendMessage()" class="space-y-1.5">
                <div class="relative">
                    <textarea
                        x-ref="messageInput"
                        x-model="messageBody"
                        :disabled="!selectedChatId || sendingMessage"
                        @keydown.enter="if (!$event.shiftKey && !$event.isComposing) { $event.preventDefault(); sendMessage(); }"
                        rows="3"
                        maxlength="5000"
                        class="w-full resize-none rounded-md border-slate-300 py-2.5 pr-12 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                        placeholder="{{ __('Please enter a message...') }}"
                    ></textarea>

                    <button
                        type="submit"
                        :disabled="!canSend()"
                        class="absolute right-2 top-1/2 inline-flex h-8 w-8 -translate-y-1/2 items-center justify-center rounded-full bg-indigo-600 text-white hover:bg-indigo-500 disabled:cursor-not-allowed disabled:bg-indigo-300"
                        title="{{ __('Send message') }}"
                    >
                        <x-menu-icon name="fa-solid fa-paper-plane" class="h-3.5 w-3.5" />
                    </button>
                </div>

                <div class="flex items-center justify-between gap-2">
                    <div class="flex min-w-0 items-center gap-2">
                        <button
                            type="button"
                            @click="toggleDiskPicker()"
                            :disabled="!selectedChatId || sendingMessage || diskFiles.length === 0"
                            class="inline-flex items-center gap-1 rounded-md border border-slate-300 px-2 py-1 text-[11px] font-medium text-slate-700 hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50"
                        >
                            <x-menu-icon name="fa-solid fa-paperclip" class="h-3 w-3" />
                            <span>{{ __('Attach from disk') }}</span>
                        </button>

                        <template x-if="selectedDiskFile()">
                            <div class="inline-flex min-w-0 items-center gap-1 rounded-md border border-indigo-200 bg-indigo-50 px-2 py-1 text-[11px] text-indigo-700">
                                <span class="inline-flex h-3.5 w-3.5 items-center justify-center">
                                    <i class="text-[12px] leading-none" :class="selectedDiskFile().icon || 'fa-solid fa-file'"></i>
                                </span>
                                <span class="max-w-[13rem] truncate" x-text="selectedDiskFile().name"></span>
                                <button
                                    type="button"
                                    @click="removeDiskAttachment()"
                                    class="inline-flex h-4 w-4 items-center justify-center rounded hover:bg-indigo-100"
                                    title="{{ __('Remove') }}"
                                >
                                    <x-menu-icon name="fa-solid fa-xmark" class="h-3 w-3" />
                                </button>
                            </div>
                        </template>
                    </div>

                    <p class="truncate text-[11px] text-red-500" x-text="errorMessage"></p>
                </div>

                <div x-show="showDiskPicker" x-cloak class="rounded-md border border-slate-200 bg-slate-50 p-2">
                    <input
                        x-ref="diskSearchInput"
                        x-model="diskSearch"
                        type="text"
                        class="w-full rounded-md border-slate-300 py-1.5 text-xs shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                        placeholder="{{ __('Search file by name or folder') }}"
                    >

                    <div class="mt-2 max-h-44 space-y-1 overflow-y-auto pr-1">
                        <template x-if="filteredDiskFiles().length === 0">
                            <p class="px-1 py-1 text-[11px] text-slate-500">{{ __('No files in disk.') }}</p>
                        </template>

                        <template x-for="file in filteredDiskFiles()" :key="`disk-file-${file.id}`">
                            <button
                                type="button"
                                @click="attachDiskFile(file)"
                                class="flex w-full items-center justify-between rounded-md border border-slate-200 bg-white px-2 py-1.5 text-left text-xs text-slate-700 transition hover:border-indigo-300 hover:bg-indigo-50"
                            >
                                <span class="flex min-w-0 items-center gap-2">
                                    <span class="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded border border-slate-200 bg-slate-50 text-slate-500">
                                        <i class="text-[11px] leading-none" :class="file.icon || 'fa-solid fa-file'"></i>
                                    </span>
                                    <span class="min-w-0">
                                    <span class="block truncate font-medium" x-text="file.name"></span>
                                    <span class="block truncate text-[10px] text-slate-500" x-text="file.folder || '—'"></span>
                                    </span>
                                </span>
                                <span class="inline-flex h-4 w-4 shrink-0 items-center justify-center text-slate-400">
                                    <x-menu-icon name="fa-solid fa-link" class="h-3 w-3" />
                                </span>
                            </button>
                        </template>
                    </div>
                </div>
            </form>
        </div>
    </section>
</div>
