// ContentView.swift — root view, switches on pairing state

import SwiftUI

struct ContentView: View {
    @EnvironmentObject var appState: AppState
    @Environment(\.scenePhase) private var scenePhase

    var body: some View {
        ZStack {
            Group {
                if let credential = appState.credential {
                    MainTerminalView(credential: credential)
                } else {
                    PairingFlowView { credential in
                        appState.didPair(credential: credential)
                    }
                }
            }
            .onChange(of: scenePhase) { _, new in
                if new == .background {
                    appState.appDidBackground()
                } else if new == .active {
                    Task { await appState.appWillForeground() }
                }
            }

            if appState.isLocked {
                LockView()
            }
        }
        .task { await appState.appWillForeground() }
    }
}
