import SwiftUI

struct ContentView: View {
    @EnvironmentObject var appState: AppState
    @State private var showPairingSuccess = false
    @State private var hadCoupleId = false

    var body: some View {
        NavigationStack {
            rootView
        }
        .environmentObject(appState)
        .fullScreenCover(isPresented: $showPairingSuccess) {
            PairingSuccessView()
                .environmentObject(appState)
        }
        .onChange(of: appState.currentUser?.coupleId) { _, newValue in
            if !hadCoupleId && newValue != nil {
                showPairingSuccess = true
            }
            hadCoupleId = newValue != nil
        }
    }

    @ViewBuilder
    private var rootView: some View {
        switch appState.authState {
        case .loading:
            LoadingView(message: "Getting ready...")
        case .unauthenticated:
            OnboardingFlow()
        case .authenticated(_, let isAnonymous):
            if isAnonymous {
                CreateProfileView()
            } else if appState.currentUser?.coupleId == nil {
                PairPromptView()
            } else {
                MainTabView()
            }
        }
    }
}

// MARK: - Main Tab View

struct MainTabView: View {
    @EnvironmentObject var appState: AppState
    @State private var selectedTab: Tab = .home
    @State private var showCreateInvite = false
    @State private var showAnswerHistory = false

    enum Tab: Hashable {
        case home, dailyQuestion, play, questionPacks, settings
    }

    var body: some View {
        TabView(selection: $selectedTab) {
            HomeView()
                .tabItem {
                    Label("Home", systemImage: selectedTab == .home ? "house.fill" : "house")
                }
                .tag(Tab.home)

            DailyQuestionView()
                .tabItem {
                    Label("Today", systemImage: selectedTab == .dailyQuestion ? "heart.fill" : "heart")
                }
                .tag(Tab.dailyQuestion)

            PlayHubView()
                .tabItem {
                    Label("Play", systemImage: selectedTab == .play ? "play.fill" : "play")
                }
                .tag(Tab.play)

            QuestionPackLibraryView()
                .tabItem {
                    Label("Packs", systemImage: selectedTab == .questionPacks ? "star.fill" : "star")
                }
                .tag(Tab.questionPacks)

            SettingsView()
                .tabItem {
                    Label("Settings", systemImage: selectedTab == .settings ? "gearshape.fill" : "gearshape")
                }
                .tag(Tab.settings)
        }
        .tint(.closerPrimary)
        .onReceive(NotificationCenter.default.publisher(for: .navigateToDailyQuestion)) { _ in
            routeToDailyOrInvite()
        }
        .onReceive(NotificationCenter.default.publisher(for: .navigateToReveal)) { _ in
            routeToDailyOrInvite()
        }
        .onReceive(NotificationCenter.default.publisher(for: .navigateToHome)) { _ in
            selectedTab = .home
        }
        .onReceive(NotificationCenter.default.publisher(for: .navigateToPlay)) { _ in
            selectedTab = .play
        }
        .onReceive(NotificationCenter.default.publisher(for: .navigateToMemoryLane)) { _ in
            selectedTab = .play
        }
        .onReceive(NotificationCenter.default.publisher(for: .navigateToConnectionChallenges)) { _ in
            selectedTab = .play
        }
        .onReceive(NotificationCenter.default.publisher(for: .navigateToAnswerHistory)) { _ in
            if appState.currentUser?.coupleId == nil {
                showCreateInvite = true
            } else {
                showAnswerHistory = true
            }
        }
        .onReceive(NotificationCenter.default.publisher(for: .navigateToSettings)) { _ in
            selectedTab = .settings
        }
        .navigationDestination(isPresented: $showAnswerHistory) {
            AnswerHistoryView()
        }
        .fullScreenCover(isPresented: $showCreateInvite) {
            CreateInviteView()
                .environmentObject(appState)
        }
    }

    private func routeToDailyOrInvite() {
        if appState.currentUser?.coupleId == nil {
            showCreateInvite = true
        } else {
            selectedTab = .dailyQuestion
        }
    }
}

// MARK: - Onboarding Flow

struct OnboardingFlow: View {
    @State private var showLogin = false
    @State private var showSignUp = false

    var body: some View {
        OnboardingView(showLogin: $showLogin, showSignUp: $showSignUp)
            .navigationDestination(isPresented: $showLogin) {
                LoginView()
            }
            .navigationDestination(isPresented: $showSignUp) {
                SignUpView()
            }
    }
}

// MARK: - Import for Secret

import Foundation
