import SwiftUI
import SwiftData
import Bedrock

@main
struct AndromidaApp: App {
    private let modelContainer: ModelContainer
    @State private var store: RitualStore
    @State private var settingsStore: SettingsStore
    @State private var categoryStore: CategoryStore
    @AppStorage("hasCompletedSetupWizard") private var hasCompletedSetupWizard = false
    
    /// Track if user just completed the wizard (to start on Rituals tab)
    @State private var justCompletedWizard = false

    init() {
        // Include all models in schema - Ritual, RitualArc, and ArcHabit
        let schema = Schema([Ritual.self, RitualArc.self, ArcHabit.self])
        let configuration = ModelConfiguration(
            schema: schema,
            isStoredInMemoryOnly: false,
            cloudKitDatabase: .private("iCloud.com.mbrucedogs.Andromida")
        )
        let container: ModelContainer
        do {
            container = try ModelContainer(for: schema, configurations: [configuration])
        } catch {
            fatalError("Unable to create model container: \(error)")
        }
        modelContainer = container
        let settings = SettingsStore()
        _settingsStore = State(initialValue: settings)
        _categoryStore = State(initialValue: CategoryStore())
        _store = State(initialValue: RitualStore(modelContext: container.mainContext, seedService: RitualSeedService(), settingsStore: settings))
    }

    var body: some Scene {
        WindowGroup {
            ZStack {
                Color.Branding.primary
                    .ignoresSafeArea()

                if hasCompletedSetupWizard {
                    // Main app - start on Rituals tab if just completed wizard
                    AppLaunchView(config: .rituals) {
                        RootView(
                            store: store,
                            settingsStore: settingsStore,
                            categoryStore: categoryStore,
                            initialTab: justCompletedWizard ? .rituals : .today
                        )
                    }
                } else {
                    // First-run setup wizard
                    AppLaunchView(config: .rituals) {
                        SetupWizardView(
                            store: store,
                            categoryStore: categoryStore,
                            onComplete: {
                                justCompletedWizard = true
                                withAnimation {
                                    hasCompletedSetupWizard = true
                                }
                            }
                        )
                    }
                }
            }
            .modelContainer(modelContainer)
            .preferredColorScheme(.dark)
        }
    }
}
