import SwiftUI
import SwiftData
import VNCCore
import VNCUI

@main
struct VNCApp: App {
    @State private var appState = AppStateController()

    private let sharedContainer: ModelContainer = {
        let schema = Schema([SavedConnection.self])
        let cloudKitConfiguration = ModelConfiguration(
            "CloudConnections",
            schema: schema,
            cloudKitDatabase: .automatic
        )
        if let container = try? ModelContainer(for: schema,
                                               configurations: [cloudKitConfiguration]) {
            return container
        }
        let local = ModelConfiguration(
            "LocalConnections",
            schema: schema,
            cloudKitDatabase: .none
        )
        return (try? ModelContainer(for: schema, configurations: [local]))
            ?? (try! ModelContainer(for: SavedConnection.self))
    }()

    var body: some Scene {
        WindowGroup {
            RootView()
                .environment(appState)
                .task { await appState.initialize() }
        }
        .modelContainer(sharedContainer)

        WindowGroup("Session", for: UUID.self) { $connectionID in
            DetachedSessionWindow(connectionID: connectionID)
        }
        .modelContainer(sharedContainer)
    }
}

private struct DetachedSessionWindow: View {
    let connectionID: UUID?
    @Environment(\.modelContext) private var modelContext
    @Query private var connections: [SavedConnection]

    var body: some View {
        if let id = connectionID,
           let match = connections.first(where: { $0.id == id }) {
            NavigationStack {
                SessionView(connection: match)
            }
        } else {
            ContentUnavailableView(
                "Connection unavailable",
                systemImage: "questionmark.app",
                description: Text("This window's connection is no longer available.")
            )
        }
    }
}
