//
//  bookstaxApp.swift
//  bookstax
//
//  Created by Sven Hanold on 19.03.26.
//

import SwiftUI
import SwiftData

@main
struct bookstaxApp: App {
    @AppStorage("onboardingComplete") private var onboardingComplete = false
    @AppStorage("appTheme") private var appTheme = "system"
    @AppStorage("accentTheme") private var accentThemeRaw = AccentTheme.ocean.rawValue

    // ServerProfileStore is initialised here so migration runs at launch
    private var profileStore = ServerProfileStore.shared

    private var preferredColorScheme: ColorScheme? {
        switch appTheme {
        case "light": return .light
        case "dark":  return .dark
        default:      return nil
        }
    }

    private var accentTheme: AccentTheme {
        AccentTheme(rawValue: accentThemeRaw) ?? .ocean
    }

    let sharedModelContainer: ModelContainer = {
        let schema = Schema([CachedShelf.self, CachedBook.self, CachedPage.self])
        let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
        do {
            return try ModelContainer(for: schema, configurations: [config])
        } catch {
            fatalError("Could not create ModelContainer: \(error)")
        }
    }()

    init() {
        AppLog(.info, "BookStax launched", category: "App")
    }

    var body: some Scene {
        WindowGroup {
            Group {
                if onboardingComplete && profileStore.activeProfile != nil {
                    MainTabView()
                        .environment(ConnectivityMonitor.shared)
                        // Re-creates the entire tab hierarchy when the active server changes
                        .id(profileStore.activeProfileId)
                } else {
                    OnboardingView()
                }
            }
            .environment(profileStore)
            .environment(\.accentTheme, accentTheme)
            .tint(accentTheme.accentColor)
            .preferredColorScheme(preferredColorScheme)
        }
        .modelContainer(sharedModelContainer)
    }
}

