import SwiftUI

/// Gates the whole UI on iCloud availability. Files are the source of truth, so
/// there is no meaningful app without iCloud — we never fall back to local-only.
struct RootGateView: View {
    @Environment(SyncEngine.self) private var syncEngine
    @Environment(\.scenePhase) private var scenePhase

    var body: some View {
        Group {
            switch syncEngine.iCloudStatus {
            case .checking:
                ProgressView("Connecting to iCloud…")
            case .available:
                ContentView()
            case .unavailable:
                ContentUnavailableView {
                    Label("iCloud Required", systemImage: "icloud.slash")
                } description: {
                    Text("Sign in to iCloud in Settings to use Workouts. Your data lives in iCloud Drive so it's safe and on all your devices.")
                } actions: {
                    Button("Try Again") { Task { await syncEngine.connect() } }
                        .buttonStyle(.borderedProminent)
                }
            }
        }
        .onChange(of: scenePhase) { _, phase in
            if phase == .active, syncEngine.iCloudStatus == .unavailable {
                Task { await syncEngine.connect() }
            }
        }
    }
}
