import SwiftUI

@main
struct NucleicRemoteApp: App {
    @StateObject private var store = RemoteStore()
    @Environment(\.scenePhase) private var scenePhase
    @UIApplicationDelegateAdaptor(PushAppDelegate.self) private var pushDelegate

    var body: some Scene {
        WindowGroup {
            RootView()
                .environmentObject(store)
                .onAppear {
                    store.onAppear()
                    // Surface the notifications prompt + register for APNS. The token rides along
                    // in the sync Hello; the relay uses it to wake the phone for approvals (§3).
                    PushRegistrar.shared.requestAuthorizationAndRegister()
                    // Anonymous, opt-out, once-a-day DAI heartbeat (docs/CLOUD_INFRA.md §4).
                    Task { await HeartbeatReporter.reportIfDue() }
                }
                // Re-check on every foreground so a new active day is counted.
                .onChange(of: scenePhase) { _, phase in
                    if phase == .active { Task { await HeartbeatReporter.reportIfDue() } }
                }
        }
    }
}

struct RootView: View {
    @EnvironmentObject var store: RemoteStore
    // Initial tab; overridable via NUCLEIC_TAB for offline UI previews.
    @State private var tab = Int(ProcessInfo.processInfo.environment["NUCLEIC_TAB"] ?? "") ?? 0

    var body: some View {
        Group {
            if store.isPaired {
                TabView(selection: $tab) {
                    HomeView()
                        .tabItem { Label("Home", systemImage: "house") }.tag(0)
                    SessionsView()
                        .tabItem { Label("Sessions", systemImage: "square.stack.3d.up") }
                        .badge(store.needsYouCount).tag(1)
                    ProjectsView()
                        .tabItem { Label("Projects", systemImage: "folder") }.tag(2)
                    TodosView()
                        .tabItem { Label("To-dos", systemImage: "checklist") }.tag(3)
                    SettingsView()
                        .tabItem { Label("Settings", systemImage: "gearshape") }.tag(4)
                }
            } else {
                PairingIntroView()
            }
        }
        .tint(Palette.accent)
    }
}
