import SwiftUI
import Bedrock
import SwiftData

struct RootTabView: View {
    @Environment(AppState.self) private var appState
    @Environment(\.scenePhase) private var scenePhase
    @State private var showingShareSheet = false
    @State private var showingOnboarding = false

    var body: some View {
        @Bindable var appState = appState
        
        TabView(selection: $appState.selectedTab) {
            Tab(String.localized("My Cards"), systemImage: "rectangle.stack", value: AppTab.cards) {
                CardsHomeView()
                    .safeAreaInset(edge: .bottom, spacing: 0) {
                        // Floating share button positioned above tab bar
                        if !appState.cardStore.cards.isEmpty {
                            FloatingShareButton {
                                showingShareSheet = true
                            }
                            .frame(maxWidth: .infinity)
                            .padding(.bottom, Design.Spacing.small)
                        }
                    }
            }

            Tab(String.localized("Contacts"), systemImage: "person.2", value: AppTab.contacts) {
                ContactsView()
            }

            Tab(String.localized("Settings"), systemImage: "gearshape", value: AppTab.settings) {
                SettingsView()
            }
        }
        .sheet(isPresented: $showingShareSheet) {
            ShareCardView()
        }
        .preferredColorScheme(appState.preferredColorScheme)
        .fullScreenCover(isPresented: $showingOnboarding) {
            OnboardingView {
                appState.preferences.hasCompletedOnboarding = true
                showingOnboarding = false
            }
            .preferredColorScheme(appState.preferredColorScheme)
        }
        .onAppear {
            updateOnboardingPresentation()
        }
        .onChange(of: appState.preferences.hasCompletedOnboarding) { _, _ in
            updateOnboardingPresentation()
        }
        .onChange(of: scenePhase) { _, newPhase in
            if newPhase == .active {
                updateOnboardingPresentation()
            }
        }
    }

    private func updateOnboardingPresentation() {
        if appState.preferences.hasCompletedOnboarding {
            showingOnboarding = false
        } else if !showingOnboarding {
            showingOnboarding = true
        }
    }
}

#Preview {
    RootTabView()
        .environment(AppState(modelContext: try! ModelContainer(for: BusinessCard.self, Contact.self, AppSettings.self).mainContext))
}
