//
//  ContentView.swift
//  Gran Fondo
//
//  Created by Willem L. Middelkoop on 27/04/2024.
//

import SwiftUI
import CoreBluetooth
import HealthKit
import Charts
import ActivityKit

struct ContentView: View {
    @EnvironmentObject var bluetoothManager: BluetoothManager
    @EnvironmentObject var activityRecorder: ActivityRecorder
    @EnvironmentObject var entitlementManager: EntitlementManager
    @State private var showWelcomeView = false
    @State private var welcomeViewHeight = Double.zero
    @State private var showMenuView = false
    @State private var showSensorView = false
    @State private var showDataView = false
    //@State private var dataViewHeight = Double.zero
    @State private var showHeroView = false
    @State private var showStopConfirmation = false
    
    @State private var pauseViewHeight = Double.zero
    
    @State private var showGraphSpeed = true
    @State private var showGraphCadence = true
    @State private var showGraphPower = true
    @State private var showGraphHeartrate = true
    
    @State private var fade = false
   // @State private var isSaving = false
    
    var body: some View {
        let scopeRange = activityRecorder.timeRangeForPreferredScope()
        
        VStack (spacing: 0) {
            HStack(alignment: .center){
                if !activityRecorder.isRecording {
                    VStack {
                        Button(action: {
                            showMenuView = true
                        }) {
                            Image(systemName: "slider.horizontal.3")
                                .resizable()
                                .scaledToFit()
                                .frame(width: 25, height: 25)
                                .foregroundColor(.white)
                        }
                        
                    }
                }
                
                VStack( spacing: 0){
                    Text("Gran Fondo: \(accessibilityLabel(for: activityRecorder.selectedWorkoutType))")
                        .foregroundColor(.white)
                        .font(.system(size: 20))
                        .fontWeight(.bold)
                        .frame(maxWidth: .infinity)
                    
                    if showWelcomeView {
                        Text("Welcome")
                            .foregroundColor(.white)
                            .font(.system(size: 18))
                            .fontWeight(.regular)
                            .textCase(.lowercase)
                            .frame(maxWidth: .infinity)
                    }else {
                        if activityRecorder.isLocationRestricted {
                            Text("Location unavailable")
                                .foregroundColor(.red)
                                .font(.system(size: 18))
                                .fontWeight(.regular)
                                .frame(maxWidth: .infinity)
                        } else if activityRecorder.isHealthKitRestricted {
                            Text("Apple Health unavailable")
                                .foregroundColor(.orange)
                                .font(.system(size: 18))
                                .fontWeight(.regular)
                                .frame(maxWidth: .infinity)
                        } else if bluetoothManager.isBluetoothRestricted {
                            Text("Bluetooth unavailable")
                                .foregroundColor(.orange)
                                .font(.system(size: 18))
                                .fontWeight(.regular)
                                .frame(maxWidth: .infinity)
                        } else { // no errors, hooray.
                            if activityRecorder.isPaused {
                                Text("paused")
                                    .foregroundColor(.yellow)
                                    .font(.system(size: 18))
                                    .fontWeight(.regular)
                                    .textCase(.lowercase)
                                    .frame(maxWidth: .infinity)
                            }else if activityRecorder.isRecording || activityRecorder.totalDistance > 500 {
                                Text(getCurrentScopeSummary())
                                    .foregroundColor(.white)
                                    .font(.system(size: 18))
                                    .fontWeight(.regular)
                                    .textCase(.lowercase)
                                    .frame(maxWidth: .infinity)
                            }else{
                                if bluetoothManager.allSensorsConnected {
                                    Text("ready to record")
                                        .foregroundColor(.green)
                                        .font(.system(size: 18))
                                        .fontWeight(.regular)
                                        .textCase(.lowercase)
                                        .frame(maxWidth: .infinity)
                                } else {
                                    Button( action: {
                                        showSensorView = true
                                    }){
                                        Text(bluetoothManager.foundNewSensors ? "found new sensors" : "looking for sensors")
                                            .foregroundColor(.blue)
                                            .font(.system(size: 18))
                                            .fontWeight(.regular)
                                            .textCase(.lowercase)
                                            .frame(maxWidth: .infinity)
                                            .opacity(fade ? 1 : 0.5)
                                            .animation(Animation.easeInOut(duration: 1).repeatForever(autoreverses: true), value: fade)
                                            .onAppear {
                                                self.fade = true
                                            }
                                    }
                                }
                            }
                        }
                    }
                }
                
                if !activityRecorder.isRecording {
                    VStack {
                        Button(action: {
                            showDataView = true
                        }) {
                            Image(systemName: "calendar")
                                .resizable()
                                .scaledToFit()
                                .frame(width: 25, height: 25)
                                .foregroundColor(.white)
                        }
                    }
                }
            }
            .padding(.horizontal)
            .padding(.bottom, 10)
            .background(Color(red: 0.2, green: 0.2, blue: 0.2))
            
            Spacer()
            // SPEED
            ZStack (alignment: .bottom) {
                
                if showGraphSpeed {
                    Chart(activityRecorder.dataPointsSelected, id: \.id) { point in
                        AreaMark(
                            x: .value("Time", point.timestamp),
                            y: .value("Speed", (activityRecorder.unitsPreference == UnitsPreference.Imperial ? point.speed / 1.609344 : point.speed))
                        ).foregroundStyle(Gradient ( colors: [.blue.opacity(1.0), .blue.opacity(0.6), .blue.opacity(0.25)]))
                            .interpolationMethod(.linear)
                        
                                                RuleMark(y: .value("Speed", (activityRecorder.unitsPreference == UnitsPreference.Imperial ? activityRecorder.currentScopeAverageSpeed / 1.609344  : activityRecorder.currentScopeAverageSpeed)))
                            .foregroundStyle(.white)
                            .lineStyle(StrokeStyle(lineWidth: 1, dash: [8]))
                            .opacity(0.1)
                    }
                    
                    .chartYAxis {
                        AxisMarks(
                            values: .automatic
                        ) {
                            AxisGridLine()
                        }
                    }
                    .chartXAxis {
                        AxisMarks(
                            values: .automatic
                        ) {
                            AxisGridLine()
                        }
                    }
                    .chartXScale(domain: scopeRange)
                    .contentShape(Rectangle())
                    .onTapGesture {
                        toggleScope()
                    }
                    .frame(maxHeight: .infinity)
                }
                
                HStack (spacing: 0){
                    Button(action: {
                        showSensorView = true
                    }) {
                        Image(systemName: "arrowshape.right.fill")
                            .foregroundColor(.white)
                            .font(.system(size: 30))
                            .frame(width:30)
                        
                        if bluetoothManager.isSpeedSensorConnected {
                            Image(systemName: "dot.radiowaves.forward")
                                .foregroundColor(.gray)
                                .font(.system(size: 15))
                                .symbolEffect(
                                    .pulse, isActive:!bluetoothManager.isSpeedSensorConnected && !activityRecorder.isRecording
                                )
                            Text(bluetoothManager.speedSensor?.name ?? "")
                                .font(.system(size: 10))
                                .fontWeight(.bold)
                                .textCase(.uppercase)
                                .foregroundColor(.gray)
                                .multilineTextAlignment(.leading)
                                .lineLimit(2)
                                .allowsTightening(true)
                                .truncationMode(.middle)
                        }
                    }
                    Spacer()
                    
                    HStack{
                        Button(action: {
                            showGraphSpeed = !showGraphSpeed
                        }){
                            if activityRecorder.selectedWorkoutType == .running {
                                Text(activityRecorder.paceFromSpeedKmPerHour(activityRecorder.currentSpeed))
                                    .font(.system(size: 50).monospacedDigit())
                                    .foregroundColor(.white)
                                    .frame(minWidth: 170, alignment: .trailing)
                                    .lineLimit(1)
                                    .allowsTightening(false)
                                VStack (alignment: .leading){
                                    Text("/km").foregroundColor(.gray).fontWeight(.light)
                                        .font(.system(size: 30))
                                        .frame(width:75, alignment: .leading)
                                    Text("pace")
                                        .font(.system(size: 10))
                                        .fontWeight(.bold)
                                        .textCase(.uppercase)
                                        .foregroundColor(.gray)
                                        .frame(width:75, alignment: .leading)
                                }
                                
                            }else{ // we assume 'normal' KM/h
                                Text("\( (activityRecorder.unitsPreference == UnitsPreference.Imperial ? activityRecorder.currentSpeed / 1.609344 : activityRecorder.currentSpeed), specifier: "%.1f")" )
                                    .font(.system(size: 50).monospacedDigit())
                                    .foregroundColor(.white)
                                    .frame(minWidth: 170, alignment: .trailing)
                                VStack{
                                    Text((activityRecorder.unitsPreference == UnitsPreference.Metric) ? "km/h" : "mph").foregroundColor(.gray).fontWeight(.light)
                                        .font(.system(size: 30))
                                        .frame(width:75, alignment: .leading)
                                    Text("speed")
                                        .font(.system(size: 10))
                                        .fontWeight(.bold)
                                        .textCase(.uppercase)
                                        .foregroundColor(.gray)
                                        .frame(width:75, alignment: .leading)
                                }
                            }
                        }
                    }
                }
                .padding(.horizontal)
                .frame(minHeight: 0, alignment: .center)
                .background(.thinMaterial)
            }
            
            // CADENCE
            if(activityRecorder.selectedWorkoutType == .cycling && bluetoothManager.isCadenceSensorConnected){
                ZStack (alignment: .bottom){
                    if activityRecorder.selectedWorkoutType == .cycling && (bluetoothManager.isCadenceSensorConnected && showGraphCadence) {
                        Chart(activityRecorder.dataPointsSelected, id: \.id) { point in
                            AreaMark(
                                x: .value("Time", point.timestamp),
                                y: .value("Cadence", point.cadence != ActivityRecorder.NOVALUE ? point.cadence : 0)
                            ).foregroundStyle(Gradient ( colors: [.purple.opacity(1.0), .purple.opacity(0.6), .purple.opacity(0.25)]))
                                .interpolationMethod(.linear)
                            
                            RuleMark(y: .value("Cadence", activityRecorder.currentScopeAverageCadence))
                                .foregroundStyle(.white)
                                .lineStyle(StrokeStyle(lineWidth: 1, dash: [8]))
                                .opacity(0.1)
                        }.chartYAxis {
                            AxisMarks(
                                values: .automatic//[0, 50, 100]
                            ) {
                                AxisGridLine()
                            }
                        }.chartXAxis {
                            AxisMarks(
                                values: .automatic
                            ) {
                                AxisGridLine()
                            }
                        }
                        .chartXScale(domain: scopeRange)
                        .contentShape(Rectangle()) // Make the entire chart tappable
                        .onTapGesture {
                            toggleScope()
                        }
                        .frame(maxHeight: .infinity)
                    }
                    
                    HStack (spacing: 0){
                        Button(action: {
                            showSensorView = true
                        }) {Image(systemName: "arrow.counterclockwise.circle")
                                .foregroundColor(.white)
                                .font(.system(size: 30))
                                .frame(width:30)
                            Image(systemName: "dot.radiowaves.forward")
                                .foregroundColor(.gray)
                                .font(.system(size: 15))
                                .symbolEffect(
                                    .pulse, isActive:!bluetoothManager.isCadenceSensorConnected && !activityRecorder.isRecording
                                )
                            Text(bluetoothManager.cadenceSensor?.name ?? "")
                                .font(.system(size: 10))
                                .fontWeight(.bold)
                                .textCase(.uppercase)
                                .foregroundColor(.gray)
                                .multilineTextAlignment(.leading)
                                .lineLimit(2)
                                .allowsTightening(true)
                                .truncationMode(.middle)
                        }
                        Spacer()
                        HStack{
                            Button(action: {
                                showGraphCadence = !showGraphCadence
                            }){
                                Text("\(activityRecorder.currentCadence == ActivityRecorder.NOVALUE ? 0 : activityRecorder.currentCadence)")
                                    .font(.system(size: 50).monospacedDigit())
                                    .foregroundColor(.white)
                                    .frame(minWidth: 140, alignment: .trailing)
                                    .lineLimit(1)
                                    .allowsTightening(false)
                                VStack{
                                    Text("rpm").foregroundColor(.gray).fontWeight(.light)
                                        .font(.system(size: 30))
                                        .frame(width:75, alignment: .leading)
                                    Text("Cadence")
                                        .font(.system(size: 10))
                                        .fontWeight(.bold)
                                        .textCase(.uppercase)
                                        .foregroundColor(.gray)
                                        .frame(width:75, alignment: .leading)
                                }
                            }
                        }
                    }
                    .padding(.horizontal)
                    .frame(minHeight: 0, alignment: .center)
                    .background(.ultraThinMaterial)
                }
            }
            
            // POWER
            if(activityRecorder.selectedWorkoutType == .cycling && bluetoothManager.isPowerMeterConnected){
                ZStack (alignment:.bottom){
                    
                    if activityRecorder.selectedWorkoutType == .cycling && (bluetoothManager.isPowerMeterConnected && showGraphPower) {
                        Chart(activityRecorder.dataPointsSelected, id: \.id) { point in
                            
                            AreaMark(
                                x: .value("Time", point.timestamp),
                                y: .value("Power (watt)", point.power != ActivityRecorder.NOVALUE ? point.power : 0)
                            ).foregroundStyle(Gradient ( colors: [.green.opacity(1.0), .green.opacity(0.6), .green.opacity(0.25)]))
                                .interpolationMethod(.linear)
                            
                            RuleMark(y: .value("Power (watt)", activityRecorder.currentScopeAveragePower))
                                .foregroundStyle(.white)
                                .lineStyle(StrokeStyle(lineWidth: 1, dash: [8]))
                                .opacity(0.1)
                        }
                        .chartYAxis {
                            AxisMarks(
                                values: .automatic
                            ) {
                                AxisGridLine()
                            }
                        }
                        .chartXAxis {
                            AxisMarks(
                                values: .automatic
                            ) {
                                AxisGridLine()
                            }
                        }
                        .chartXScale(domain: scopeRange)
                        .contentShape(Rectangle())
                        .onTapGesture {
                            toggleScope()
                        }
                        .frame(maxHeight: .infinity)
                    }
                    
                    HStack (spacing: 0){
                        Button(action: {
                            showSensorView = true
                        }) {
                            Image(systemName: "bolt.fill")
                                .foregroundColor(.white)
                                .font(.system(size: 30))
                                .frame(width:30)
                            Image(systemName: "dot.radiowaves.forward")
                                .foregroundColor(.gray)
                                .font(.system(size: 15))
                                .symbolEffect(
                                    .pulse, isActive:!bluetoothManager.isPowerMeterConnected && !activityRecorder.isRecording
                                )
                            Text(bluetoothManager.powerMeter?.name ?? "")
                                .font(.system(size: 10))
                                .fontWeight(.bold)
                                .textCase(.uppercase)
                                .foregroundColor(.gray)
                                .lineLimit(2)
                                .allowsTightening(true)
                                .truncationMode(.middle)
                                .multilineTextAlignment(.leading)
                        }
                        Spacer()
                        
                        HStack{
                            Button(action: {
                                showGraphPower = !showGraphPower
                            }){
                                Text("\(activityRecorder.currentPower == ActivityRecorder.NOVALUE ? 0 : activityRecorder.currentPower)" )
                                    .font(.system(size: 50).monospacedDigit())
                                    .foregroundColor(.white)
                                    .frame(minWidth: 140, alignment: .trailing)
                                    .lineLimit(1)
                                    .allowsTightening(false)
                                VStack{
                                    Text("watt").foregroundColor(.gray).fontWeight(.light)
                                        .font(.system(size: 30))
                                        .frame(width:75, alignment: .leading)
                                    Text("Power")
                                        .font(.system(size: 10))
                                        .fontWeight(.bold)
                                        .textCase(.uppercase)
                                        .foregroundColor(.gray)
                                        .frame(width:75, alignment: .leading)
                                }
                            }
                        }
                    }
                    .padding(.horizontal)
                    .frame(minHeight: 0, alignment: .center)
                    .background(.ultraThinMaterial)
                }
            }
            
            if(bluetoothManager.isHeartRateMonitorConnected){
                // HEART RATE
                ZStack(alignment: .bottom){
                    if (bluetoothManager.isHeartRateMonitorConnected && showGraphHeartrate) {
                        HStack{
                            Chart(activityRecorder.dataPointsSelected, id: \.id) { point in
                                
                                AreaMark(
                                    x: .value("Time", point.timestamp),
                                    y: .value("Heart Rate (bpm)", point.heartRate != ActivityRecorder.NOVALUE ? point.heartRate : 0)
                                ).foregroundStyle(Gradient ( colors: [.red.opacity(1.0), .red.opacity(0.6), .red.opacity(0.25)]))
                                    .interpolationMethod(.linear)
                                    
                                
                                RuleMark(y: .value("Heart Rate (bpm)", activityRecorder.currentScopeAverageHeartRate))
                                    .foregroundStyle(.white)
                                    .lineStyle(StrokeStyle(lineWidth: 1, dash: [8]))
                                    .opacity(0.1)
                                /*  .annotation(position: .overlay, alignment: .topTrailing, spacing: 0) {
                                 VStack{
                                 Text("55")
                                 .fontWeight(.bold)
                                 .font(.system(size: 30).monospacedDigit())
                                 .foregroundColor(.white)
                                 .padding(.horizontal)
                                 .opacity(0.1)
                                 Text("average")
                                 .font(.system(size: 10))
                                 .fontWeight(.bold)
                                 .textCase(.uppercase)
                                 .foregroundColor(.white)
                                 .opacity(0.1)
                                 }
                                 }*/
                                
                            }
                            
                            .chartYAxis {
                                AxisMarks(
                                    values: .automatic
                                ) {
                                    AxisGridLine()
                                }
                            }
                            .chartXAxis {
                                AxisMarks(
                                    values: .automatic
                                ) {
                                    AxisGridLine()
                                }
                            }
                            .chartXScale(domain: scopeRange)
                            .contentShape(Rectangle())
                            .onTapGesture {
                                toggleScope()
                            }
                            .frame(maxHeight: .infinity)
                        }
                    }
                    
                    HStack (spacing: 0){
                        Button(action: {
                            showSensorView = true
                        }) {
                            Image(systemName: "heart.fill")
                                .foregroundColor(.white)
                                .font(.system(size: 30))
                                .frame(width:30)
                            Image(systemName: "dot.radiowaves.forward")
                                .foregroundColor(.gray)
                                .font(.system(size: 15))
                                .symbolEffect(
                                    .pulse, isActive:!bluetoothManager.isHeartRateMonitorConnected && !activityRecorder.isRecording
                                )
                            Text(bluetoothManager.heartRateMonitor?.name ?? "")
                                .font(.system(size: 10))
                                .fontWeight(.bold)
                                .textCase(.uppercase)
                                .foregroundColor(.gray)
                                .multilineTextAlignment(.leading)
                                .allowsTightening(true)
                                .lineLimit(2)
                                .truncationMode(.middle)
                        }
                        Spacer()
                        HStack{
                            Button(action: {
                                showGraphHeartrate = !showGraphHeartrate
                            }){
                                Text("\(activityRecorder.currentHeartRate == ActivityRecorder.NOVALUE ? 0 : activityRecorder.currentHeartRate)")
                                    .font(.system(size: 50).monospacedDigit())
                                    .foregroundColor(.white)
                                    .lineLimit(1)
                                    .allowsTightening(false)
                                    .frame(minWidth: 100, alignment: .trailing)
                                VStack{
                                    Text("bpm").foregroundColor(.gray).fontWeight(.light)
                                        .font(.system(size: 30))
                                        .frame(width:75, alignment: .leading)
                                    Text("heart rate")
                                        .font(.system(size: 10))
                                        .fontWeight(.bold)
                                        .textCase(.uppercase)
                                        .foregroundColor(.gray)
                                        .frame(width:75, alignment: .leading)
                                }
                            }
                        }
                    }
                    .padding(.horizontal)
                    .frame(minHeight: 0, alignment: .center)
                    .background(.ultraThinMaterial)
                }
                
            }
            
            
            /*  HStack {
             // Existing start/stop button here
             Button(action: toggleScope) {
             HStack{
             Image(systemName: "chart.line.uptrend.xyaxis")
             Text("\(activityRecorder.preferredScope.description): 5.3KM @ 22 km/h")
             }
             }
             .fontWeight(.regular)
             .font(.system(size: 20))
             .textCase(.lowercase)
             /*.frame(height: 20)*/
             .frame(maxWidth: .infinity)
             /*.padding()*/
             .background(Color.black)
             .foregroundColor(Color.gray.opacity(0.5))
             .cornerRadius(8)
             // .clipShape(Capsule())
             }.padding(.horizontal)
             */
            
            
            HStack {
                if !activityRecorder.isRecording {
                    VStack {
                        HStack {
                            workoutTypeButton(for: .cycling)
                            workoutTypeButton(for: .running)
                        }
                        .padding(3)
                        .background(.gray)
                        .cornerRadius(8)
                        
                        Text(accessibilityLabel(for: activityRecorder.selectedWorkoutType))
                            .font(.system(size: 10))
                            .fontWeight(.bold)
                            .textCase(.uppercase)
                            .foregroundColor(.white)
                    }
                }
                
                VStack {
                    recordingButton
                    /*Text(isSaving ? "Saving" : showStopConfirmation ? "Tap again to confirm" : activityRecorder.isRecording ? "Recording" : activityRecorder.isLocationRestricted ? "No Location" :  "Ready to record")
                        .font(.system(size: 10))
                        .fontWeight(.bold)
                        .textCase(.uppercase)
                        .foregroundColor(.white)*/
                    Text(activityRecorder.isSaving ? "Saving" : activityRecorder.isPaused ? "Paused" : activityRecorder.isRecording ? "Recording" : activityRecorder.isLocationRestricted ? "No Location" :  "Ready to record")
                        .font(.system(size: 10))
                        .fontWeight(.bold)
                        .textCase(.uppercase)
                        .foregroundColor(.white)
                }
            }
            .padding(.horizontal)
            .padding(.bottom, 10)
            .padding(.top, 10)
            .background(Color(red: 0.2, green: 0.2, blue: 0.2))
        }
        .background(.black)
        .environment(\.colorScheme, .dark)
        
        .sheet(isPresented: $showWelcomeView) {
            WelcomeView()
            .presentationDragIndicator(.automatic)
            .readSize { newSize in
                welcomeViewHeight = newSize.height
            }
            .presentationDetents([.height(welcomeViewHeight)])
            
        }
        .sheet(isPresented: $showSensorView) {
            SensorView(sensors: $bluetoothManager.sensors, bluetoothManager: bluetoothManager)
        }
        .sheet(isPresented: $showMenuView) {
            MenuView()
        }
        .sheet(isPresented: $activityRecorder.isPaused, onDismiss: activityRecorder.resumeRecording) {
            PauseView()
                //presentationDragIndicator(.automatic)
                .readSize { newSize in
                    pauseViewHeight = newSize.height
                }
                .presentationDetents([.height(pauseViewHeight)])
        }
        .sheet(isPresented: $showDataView) {
            DataView()
                //.presentationCompactAdaptation(.none)
                .presentationDragIndicator(.automatic)
               /* .readSize { newSize in
                    dataViewHeight = newSize.height
                }
                .presentationDetents([.height(dataViewHeight)])*/
        }
        
        .onAppear {
            UIApplication.shared.isIdleTimerDisabled = true
            showWelcomeView = !activityRecorder.isWelcomed
            
            if !activityRecorder.isRecording && !entitlementManager.hasPro && activityRecorder.totalDistanceLifetime > ActivityRecorder.FREEMETERS{ // 10 KM
                showHeroView = true
            }
        }
        .onDisappear {
            UIApplication.shared.isIdleTimerDisabled = false
        }
    }
    
    
    private var timeFormat: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm:ss"
        return formatter
    }
    
    private var recordingButton: some View {
        Button(action: {
            if !activityRecorder.isRecording {
                activityRecorder.startRecording()
            } else if activityRecorder.isRecording {
                activityRecorder.pauseRecording()
            } /*else if showStopConfirmation {
                isSaving = true
                showStopConfirmation = false
                withAnimation {
                    activityRecorder.stopRecording { success in
                        print("ContentVIew: recordingButton completion handler succes")
                        isSaving = false  // Enable the button once saving is complete
                    }
                }
            }*/
        }) {
            HStack {
                if activityRecorder.isSaving {
                    ProgressView()
                        .progressViewStyle(.circular)
                        .scaleEffect(1.5)
                        .ignoresSafeArea(.all)
                        
                } else if showStopConfirmation {
                    
                    Text("STOP?")
                        .frame(alignment: .center)
                        .fontWeight(.bold)
                        .font(.system(size: 30)
                            .monospacedDigit())
                        .frame(height: 30)
                        .padding()
                        .background(activityRecorder.isRecording ? Color.red : Color.green)
                        .foregroundColor(.white)
                    
                    
                } else {
                    
                   /* */
                    if activityRecorder.isLocationRestricted {
                        
                        Image(systemName: "location.slash.fill")
                            .frame(alignment: .center)
                            .fontWeight(.bold)
                            .font(.system(size: 30)
                                .monospacedDigit())
                            .frame(height: 30)
                            .padding()
                        //.background(activityRecorder.isRecording ? Color.red : Color.green)
                            .foregroundColor(.white)
                    }else{
                        Text(activityRecorder.isRecording ? getRecordingButtonText() : "START")
                            .frame(alignment: .center)
                            .fontWeight(.bold)
                            .font(.system(size: 30)
                                .monospacedDigit())
                            .frame(height: 30)
                            .padding()
                        //.background(activityRecorder.isRecording ? Color.red : Color.green)
                            .foregroundColor(.white)
                    }
                }
            }
            .frame(height:30)
            .frame(maxWidth: .infinity, alignment: .center)
            .padding()
            .background(activityRecorder.isRecording ? Color.red : activityRecorder.isLocationRestricted ? Color.gray : Color.green)
            .foregroundColor(.white)
            .clipShape(Capsule())
        }
        .disabled(activityRecorder.isLocationRestricted || activityRecorder.isSaving)
        
       /* .confirmationDialog(
            "Please confirm",
            isPresented: $showStopConfirmation,
            titleVisibility: .visible
        ) {
            Button("Stop recording", role: .destructive) {
                isSaving = true
                withAnimation {
                    activityRecorder.stopRecording { success in
                        print("ContentVIew: recordingButton completion handler succes")
                        isSaving = false  // Enable the button once saving is complete
                    }
                }
            }.keyboardShortcut(.defaultAction)

            Button("Continue Recording", role: .cancel) {}
        }*/
        /*.alert(isPresented: $showSaveConfirmation) {
            Alert(
                title: Text("Confirm Stop"),
                message: Text("Are you sure you want to stop recording?"),
                primaryButton: .destructive(Text("Stop")) {
                    /*activityRecorder.stopRecording()*/
                    activityRecorder.stopRecording { success in
                        print("ContentVIew: recordingButton completion handler succes")
                        isSaving = false  // Enable the button once saving is complete
                    }
                    isSaving = true  // Disable the button while saving
                },
                secondaryButton: .cancel()
            )
        }*/
        
       /* Button(action: toggleRecording) {
            HStack {
                Image(systemName: activityRecorder.isRecording ? "stop.circle.fill" : "play.circle.fill")
                Text(activityRecorder.isRecording ? getFormattedElapsedTime(for: activityRecorder.elapsedTime) : "START")
                    .frame(minWidth: 100, alignment: .center)
                    .fontWeight(.bold)
                    .font(.system(size: 30)
                        .monospacedDigit())
                    .frame(height: 30)
                    .padding()
                    .background(activityRecorder.isRecording ? Color.red : Color.green)
                    .foregroundColor(.white)
                    .clipShape(Capsule())
            }
            .frame(height:30)
            .padding()
            .background(activityRecorder.isRecording ? Color.red : Color.green)
            .foregroundColor(.white)
            .clipShape(Capsule())
        }*/
    }
    
    func getCurrentScopeSummary() -> String{
        // Last 15 minutes: 25.7 KM @ 30.0 KM/h
        return activityRecorder.preferredScope.description + ": " + activityRecorder.getDistanceString(activityRecorder.currentScopeDistance) + " @ " + activityRecorder.getSpeedString(activityRecorder.currentScopeAverageSpeed, workoutType: activityRecorder.selectedWorkoutType)
    }
    
    func getRecordingButtonText() -> String{
        
        return activityRecorder.getDistanceString(activityRecorder.totalDistance) + " in " + activityRecorder.getFormattedElapsedTime(for: activityRecorder.elapsedTime)
    }
    
    private func workoutTypeButton(for type: HKWorkoutActivityType) -> some View {
        Button(action: {
            activityRecorder.selectedWorkoutType = type
        }) {
            Image(systemName: activityRecorder.getActivityTypeImageName(for: type))
                .resizable()
                .scaledToFit()
                .frame(width: 24, height: 24)
                .padding()
                .background(activityRecorder.selectedWorkoutType == type ? Color.white : Color.gray)
                .foregroundColor(activityRecorder.selectedWorkoutType == type ? Color.black : Color.white)
                .cornerRadius(8)
                .accessibilityLabel(accessibilityLabel(for: type))
                  
        }
        .disabled(activityRecorder.isRecording)
        .opacity(!activityRecorder.isRecording 
                 ? 1.0
                 : (activityRecorder.selectedWorkoutType == type) ? 1.0 : 0.1)
    }
    
    private func accessibilityLabel(for type: HKWorkoutActivityType) -> String {
        return activityRecorder.getActivityTypeDescription(for: type)
    }
    
    /*private func toggleRecording() {
        if activityRecorder.isRecording {
            activityRecorder.stopRecording()
        } else {
            activityRecorder.startRecording()
        }
    }*/
    
    private func toggleScope() {
        guard let currentIndex = DataPointScope.allCases.firstIndex(of: activityRecorder.preferredScope) else { return }
        let nextIndex = (currentIndex + 1) % DataPointScope.allCases.count
        activityRecorder.setDataPointScope(to: DataPointScope.allCases[nextIndex])
    }
}



#Preview {
    ContentView()
}

struct SizePreferenceKey: PreferenceKey {
  static var defaultValue: CGSize = .zero
  static func reduce(value: inout CGSize, nextValue: () -> CGSize) {}
}

extension View {
  func readSize(onChange: @escaping (CGSize) -> Void) -> some View {
    background(
      GeometryReader { geometryProxy in
        Color.clear
          .preference(key: SizePreferenceKey.self, value: geometryProxy.size)
      }
    )
    .onPreferenceChange(SizePreferenceKey.self, perform: onChange)
  }
}
