import SwiftUI

struct MainTabView: View {
    @Environment(ConnectivityMonitor.self) private var connectivity
    @State private var selectedTab = 0
    @State private var showNudge = false
    private let navState = AppNavigationState.shared

    var body: some View {
        TabView(selection: $selectedTab) {
            LibraryView()
                .tabItem { Label(L("tab.library"), systemImage: "books.vertical") }
                .tag(0)
            QuickNoteView()
                .tabItem { Label(L("tab.quicknote"), systemImage: "square.and.pencil") }
                .tag(1)
            SearchView()
                .tabItem { Label(L("tab.search"), systemImage: "magnifyingglass") }
                .tag(2)
            SettingsView()
                .tabItem { Label(L("tab.settings"), systemImage: "gear") }
                .tag(3)
        }
        .onChange(of: navState.pendingBookNavigation) { _, book in
            if book != nil { selectedTab = 0 }
        }
        .onChange(of: navState.navigateToSettings) { _, go in
            if go { selectedTab = 3; navState.navigateToSettings = false }
        }
        .sheet(isPresented: $showNudge, onDismiss: {
            DonationService.shared.recordNudgeSeen()
        }) {
            SupportNudgeSheet(isPresented: $showNudge)
                .presentationDetents([.large])
                .presentationDragIndicator(.visible)
        }
        .task {
            // Small delay so the app settles before the sheet appears
            try? await Task.sleep(for: .seconds(2))
            showNudge = DonationService.shared.shouldShowNudge
        }
    }
}

#Preview {
    MainTabView()
        .environment(ConnectivityMonitor.shared)
}
