import SwiftUI

struct MessageRow: View {
    let message: SavedMessage
    var onDM: ((SavedMessage) -> Void)?
    var onProfile: ((SavedMessage) -> Void)?
    @Environment(ConnectionManager.self) private var manager

    private var isOwnMessage: Bool {
        message.senderIsRecipient || message.senderId == manager.localSenderId
    }

    var body: some View {
        if message.isSystem {
            Text(message.content)
                .font(.body)
                .foregroundStyle(.secondary)
                .italic()
                .frame(maxWidth: .infinity, alignment: .center)
                .padding(.vertical, 6)
        } else {
            VStack(alignment: .leading, spacing: 8) {
                HStack {
                    Text(message.senderName)
                        .font(.headline)
                        .foregroundStyle(Color.accentColor)

                    if message.senderIsRecipient {
                        Text("(you)")
                            .font(.subheadline)
                            .foregroundStyle(.secondary)
                    }

                    Spacer()

                    Text(message.timestamp, style: .time)
                        .font(.subheadline)
                        .foregroundStyle(.secondary)
                }

                Text(message.content)
                    .font(.title3)
            }
            .padding(.horizontal, 12)
            .padding(.vertical, 10)
            .background(.regularMaterial)
            .clipShape(.rect(cornerRadius: 12))
            .contextMenu {
                if !isOwnMessage, message.senderId != nil {
                    if let onDM {
                        Button("DM \(message.senderName)", systemImage: "envelope") { onDM(message) }
                    }
                    if let onProfile {
                        Button("Show \(message.senderName)'s Profile", systemImage: "person.circle") { onProfile(message) }
                    }
                }
            }
            .accessibilityElement(children: .combine)
            .accessibilityActions {
                if !isOwnMessage, message.senderId != nil {
                    if let onDM {
                        Button("DM \(message.senderName)") { onDM(message) }
                    }
                    if let onProfile {
                        Button("Show \(message.senderName)'s Profile") { onProfile(message) }
                    }
                }
            }
        }
    }
}
