import SwiftUI

struct DMListView: View {
    @Environment(ConnectionManager.self) private var manager
    @Binding var selectedConversation: String?

    private var conversations: [(id: String, name: String, lastMessage: ChatMessage)] {
        let dmMessages = manager.messages["direct-messages"] ?? []
        var latest: [String: (name: String, message: ChatMessage)] = [:]

        for message in dmMessages where !message.isSystem {
            // The conversation partner is the other person
            guard let senderId = message.senderId, !message.senderIsRecipient else { continue }
            if latest[senderId].map({ message.timestamp > $0.message.timestamp }) ?? true {
                latest[senderId] = (message.senderName, message)
            }
        }

        return latest
            .map { (id: $0.key, name: $0.value.name, lastMessage: $0.value.message) }
            .sorted { $0.lastMessage.timestamp > $1.lastMessage.timestamp }
    }

    var body: some View {
        if conversations.isEmpty {
            ContentUnavailableView(
                "No Conversations",
                systemImage: "envelope",
                description: Text("Direct messages will appear here.")
            )
        } else {
            List(conversations, id: \.id, selection: $selectedConversation) { convo in
                NavigationLink(value: convo.id) {
                    VStack(alignment: .leading, spacing: 4) {
                        HStack {
                            Text(convo.name)
                                .font(.headline)
                            Spacer()
                            Text(convo.lastMessage.timestamp, style: .time)
                                .font(.caption)
                                .foregroundStyle(.secondary)
                        }
                        Text(convo.lastMessage.content)
                            .font(.subheadline)
                            .foregroundStyle(.secondary)
                            .lineLimit(1)
                    }
                    .padding(.vertical, 4)
                }
            }
            .listStyle(.plain)
        }
    }
}
