User: Poderia corrigir a ordenação dos chats? Preciso que reordene corretamente, 

<template>
    <div class="flex h-screen bg-gray-50">
        <!-- Sidebar -->
        <aside
            :class="sidebarOpen ? 'w-64 transition-all' : 'hidden'"
            class="bg-slate-200 border-r-2 border-slate-800/[0.06] shadow text-gray-700 h-screen overflow-y-auto transition-all duration-300 flex w-full flex-col px-3"
            :style="sidebarOpen ? 'width: 20rem' : 'width: 4.5rem'"
        >
			<div class="flex space-x-2 justify-between h-[60px] items-center md:h-header-height">
                <button
                    @click="openNewChatModal"
                    class="flex text-slate-800 hover:text-gray-400 transition"
                >
                    <i class="pi pi-plus"></i>
                </button>
				<input
					v-model="search"
					type="text"
					placeholder="Search"
					class="w-full rounded-full active:outline-none bg-transparent border-none text-slate-800"
				/>
				<button
                    @click="toggleSidebar"
                    class="flex text-slate-800 hover:text-gray-400 transition"
                >
                    <i
                        :class="
                            sidebarOpen
                                ? 'pi pi-arrow-left'
                                : 'pi pi-arrow-right'
                        "
                    ></i>
                </button>
			</div>

            <div class="flex-grow p-2">
                <ChatList
                    :chats="chats"
                    :currentChat="currentChat"
                    @select-chat="selectChat($event)"
                    @open-delete-chat-modal="handleOpenDeleteChatModal($event)"
                />
            </div>
        </aside>

        <!-- Main Content -->
        <main class="flex-1 flex flex-col">
            <!-- Header -->
            <header
                class="bg-gray-700 backdrop-blur border-b shadow p-4 flex items-center justify-between"
            >
                <button
                    @click="toggleSidebar"
                    class="text-gray-200 hover:text-gray-800 transition"
                >
                    <i
                        :class="
                            sidebarOpen
                                ? 'pi pi-arrow-left'
                                : 'pi pi-arrow-right'
                        "
                    ></i>
                </button>
                <h2 class="text-xl font-bold text-gray-200">
                    {{ currentChat?.title || "Select a Chat" }}
                </h2>
                <button
                    v-if="currentChat"
                    @click="openDeleteChatModal(currentChat)"
                    class="text-red-400 hover:text-red-500 transition p-1"
                >
                    <TrashIcon class="h-6 w-6" />
                </button>
            </header>

            <!-- Messages -->
            <section
                class="flex-1 overflow-y-auto p-6 space-y-4 bg-slate-100 dark:bg-gray-800"
                ref="messagesContainer"
            >
                <div v-if="currentChat && currentChat.messages?.length > 0">
                    <TextBubble
                        v-for="message in currentChat.messages"
                        :key="message.id"
                        :message="message"
                    />
                </div>
                <div
                    v-else-if="currentChat"
                    class="text-center text-gray-500 mt-8"
                >
                    No messages yet. Start the conversation!
                </div>
                <div
                    v-else
                    class="flex items-center justify-center h-full text-gray-500"
                >
                    Select a chat to start messaging
                </div>
            </section>

            <!-- Message Input -->
            <footer
                class="bg-gray-50 border-t border-gray-200 p-4 sticky bottom-0"
            >
                <form
                    @submit.prevent="sendMessage"
                    class="flex items-center gap-3 max-w-5xl mx-auto"
                >
                    <input
                        v-model="newMessage"
                        type="text"
                        placeholder="Digite sua mensagem..."
                        class="flex-1 bg-white border border-gray-200 rounded-xl py-3 px-4 font-sans text-gray-800 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
                        :disabled="!currentChat"
                    />
                    <button
                        type="submit"
                        class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-3 px-6 rounded-xl transition-colors duration-200 flex items-center gap-2 disabled:opacity-50 disabled:hover:bg-blue-500 shadow-sm hover:shadow-md"
                        :disabled="!currentChat || !newMessage.trim()"
                    >
                        <span class="hidden sm:inline">Enviar</span>
                        <i class="pi pi-send"></i>
                    </button>
                </form>
            </footer>
        </main>

        <!-- Modals -->
        <NewChatModal
            v-if="showNewChatModal"
			:customModels="customModels"
            @close="closeNewChatModal"
            @create="createNewChat"
        />
        <DeleteChatModal
            v-if="showDeleteChatModal"
            :chat="chatToDelete"
            @close="closeDeleteChatModal"
            @delete="deleteChat"
        />
    </div>
</template>

<style scoped>
.flex-1 > div {
    transition: all 0.3s ease;
}
.self-start {
    justify-self: flex-start;
}
.self-end {
    justify-self: flex-end;
}
</style>

<script setup>
import { ref, watch, onMounted, computed, nextTick } from "vue";
import { usePage, router } from "@inertiajs/vue3";
import { TrashIcon } from "lucide-vue-next";
import TextBubble from "@/Components/Chat/TextBubble.vue";
import NewChatModal from "@/Components/Chat/NewChatModal.vue";
import DeleteChatModal from "@/Components/Chat/DeleteChatModal.vue";
import ChatList from "@/Components/Chat/ChatList.vue";
import axios from "axios";
import dayjs from "dayjs";
// State
const props = defineProps(["chats", "customModels"]);

const search = ref("");
const isMobile = ref(false);
const sidebarOpen = ref(true);
const chatId = ref(null);
const chats = ref(props.chats);
const currentChat = ref(null);
const newMessage = ref("");
const showNewChatModal = ref(false);
const showDeleteChatModal = ref(false);
const chatToDelete = ref(null);
const messagesContainer = ref(null);

// Computed
const user = computed(() => usePage().props.auth.user);

const toggleSidebar = () => (sidebarOpen.value = !sidebarOpen.value);

computed(() => {
	if (window.innerWidth < 768) {
		isMobile.value = true;
		sidebarOpen.value = false;
	}
});

const reorderChats = (chatArray) => {
    return chatArray.sort((a, b) => {
        // Prioriza mensagens mais recentes
        const getRelevantDate = (chat) => {
            // Primeiro tenta usar a data da última mensagem
            if (chat.lastMessage) {
                return new Date(chat.last_message_at || chat.updated_at || chat.created_at).getTime();
            }

            // Se não tiver última mensagem, usa updated_at
            if (chat.updated_at) {
                return new Date(chat.updated_at).getTime();
            }

            // Fallback para created_at
            return chat.created_at ? new Date(chat.created_at).getTime() : 0;
        };

        const dateA = getRelevantDate(a);
        const dateB = getRelevantDate(b);

        // Ordena em ordem decrescente (mais recente primeiro)
        return dateB - dateA;
    });
};

// Atualizar o watch e onMounted para usar essa função
onMounted(() => {
    chats.value = reorderChats(props.chats);
});

watch(
	() => props.chats,
	(newChats) => {
		// Exibe os chats por updated_at em ordem decrescente
		chats.value = reorderChats(newChats);
	}
);


// Methods
const selectChat = (chat) => {
    currentChat.value = chat;
	reorderChats(chats.value);
    scrollToBottom();
};


const scrollToBottom = async () => {
    await nextTick();
    if (messagesContainer.value) {
        messagesContainer.value.scrollTop =
            messagesContainer.value.scrollHeight;
    }
};

const openNewChatModal = () => (showNewChatModal.value = true);
const closeNewChatModal = () => (showNewChatModal.value = false);

const createNewChat = async ({model_id}) => {
    try {
        axios.post("/chats", { model_id }).then((response) => {
			console.log(response.data);
            if (response.data.success) {
                const newChat = {
                    ...response.data.chat,
                    messages: [], // Inicialize messages como um array vazio
                };
                chats.value.push(newChat);
                currentChat.value = newChat;
            }
        });
        closeNewChatModal();
		// Atualizar o watch e onMounted para usar essa função
        selectChat(currentChat.value);
    } catch (error) {
        console.error("Failed to create chat:", error);
    }
};

const openDeleteChatModal = (chat) => {
    chatToDelete.value = chat;
    showDeleteChatModal.value = true;
};

const closeDeleteChatModal = () => {
    showDeleteChatModal.value = false;
    chatToDelete.value = null;
};

const deleteChat = async () => {
    try {
        await axios.delete(`/chats/${chatToDelete.value.id}`);

        chats.value = chats.value.filter(
            (chat) => chat.id !== chatToDelete.value.id
        );

        closeDeleteChatModal();
    } catch (error) {
        console.error("Failed to delete chat:", error);
    }
};

const setChatLastMessage = (chat, message) => {
    if (chat) {
        chat.lastMessage = message.content;
        chat.last_message_at = message.created_at;
        chat.lastMessageDate = dayjs(message.created_at.date).isSame(dayjs(), 'day')
            ? dayjs(message.created_at.date).format('HH:mm')
            : dayjs(message.created_at.date).format('DD/MM/YYYY');
    }
};

const sendMessage = () => {
    if (!currentChat.value || !newMessage.value.trim()) return;

    axios
        .post(`/chats/${currentChat.value.id}/messages`, {
            content: newMessage.value,
        })
        .then((response) => {
            if (response.data.success) {
                currentChat.value?.messages.push(response.data.message);
				setChatLastMessage(currentChat.value, response.data.message);
                newMessage.value = "";
                scrollToBottom();
            }
        })
        .catch((error) => {
            console.error("Failed to send message:", error);
            // Optionally show an error toast or message to the user
        });
};
// Websocket listeners
onMounted(() => {
    Echo.private(`chats.${user.value.id}`)
        .listen("MessageSent", (event) => {
            nextTick(() => {
                if (event.id) {
                    if (event.role === "assistant") {
                        // Verifica se a mensagem já existe no chat
                        const messageExists = currentChat.value?.messages.some(
                            (message) => message.id === event.id
                        );

                        if (!messageExists) {
							setChatLastMessage(currentChat.value, event);
                            currentChat.value?.messages.push(event);
                            scrollToBottom();
                        } else {
                            console.log(
                                "Message already exists in the chat, not adding it again."
                            );
                        }
                    }
                    // If this is the current chat, scroll to bottom
                    if (currentChat.value?.id === event.chatId) {
                        scrollToBottom();
                    }
                }
            });
        })
        .listen("ChatCreated", (event) => {
            nextTick(() => {
                // Prevent duplicate chats
                const existingChat = chats.value.find(
                    (c) => c.id === event.chat.id
                );
                if (!existingChat) {
					chats.value.push(event.chat);
                }


            });
        })
        .listen("ChatDeleted", (event) => {
            nextTick(() => {
                const index = chats.value.findIndex(
                    (c) => c.id === event.chatId
                );
                if (index !== -1) {
                    chats.value.splice(index, 1);
                    if (currentChat.value?.id === event.chatId) {
                        currentChat.value = null;
                    }
                }
            });
        })
        .error((error) => {
            console.error("Echo channel error:", error);
        });
});
</script>

<style scoped>
.group:hover button {
    display: block;
}
</style>

User: Pode enviar apenas a funcao reorderChats?
Assistant: Claro! Aqui está a função `reorderChats` que você solicitou:

```javascript
const reorderChats = (chatArray) => {
    return chatArray.sort((a, b) => {
        // Prioriza mensagens mais recentes
        const getRelevantDate = (chat) => {
            // Primeiro tenta usar a data da última mensagem
            if (chat.lastMessage) {
                return new Date(chat.last_message_at || chat.updated_at || chat.created_at).getTime();
            }

            // Se não tiver última mensagem, usa updated_at
            if (chat.updated_at) {
                return new Date(chat.updated_at).getTime();
            }

            // Fallback para created_at
            return chat.created_at ? new Date(chat.created_at).getTime() : 0;
        };

        const dateA = getRelevantDate(a);
        const dateB = getRelevantDate(b);

        // Ordena em ordem decrescente (mais recente primeiro)
        return dateB - dateA;
    });
};
```

Essa função ordena um array de chats com base na data da última mensagem, utilizando `last_message_at`, `updated_at` ou `created_at`, priorizando sempre a data mais recente.
User: Corrige esse componente

Corrige esse componente

<ChatList
                    :chat="chatList.currentChat"
                    @select-chat="chatList.setCurrentChat($event)"
                    @open-delete-chat-modal="chatList.closeNewChatModal"
                />

<template>
    <div class="rounded-lg">
		<div class="flex items-center">
			<img
				class="w-8 h-8 rounded-full flex-shrink-0 mr-3 border-2 border-blue-500"
				:src="`https://ui-avatars.com/api/?name=${chat.title}`"
				:alt="chat.title"
			/>
			<div class="flex-1 min-w-0">
				<h4 class="text-sm font-semibold text-gray-900 truncate">
					{{ chat.title }}
				</h4>
				<p class="text-xs text-gray-500 truncate">
					{{ chat.last_message?.content || 'No messages yet' }} ·
					{{ chat.lastMessageDate }}
				</p>
				<span class="bg-green-100 text-green-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-green-900 dark:text-green-300">{{ chat.custom_model.owned_by }}</span>
				<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">
					{{ chat.custom_model.name }}
				</span>
			</div>
			<button
				@click.stop="openDeleteChatModal(chat)"
				class="ml-3 text-red-400 hover:text-red-500 transition"
			>
				<TrashIcon class="h-5 w-5" />
			</button>
		</div>
    </div>
</template>

<script>
import { ref, defineProps } from "vue";

const props = defineProps({
	chat: Object,
});

export default {
	props,
};
</script>

<style scoped>
.fade-text {
    position: relative;
    overflow: hidden;
}

.fade-text::after {
    content: "";
    position: absolute;
    right: 0;
    top: 0;
    width: 20px;
    height: 100%;
    pointer-events: none;
}
</style>

User: Corrige esse componente

<ChatList
                    :chat="chatList.currentChat"
                    @select-chat="chatList.setCurrentChat($event)"
                    @open-delete-chat-modal="chatList.closeNewChatModal"
                />

<template>
    <div class="rounded-lg">
		<div class="flex items-center">
			<img
				class="w-8 h-8 rounded-full flex-shrink-0 mr-3 border-2 border-blue-500"
				:src="`https://ui-avatars.com/api/?name=${chat.title}`"
				:alt="chat.title"
			/>
			<div class="flex-1 min-w-0">
				<h4 class="text-sm font-semibold text-gray-900 truncate">
					{{ chat.title }}
				</h4>
				<p class="text-xs text-gray-500 truncate">
					{{ chat.last_message?.content || 'No messages yet' }} ·
					{{ chat.lastMessageDate }}
				</p>
				<span class="bg-green-100 text-green-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-green-900 dark:text-green-300">{{ chat.custom_model.owned_by }}</span>
				<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">
					{{ chat.custom_model.name }}
				</span>
			</div>
			<button
				@click.stop="openDeleteChatModal(chat)"
				class="ml-3 text-red-400 hover:text-red-500 transition"
			>
				<TrashIcon class="h-5 w-5" />
			</button>
		</div>
    </div>
</template>

<script>
import { ref, defineProps } from "vue";

const props = defineProps({
	chat: Object,
});

export default {
	props,
};
</script>

<style scoped>
.fade-text {
    position: relative;
    overflow: hidden;
}

.fade-text::after {
    content: "";
    position: absolute;
    right: 0;
    top: 0;
    width: 20px;
    height: 100%;
    pointer-events: none;
}
</style>

Assistant: