@php
    $user = Auth::user();
    $rightRailCollapsed = (bool) ($user?->right_rail_collapsed ?? false);
    $rail = app(\App\Support\RightRailManager::class)->data($user);
    $notifications = $rail['notifications'];
    $chats = $rail['chats'];
    $unreadCount = (int) $rail['unread_count'];
    $chatUnreadCount = (int) ($rail['chat_unread_count'] ?? 0);
    $notificationFeedUrl = route('notifications.feed', [], false);
    $notificationsPayload = $notifications->values()->map(function (array $item): array {
        $key = (string) ($item['key'] ?? '');
        $item['open_url'] = $key !== ''
            ? route('notifications.open', ['key' => $key])
            : route('dashboard');

        return $item;
    })->all();
    $conversationShowUrlTemplate = route('chat.conversations.show', ['member' => '__MEMBER__'], false);
    $conversationStoreUrlTemplate = route('chat.conversations.store', ['member' => '__MEMBER__'], false);
    $chatSidebarUrlTemplate = route('chat.sidebar', ['member' => '__MEMBER__'], false);
    $userSidebarUrlTemplate = route('users.show', ['member' => '__USER__'], false);

    $parts = preg_split('/\s+/u', trim((string) $user->name)) ?: [];
    $first = $parts[0] ?? '';
    $last = $parts[1] ?? '';
    $profileInitials = mb_strtoupper(mb_substr($first, 0, 1).mb_substr($last, 0, 1));
    if ($profileInitials === '') {
        $profileInitials = mb_strtoupper(mb_substr((string) $user->name, 0, 1));
    }

    $userPhotoUrl = \App\Support\ProfileAvatarManager::url($user->profile_photo_path);
    $userPhotoStyle = \App\Support\ProfileAvatarManager::style(
        $user->profile_photo_focus_x,
        $user->profile_photo_focus_y,
        $user->profile_photo_zoom
    );
@endphp

<div
    x-data="rightRailToggle({
        collapsed: @js($rightRailCollapsed),
        updateUrl: @js(route('profile.right-rail')),
    })"
    x-init="init()"
>
    <button
        type="button"
        x-show="collapsed"
        @click="toggle()"
        data-right-rail-show-button
        class="fixed right-2 top-28 z-50 inline-flex h-10 w-10 items-center justify-center rounded-full border border-slate-200 bg-white text-slate-600 shadow hover:text-slate-900"
        style="{{ $rightRailCollapsed ? '' : 'display: none;' }}"
        title="{{ __('Show right panel') }}"
        aria-label="{{ __('Show right panel') }}"
    >
        <x-menu-icon name="fa-solid fa-chevron-left" class="h-4 w-4" />
    </button>

    <aside
        x-show="!collapsed"
        class="app-right-rail fixed right-0 top-0 z-40 h-screen w-80 border-l border-slate-200 bg-white/95 backdrop-blur"
        style="{{ $rightRailCollapsed ? 'display: none;' : '' }}"
        data-right-rail-panel
        data-sidepanel-scope
    >
        <div class="flex h-full flex-col">
            <div
                class="border-b border-slate-200 p-4"
                x-data="rightRailNotifications({
                    notifications: @js($notificationsPayload),
                    unreadCount: @js($unreadCount),
                    feedUrl: @js($notificationFeedUrl),
                    pollInterval: 10000
                })"
                x-init="init()"
            >
                <div class="mb-3 flex items-start justify-between gap-3">
                    <div>
                        <h3 class="text-sm font-semibold text-slate-900">Notifications</h3>
                        <p class="text-xs text-slate-500">Top event feed</p>
                    </div>

                    <div class="flex items-center gap-2">
                        <button
                            type="button"
                            @click="toggle()"
                            class="inline-flex h-9 w-9 items-center justify-center rounded-full border border-slate-200 text-slate-500 hover:text-slate-900"
                            title="{{ __('Hide right panel') }}"
                            aria-label="{{ __('Hide right panel') }}"
                        >
                            <x-menu-icon name="fa-solid fa-chevron-right" class="h-3.5 w-3.5" />
                        </button>
                        <a
                            href="{{ route('profile.edit') }}"
                            title="{{ __('Profile') }}"
                            class="relative inline-flex h-10 w-10 items-center justify-center rounded-full bg-sky-500 text-xs font-semibold text-white ring-2 ring-sky-300/50 transition hover:bg-sky-400"
                        >
                            @if ($userPhotoUrl)
                                <span class="h-full w-full overflow-hidden rounded-full">
                                    <img src="{{ $userPhotoUrl }}" alt="Profile" class="h-full w-full object-cover" style="{{ $userPhotoStyle }}">
                                </span>
                            @else
                                {{ $profileInitials }}
                            @endif
                            <span class="absolute bottom-0 right-0 h-2.5 w-2.5 rounded-full {{ $user->last_seen_at && $user->last_seen_at->gte(now()->subMinutes(5)) ? 'bg-emerald-400' : 'bg-slate-300' }} ring-2 ring-white"></span>
                        </a>
                    </div>
                </div>

            <div class="mb-2 inline-flex items-center gap-2 rounded-full bg-slate-100 px-3 py-1 text-xs font-medium text-slate-700">
                <x-menu-icon name="fa-solid fa-bell" class="h-4 w-4" />
                <span x-text="`${unreadCount} notifications`">{{ $unreadCount }} notifications</span>
            </div>

            <div class="max-h-48 space-y-2 overflow-y-auto pr-1">
                <template x-if="notifications.length === 0">
                    <div class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-3 text-xs text-slate-500">
                        There are no new notifications.
                    </div>
                </template>

                <template x-for="item in notifications" :key="item.key">
                    <a
                        :href="item.open_url || '#'"
                        class="group flex items-start gap-2 rounded-lg border border-slate-200 bg-slate-50 px-2 py-2 hover:border-indigo-200 hover:bg-indigo-50"
                    >
                        <span class="mt-0.5 inline-flex h-6 w-6 items-center justify-center rounded-md bg-white text-slate-600">
                            <span class="inline-flex h-4 w-4 items-center justify-center">
                                <i :class="notificationIconClass(item.icon)"></i>
                            </span>
                        </span>

                        <span class="min-w-0 flex-1">
                            <span class="block truncate text-xs font-medium text-slate-900" x-text="item.title"></span>
                            <span class="mt-0.5 block truncate text-[11px] text-slate-500" x-text="item.subtitle"></span>
                        </span>

                        <span class="shrink-0 text-[10px] text-slate-400" x-text="item.time"></span>
                    </a>
                </template>
            </div>
            </div>

            <div
                class="min-h-0 flex flex-1 flex-col p-4"
                x-data="rightRailChat({
                    chats: @js($chats->values()->all()),
                    showUrlTemplate: @js($conversationShowUrlTemplate),
                    storeUrlTemplate: @js($conversationStoreUrlTemplate),
                    sidebarUrlTemplate: @js($chatSidebarUrlTemplate),
                    userSidebarUrlTemplate: @js($userSidebarUrlTemplate),
                    initialChatId: null,
                    chatListOnly: true,
                    sidebarMode: false,
                    pollInterval: 5000
                })"
                x-init="init()"
            >
                <div class="mb-3 flex items-center justify-between">
                    <div>
                        <h3 class="text-sm font-semibold text-slate-900">Chats</h3>
                        <p class="text-xs text-slate-500">Opens in sidebar</p>
                    </div>
                    <span class="rounded-full bg-slate-100 px-2 py-1 text-[11px] font-semibold text-slate-700" x-text="chats.length"></span>
                </div>

                <div class="mb-3 inline-flex items-center gap-2 rounded-full bg-slate-100 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 class="min-h-0 flex-1 space-y-2 overflow-y-auto pr-1">
                    <template x-if="chats.length === 0">
                        <div class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-3 text-xs text-slate-500">
                            No users found.
                        </div>
                    </template>

                    @foreach ($chats as $chat)
                        <button
                            type="button"
                            @click="openChatSidebar({{ (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>
            </div>
        </div>
    </aside>
</div>

@once
    <script>
        document.addEventListener('alpine:init', () => {
            Alpine.data('rightRailToggle', ({ collapsed = false, updateUrl = '' }) => ({
                collapsed: Boolean(collapsed),
                updateUrl: typeof updateUrl === 'string' ? updateUrl : '',
                csrfToken: document.querySelector('meta[name=csrf-token]')?.getAttribute('content') ?? '',

                init() {
                    this.applyLayout();
                },

                toggle() {
                    this.collapsed = !this.collapsed;
                    this.applyLayout();
                    this.saveState();
                },

                applyLayout() {
                    if (document.body) {
                        document.body.dataset.rightRailCollapsed = this.collapsed ? '1' : '0';
                    }
                    const root = document.querySelector('[data-right-rail-root]');
                    const content = document.querySelector('[data-right-rail-content]');
                    if (root) {
                        root.dataset.rightRailCollapsed = this.collapsed ? '1' : '0';
                    }
                    if (content) {
                        content.classList.toggle('pr-[20rem]', !this.collapsed);
                        content.classList.toggle('pr-0', this.collapsed);
                    }
                },

                saveState() {
                    if (!this.updateUrl) {
                        return;
                    }
                    fetch(this.updateUrl, {
                        method: 'PATCH',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json',
                            'X-CSRF-TOKEN': this.csrfToken,
                        },
                        body: JSON.stringify({ collapsed: this.collapsed }),
                    }).catch(() => {});
                },
            }));

            Alpine.data('rightRailNotifications', ({
                notifications = [],
                unreadCount = 0,
                feedUrl = '',
                pollInterval = 10000,
            }) => ({
                notifications: [],
                unreadCount: Number(unreadCount || 0),
                feedUrl: typeof feedUrl === 'string' ? feedUrl : '',
                pollInterval: Number(pollInterval || 10000),
                pollHandle: null,
                loadingFeed: false,

                init() {
                    this.$el?.addEventListener('crm:right-rail-notifications:destroy', () => {
                        this.stopPolling();
                    }, { once: true });

                    this.notifications = this.normalizeNotifications(notifications);
                    this.unreadCount = Number(this.unreadCount || this.notifications.length);
                    this.startPolling();
                },

                notificationIconClass(icon) {
                    const normalizedIcon = String(icon || '').trim();
                    const iconClass = normalizedIcon !== '' ? normalizedIcon : 'fa-solid fa-bell';

                    return `${iconClass} text-sm leading-none`;
                },

                normalizeNotifications(items) {
                    if (!Array.isArray(items)) {
                        return [];
                    }

                    return items
                        .map((item) => {
                            if (!item || typeof item !== 'object') {
                                return null;
                            }

                            return {
                                key: String(item.key || ''),
                                icon: String(item.icon || ''),
                                title: String(item.title || ''),
                                subtitle: String(item.subtitle || ''),
                                time: String(item.time || ''),
                                open_url: String(item.open_url || ''),
                            };
                        })
                        .filter((item) => item && item.key !== '');
                },

                startPolling() {
                    if (!this.feedUrl) {
                        return;
                    }

                    this.stopPolling();
                    this.reload(true);
                    this.pollHandle = window.setInterval(() => {
                        this.reload(true);
                    }, this.pollInterval);
                },

                stopPolling() {
                    if (!this.pollHandle) {
                        return;
                    }

                    window.clearInterval(this.pollHandle);
                    this.pollHandle = null;
                },

                async reload(isSilent = false) {
                    if (!this.feedUrl || this.loadingFeed) {
                        return;
                    }

                    this.loadingFeed = true;

                    try {
                        const response = await window.fetch(this.feedUrl, {
                            headers: {
                                Accept: 'application/json',
                                'X-Requested-With': 'XMLHttpRequest',
                            },
                        });

                        if (!response.ok) {
                            throw new Error(`HTTP ${response.status}`);
                        }

                        const payload = await response.json();
                        this.notifications = this.normalizeNotifications(payload.notifications);
                        this.unreadCount = Number(payload.unread_count || this.notifications.length);
                    } catch (error) {
                        if (!isSilent) {
                            this.unreadCount = Number(this.notifications.length || 0);
                        }
                    } finally {
                        this.loadingFeed = false;
                    }
                },
            }));

            Alpine.data('rightRailChat', ({
                chats,
                showUrlTemplate,
                storeUrlTemplate,
                diskFiles = [],
                sidebarUrlTemplate = null,
                userSidebarUrlTemplate = null,
                initialChatId = null,
                chatListOnly = false,
                sidebarMode = false,
                pollInterval,
            }) => ({
                chats: Array.isArray(chats) ? chats : [],
                showUrlTemplate,
                storeUrlTemplate,
                diskFiles: Array.isArray(diskFiles) ? diskFiles : [],
                sidebarUrlTemplate: typeof sidebarUrlTemplate === 'string' ? sidebarUrlTemplate : '',
                userSidebarUrlTemplate: typeof userSidebarUrlTemplate === 'string' ? userSidebarUrlTemplate : '',
                initialChatId: Number(initialChatId || 0),
                chatListOnly: Boolean(chatListOnly),
                sidebarMode: Boolean(sidebarMode),
                pollInterval: Number(pollInterval || 5000),
                selectedChatId: null,
                messages: [],
                loadingMessages: false,
                sendingMessage: false,
                messageBody: '',
                errorMessage: '',
                showDiskPicker: false,
                diskSearch: '',
                selectedDiskFileId: null,
                pollHandle: null,
                chatUnreadCount: 0,

                init() {
                    this.$el?.addEventListener('crm:chat-component:destroy', () => {
                        this.stopPolling();
                    }, { once: true });

                    this.sortChats();
                    this.chatUnreadCount = this.chats.reduce((sum, chat) => sum + Number(chat.unread_count || 0), 0);

                    const preferredChat = this.chatById(this.initialChatId);
                    if (this.chats.length > 0) {
                        if (this.chatListOnly) {
                            this.selectedChatId = Number(preferredChat?.id ?? 0);
                            return;
                        }

                        this.selectedChatId = Number(preferredChat?.id ?? this.chats[0].id);
                        this.loadConversation();
                        this.startPolling();
                    }
                },

                selectedChat() {
                    return this.chats.find((chat) => Number(chat.id) === Number(this.selectedChatId)) ?? null;
                },

                chatById(chatId) {
                    return this.chats.find((chat) => Number(chat.id) === Number(chatId)) ?? null;
                },

                chatUnreadFor(chatId) {
                    const chat = this.chatById(chatId);
                    return Number(chat?.unread_count || 0);
                },

                chatSubtitle(chatId, roleLabel, fallbackLastMessageHuman) {
                    const chat = this.chatById(chatId);
                    const suffix = chat?.last_message_human || fallbackLastMessageHuman || '—';
                    return `${roleLabel} · ${suffix}`;
                },

                sortChats() {
                    this.chats = [...this.chats].sort((left, right) => {
                        const unreadDiff = Number(right.unread_count || 0) - Number(left.unread_count || 0);
                        if (unreadDiff !== 0) {
                            return unreadDiff;
                        }

                        const rightTimestamp = Date.parse(right.last_message_at || '') || 0;
                        const leftTimestamp = Date.parse(left.last_message_at || '') || 0;
                        if (rightTimestamp !== leftTimestamp) {
                            return rightTimestamp - leftTimestamp;
                        }

                        return String(left.name || '').localeCompare(String(right.name || ''), 'en');
                    });
                },

                conversationUrl(chatId) {
                    return this.showUrlTemplate.replace('__MEMBER__', String(chatId));
                },

                storeUrl(chatId) {
                    return this.storeUrlTemplate.replace('__MEMBER__', String(chatId));
                },

                sidebarUrl(chatId) {
                    if (!this.sidebarUrlTemplate) {
                        return '';
                    }

                    return this.sidebarUrlTemplate.replace('__MEMBER__', String(chatId));
                },

                userSidebarUrl(userId) {
                    if (!this.userSidebarUrlTemplate) {
                        return '';
                    }

                    return this.userSidebarUrlTemplate.replace('__USER__', String(userId));
                },

                canSend() {
                    return Boolean(this.selectedChatId)
                        && (this.messageBody.trim() !== '' || this.selectedDiskFile() !== null)
                        && !this.sendingMessage;
                },

                selectChat(chatId) {
                    const normalizedId = Number(chatId);
                    if (!normalizedId || normalizedId === Number(this.selectedChatId)) {
                        return;
                    }

                    this.selectedChatId = normalizedId;
                    this.showDiskPicker = false;
                    if (this.chatListOnly) {
                        return;
                    }

                    this.messages = [];
                    this.errorMessage = '';
                    this.loadConversation();
                    this.startPolling();
                },

                openChatSidebar(chatId) {
                    const normalizedId = Number(chatId);
                    if (!normalizedId) {
                        return;
                    }

                    this.selectChat(normalizedId);

                    if (this.sidebarMode) {
                        return;
                    }

                    const sidebarUrl = this.sidebarUrl(normalizedId);
                    if (!sidebarUrl) {
                        return;
                    }

                    if (window.crmSidepanel && typeof window.crmSidepanel.open === 'function') {
                        window.crmSidepanel.open(sidebarUrl, 'Chats', { allowAny: true });
                        return;
                    }

                    window.location.assign(sidebarUrl);
                },

                openUserSidebar(userId) {
                    const normalizedId = Number(userId);
                    if (!normalizedId) {
                        return;
                    }

                    const sidebarUrl = this.userSidebarUrl(normalizedId);
                    if (!sidebarUrl) {
                        return;
                    }

                    if (window.crmSidepanel && typeof window.crmSidepanel.open === 'function') {
                        window.crmSidepanel.open(sidebarUrl, 'Employee profile', { allowAny: true });
                        return;
                    }

                    window.location.assign(sidebarUrl);
                },

                selectedDiskFile() {
                    const id = Number(this.selectedDiskFileId || 0);
                    if (!id) {
                        return null;
                    }

                    return this.diskFiles.find((file) => Number(file?.id || 0) === id) ?? null;
                },

                filteredDiskFiles() {
                    if (!Array.isArray(this.diskFiles) || this.diskFiles.length === 0) {
                        return [];
                    }

                    const query = String(this.diskSearch || '').trim().toLowerCase();
                    if (query === '') {
                        return this.diskFiles.slice(0, 80);
                    }

                    return this.diskFiles
                        .filter((file) => {
                            const haystack = [
                                String(file?.name || ''),
                                String(file?.folder || ''),
                                String(file?.owner_name || ''),
                            ].join(' ').toLowerCase();

                            return haystack.includes(query);
                        })
                        .slice(0, 80);
                },

                toggleDiskPicker() {
                    if (!this.selectedChatId || this.sendingMessage || this.diskFiles.length === 0) {
                        return;
                    }

                    this.showDiskPicker = !this.showDiskPicker;
                    if (this.showDiskPicker) {
                        this.$nextTick(() => {
                            const input = this.$refs.diskSearchInput;
                            if (input && typeof input.focus === 'function') {
                                input.focus();
                            }
                        });
                    }
                },

                attachDiskFile(file) {
                    const id = Number(file?.id || 0);
                    if (!id) {
                        return;
                    }

                    this.selectedDiskFileId = id;
                    this.showDiskPicker = false;
                    this.diskSearch = '';
                },

                removeDiskAttachment() {
                    this.selectedDiskFileId = null;
                },

                startPolling() {
                    this.stopPolling();
                    this.pollHandle = window.setInterval(() => {
                        if (!this.selectedChatId || this.sendingMessage) {
                            return;
                        }

                        this.loadConversation(true);
                    }, this.pollInterval);
                },

                stopPolling() {
                    if (this.pollHandle) {
                        window.clearInterval(this.pollHandle);
                        this.pollHandle = null;
                    }
                },

                async loadConversation(isSilent = false) {
                    if (!this.selectedChatId) {
                        return;
                    }

                    if (!isSilent) {
                        this.loadingMessages = true;
                    }

                    try {
                        const response = await window.fetch(this.conversationUrl(this.selectedChatId), {
                            headers: {
                                'Accept': 'application/json',
                                'X-Requested-With': 'XMLHttpRequest',
                            },
                        });

                        if (!response.ok) {
                            throw new Error(`HTTP ${response.status}`);
                        }

                        const payload = await response.json();
                        this.messages = Array.isArray(payload.messages) ? payload.messages : [];

                        const activeChat = this.selectedChat();
                        if (activeChat) {
                            activeChat.unread_count = 0;
                            if (payload.member) {
                                activeChat.is_online = Boolean(payload.member.is_online);
                                activeChat.last_seen = String(payload.member.last_seen || activeChat.last_seen || '');
                                activeChat.photo_url = payload.member.photo_url || activeChat.photo_url;
                                activeChat.photo_style = payload.member.photo_style || activeChat.photo_style;
                            }
                        }

                        const lastMessage = this.messages[this.messages.length - 1] ?? null;
                        if (activeChat && lastMessage) {
                            activeChat.last_message = String(lastMessage.preview_text || lastMessage.body || '');
                            activeChat.last_message_human = String(lastMessage.sent_at_human || '');
                            activeChat.last_message_at = String(lastMessage.sent_at || '');
                        }

                        this.chatUnreadCount = this.chats.reduce((sum, chat) => sum + Number(chat.unread_count || 0), 0);
                        this.sortChats();
                        this.scrollToBottom();
                    } catch (error) {
                        if (!isSilent) {
                            this.errorMessage = 'Failed to load dialog.';
                        }
                    } finally {
                        if (!isSilent) {
                            this.loadingMessages = false;
                        }
                    }
                },

                async sendMessage() {
                    if (!this.canSend()) {
                        return;
                    }

                    const body = this.messageBody.trim();
                    const selectedDisk = this.selectedDiskFile();
                    this.sendingMessage = true;
                    this.errorMessage = '';

                    try {
                        const payload = { body };
                        if (selectedDisk && Number(selectedDisk.id || 0) > 0) {
                            payload.disk_id = Number(selectedDisk.id);
                        }

                        const response = await window.fetch(this.storeUrl(this.selectedChatId), {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'Accept': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]')?.getAttribute('content') || '',
                                'X-Requested-With': 'XMLHttpRequest',
                            },
                            body: JSON.stringify(payload),
                        });

                        if (!response.ok) {
                            throw new Error(`HTTP ${response.status}`);
                        }

                        const payload = await response.json();
                        if (!payload || !payload.message) {
                            throw new Error('Payload is empty');
                        }

                        this.messages.push(payload.message);
                        this.messageBody = '';
                        this.selectedDiskFileId = null;
                        this.showDiskPicker = false;
                        this.diskSearch = '';
                        this.focusMessageInput();

                        const activeChat = this.selectedChat();
                        if (activeChat) {
                            activeChat.unread_count = 0;
                            activeChat.last_message = String(payload.message.preview_text || payload.message.body || '');
                            activeChat.last_message_human = String(payload.message.sent_at_human || '');
                            activeChat.last_message_at = String(payload.message.sent_at || '');
                        }

                        this.sortChats();
                        this.scrollToBottom();
                    } catch (error) {
                        this.errorMessage = 'Failed to send message.';
                    } finally {
                        this.sendingMessage = false;
                    }
                },

                scrollToBottom() {
                    this.$nextTick(() => {
                        if (!this.$refs.messagesBox) {
                            return;
                        }

                        this.$refs.messagesBox.scrollTop = this.$refs.messagesBox.scrollHeight;
                    });
                },

                focusMessageInput() {
                    this.$nextTick(() => {
                        const input = this.$refs.messageInput;
                        if (!input || typeof input.focus !== 'function') {
                            return;
                        }

                        input.focus({ preventScroll: true });
                    });
                },
            }));
        });
    </script>
@endonce
