//
//  LocationView.swift
//  Toolboxes
//
//  Created by 研发2组 on 2024/9/21.
//

import SwiftUI
import MAMapKit
import CoreLocation

struct LocationView: View {
    
    @State private var showCompass: Bool = true
    @State private var selectedLayer: String = "satellite"
    @EnvironmentObject var compassManager: CompassManager
    
    var body: some View {
        ZStack {
            
            MapView(selectedLayer: $selectedLayer)
                .edgesIgnoringSafeArea(.all)
                .onAppear {
                    selectedLayer = UserDefaults.standard.string(forKey: "selectedMapLayer") ?? "satellite"
                }
            VStack {
                HStack {
                    Spacer()
                    
                    VStack(spacing: 40) {
                        
                        Button(action: {
                            MapViewManager.shared.loadUserLoc()
                        }) {
                            Image("location_loc")
                                .resizable() // 确保图像可调整大小
                                .aspectRatio(contentMode: .fit) // 保持宽高比
                                .circularwhiteBackground(size: 44)
                        }
                        
                        NavigationLink(destination: MapLayerView()) {
                            Image("location_layer")
                                .resizable() // 确保图像可调整大小
                                .aspectRatio(contentMode: .fit) // 保持宽高比
                                .circularwhiteBackground(size: 44)
                        }
                    }
                    .padding(.trailing, 20)
                }
                .padding(.top, 40)
                
                Spacer() // Moves buttons to the top-right corner
                
                if showCompass {
                    ZStack{
                        Image("loc_compass")
                            .resizable()
                            .scaledToFit()
                            .frame(width: 150, height: 150)
                            .clipShape(Circle())
                        
                        Image("loc_point")
                            .resizable()
                            .scaledToFit()
                            .frame(width: 50, height: 50)
                            .rotationEffect(Angle(degrees: -compassManager.heading))
                            .clipShape(Circle())
                    }
                }
                
                Spacer().frame(height: 30.00)
            }
        }
        .onAppear {
            showCompass = UserDefaults.standard.bool(forKey: "showCompass")
        }
        .navigationBarHidden(true)
    }


}



struct LocationView_Previews: PreviewProvider {
    static var previews: some View {
        LocationView()
    }
}
