import SwiftUI
import NucleicCore

/// Lists the subagents (Orchestra workers) this chat spawned via the `nucleic_subagent`
/// MCP tool. These are ordinary sessions kept out of the sidebar (`SessionSummary.isSubagent`)
/// and surfaced here instead, treated as subsessions of their parent chat: each row opens the
/// worker in the detail view. Reads straight off the observable store, so it fills in and
/// updates status live as workers spawn and finish.
struct SubagentsPanel: View {
    let session: Session?
    @Environment(AppStore.self) private var store

    private var subagents: [SessionSummary] {
        guard let session else { return [] }
        return store.subagentSummaries(for: session.id)
    }

    var body: some View {
        if session == nil {
            placeholder("No chat open", systemImage: "person.2")
        } else if subagents.isEmpty {
            placeholder("No subagents yet", systemImage: "person.2")
        } else {
            ScrollView {
                LazyVStack(alignment: .leading, spacing: 0) {
                    ForEach(subagents) { sub in
                        SessionRow(
                            summary: sub,
                            isSelected: store.openSessionID == sub.id && store.openHostID == sub.hostID)
                        .contentShape(Rectangle())
                        .onTapGesture { store.openSession(sub) }
                        if sub.id != subagents.last?.id { Divider() }
                    }
                }
                .padding(.vertical, 4)
                .frame(maxWidth: .infinity, alignment: .leading)
            }
        }
    }

    private func placeholder(_ text: String, systemImage: String) -> some View {
        VStack(spacing: 8) {
            Image(systemName: systemImage).font(.largeTitle).foregroundStyle(.tertiary)
            Text(text).font(.callout).foregroundStyle(.secondary)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}
