import SwiftUI
import SwiftData

struct ContentView: View {
    @Environment(\.modelContext) private var context
    @Environment(\.scenePhase) private var scenePhase
    @Query private var allSettings: [AppSettings]
    @State private var isReady = false

    private var settings: AppSettings? { allSettings.first }

    var body: some View {
        Group {
            if !isReady {
                // Splash screen
                ZStack {
                    Color.mealMoodBackground.ignoresSafeArea()
                    AppIconPlaceholder(size: 120)
                }
            } else if let settings = settings, settings.onboardingCompleted {
                HomeView()
            } else {
                OnboardingView {
                    // Onboarding completed
                }
            }
        }
        .environment(\.locale, Locale(identifier: settings?.languageEnum.localeIdentifier ?? Locale.current.identifier))
        .onAppear {
            initializeAppIfNeeded()
            Task {
                if settings?.iCloudSyncEnabledResolved ?? true {
                    await ICloudSyncService.shared.pullRemoteIfNeeded(context: context)
                }
                await syncPremiumStatus()
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                withAnimation(.easeInOut) {
                    isReady = true
                }
            }
        }
        .onChange(of: scenePhase) { _, phase in
            Task {
                switch phase {
                case .active:
                    await syncPremiumStatus()
                case .inactive, .background:
                    if settings?.iCloudSyncEnabledResolved ?? true {
                        await ICloudSyncService.shared.pushLocalSnapshot(context: context)
                    }
                @unknown default:
                    break
                }
            }
        }
    }

    private func initializeAppIfNeeded() {
        // Create default settings if none exist
        if allSettings.isEmpty {
            DefaultDataService.createDefaultSettings(context: context)
        }

        // Create default tags if none exist
        let tagDescriptor = FetchDescriptor<Tag>()
        if (try? context.fetch(tagDescriptor))?.isEmpty ?? true {
            DefaultDataService.createDefaultTags(context: context)
        }
    }

    private func syncPremiumStatus() async {
        let descriptor = FetchDescriptor<AppSettings>()
        guard let settings = try? context.fetch(descriptor).first else { return }
        let premium = await StoreManager.hasActiveSubscription()
        if settings.isPremium != premium {
            settings.isPremium = premium
            try? context.save()
        }
    }
}
