//
//  Heise Vision Pro
//  Copyright © 2024 Gero Gerber. All rights reserved.
//

import SwiftUI

struct ToggleImmersiveSpaceButton: View {
    @Environment(AppModel.self) private var appModel
    @Environment(\.dismissImmersiveSpace) private var dismissImmersiveSpace
    @Environment(\.openImmersiveSpace) private var openImmersiveSpace

    let labelText: String
    let immersiveSpaceId: String

    var body: some View {
        Button {
            Task { @MainActor in
                if appModel.currentImmersiveSpaceID == immersiveSpaceId {
                    await dismissImmersiveSpace()
                    appModel.currentImmersiveSpaceID = nil
                } else {
                    appModel.immersiveSpaceIsLoading = true
                    appModel.currentImmersiveSpaceID = nil

                    switch await openImmersiveSpace(id: immersiveSpaceId) {
                        case .opened:
                            appModel.currentImmersiveSpaceID = immersiveSpaceId
                        case .userCancelled, .error:
                            fallthrough
                        @unknown default:
                            appModel.currentImmersiveSpaceID = nil
                    }

                    appModel.immersiveSpaceIsLoading = false
                }
            }
        } label: {
            Text(appModel.currentImmersiveSpaceID == immersiveSpaceId ? "Stop \(labelText)" : "Start \(labelText)")
                .frame(width: 300)
        }
        .disabled(appModel.immersiveSpaceIsLoading || appModel.assetsLoaded == false)
        .animation(.none, value: 0)
        .fontWeight(.semibold)
    }
}
