import SwiftUI
import SwiftData

@main
struct Sesame_Watch_Watch_AppApp: App {
    
    @State
    var modelContainer: ModelContainer
    
    @ObservedObject
    var coordinator: RequestCoordinator
    
    let keyManagement = KeyManagement()

    @State
    var selected: Int = 0

    @State
    var didLaunchFromComplication = false
    
    init() {
        do {
            let modelContainer = try ModelContainer(for: HistoryItem.self)
            self.modelContainer = modelContainer
            self.coordinator = .init(modelContext: modelContainer.mainContext)
        } catch {
            fatalError("Failed to create model container: \(error)")
        }
    }
    
    var body: some Scene {
        WindowGroup {
            TabView(selection: $selected) {
                ContentView(coordinator: coordinator, didLaunchFromComplication: $didLaunchFromComplication)
                    .tag(1)
                SettingsView()
                    .environmentObject(keyManagement)
                    .tag(2)
                HistoryView()
                    .tag(3)
            }
            .tabViewStyle(PageTabViewStyle())
            .onOpenURL { url in
                selected = 0
                didLaunchFromComplication = true
            }
        }
        .modelContainer(modelContainer)
    }
}
