import SwiftUI

struct CompassView: View {
 
    @Binding var showPopup: Bool
    @State var showHorizontalGlobe: Bool = true
    @State var showAuxiliaryLine: Bool = true
    @State private var isCircularLevelVisible = true
    @State private var scale: CGFloat = 1.0
    @State private var showLables: Bool = true
    @EnvironmentObject var compassManager: CompassManager
    
    // To track the base scale for gesture
    @State private var baseScale: CGFloat = 1.0
    
    @State private var currentHeading: Double = 0.0
    @State private var previousHeading: Double = 0.0
    var body: some View {
        ZStack{
        VStack(spacing: 40) {
            
            HStack {
                Button(action: {
                    withAnimation(.easeInOut(duration: 0.6)) {
                        isCircularLevelVisible.toggle()
                    }
                    
                }) {
                    Image("nav_change")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .circularBackground(size: 44)
                }
                
                Spacer()
                
                if isCircularLevelVisible {
                    Button(action: {
                        showPopup = true
                    }) {
                        Image("nav_compass")
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .circularBackground(size: 44)
                    }
                }
            }
            .padding([.leading, .trailing], 20.0)
            .padding(.top, 20.0)
            .zIndex(1)
            
            Text("\(Int(compassManager.heading))° \(compassManager.dirction)")
                .font(.largeTitle)
                .bold()
                .zIndex(1)
            
            Spacer()
            
            ZStack {
                let shadowRadius: CGFloat = 10
                let shadowOffset: CGFloat = 5
                let radians = currentHeading * .pi / 180
                let xOffset = shadowOffset * cos(radians)
                let yOffset = shadowOffset * sin(radians)
                
                // 背对背的两张图片
                ZStack {
                    // 正面图片
                    Image("home_compass")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 320, height: 320)
                        .rotationEffect(.degrees(-currentHeading))
                        .clipShape(Circle())
                        .shadow(color: Color.customshadow, radius: shadowRadius, x: xOffset, y: yOffset)
                        .opacity(isCircularLevelVisible ? 1 : 0) // 当翻转时隐藏正面
                        .rotation3DEffect(Angle(degrees: isCircularLevelVisible ? 0 : 180), axis: (x: 0, y: 1, z: 0)) // 3D 翻转效果
                        .overlay(AnyView(
                            Rectangle()
                                .fill(Color.red)
                                .frame(width: 3, height: 45)
                                .offset(y: -150)
                        )  .opacity(isCircularLevelVisible ? 1 : 0)
                        )
                    CircularLevelView()
                        .clipShape(Circle())
                        .background(Color.clear)
                        .frame(width: 200, height: 200)
                        .rotationEffect(.degrees(-90))
                        .opacity((isCircularLevelVisible && showHorizontalGlobe) ? 1 : 0)
                    
                    
                    // 背面图片
                    Image("home_compass_1")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 320, height: 320)
                        .rotationEffect(.degrees(-currentHeading))
                        .clipShape(Circle())
                        .shadow(color: Color.customshadow, radius: shadowRadius, x: xOffset, y: yOffset)
                        .opacity(isCircularLevelVisible ? 0 : 1) // 当翻转时显示背面
                        .rotation3DEffect(Angle(degrees: isCircularLevelVisible ? -180 : 0), axis: (x: 0, y: 1, z: 0)) // 3D 翻转效果
                        .overlay(AnyView(
                            ZStack {
                                Rectangle()
                                    .fill(showAuxiliaryLine ? Color.red : Color.clear)
                                    .frame(width: 1)
                                    .frame(maxHeight: .infinity)
                                Rectangle()
                                    .fill(showAuxiliaryLine ? Color.red : Color.clear)
                                    .frame(height: 1)
                                    .frame(maxWidth: .infinity)
                            }
                        )  .opacity(isCircularLevelVisible ? 0 : 1)
                        )
                    
                }
                
                
            }
            .scaleEffect(isCircularLevelVisible ? 1.0 : scale)
            .gesture(
                isCircularLevelVisible == false ? MagnificationGesture()
                    .onChanged { value in
                        // Calculate the new scale based on the base scale
                        let newScale = baseScale * value
                        scale = min(max(newScale, 1.0), 2.0) // Limit between 1.0 and 1.8
                        showLables = scale <= 1.0
                    }
                    .onEnded { value in
                        baseScale = scale
                    } : nil // Only apply the gesture if isCircularLevelVisible == false
            )
            
            Spacer()
            
            if isCircularLevelVisible && showLables {
                // Bottom altitude and pressure display
                HStack {
                    Text(compassManager.altitude == 0.0 ? "----" : "\(L("Altitude")): \(Int(compassManager.altitude))m")
                        .font(.body)
                        .foregroundColor(.customtextcolor)
                    
                    Spacer()
                    
                    Text(compassManager.pressure == 0.0 ? "----" : "\(L("Pressure")): \(Int(compassManager.pressure))bp")
                        .font(.body)
                        .foregroundColor(.customtextcolor)
                }
                .padding(.horizontal, 100.0)
            }
            
            Spacer()
        }
            
       
           
    }
        
        
        .gradientBackground()
        .onAppear {
    
            showHorizontalGlobe = UserDefaults.standard.bool(forKey: "showHorizontalGlobe")
            showAuxiliaryLine = UserDefaults.standard.bool(forKey: "showAuxiliaryLine")
            currentHeading = compassManager.heading
        }
        
        .onChange(of: compassManager.heading) { newHeading in
            // 计算最短旋转角度
            let angleDifference = newHeading - currentHeading
            let adjustedAngle = (angleDifference + 540).truncatingRemainder(dividingBy: 360) - 180
            currentHeading += adjustedAngle
        }
    }
    
    
}

struct CompassView_Previews: PreviewProvider {
    static var previews: some View {
        CompassView(showPopup: Binding.constant(false))
    }
}

struct RotatingModifier: AnimatableModifier {
    var rotation: Double
    
    var animatableData: Double {
        get { rotation }
        set { rotation = newValue }
    }
    
    func body(content: Content) -> some View {
        content.rotationEffect(.degrees(rotation))
    }
}
