//
//  BottomView.swift
//  AcaMate
//
//  Created by TAnine on 2/4/25.
//

import SwiftUI

struct BottomView: View {
    @EnvironmentObject var appVM: AppViewModel
    @StateObject var btnVM = ButtonViewModel()
    
    @State private var homeID = UUID()
    @State private var managementID = UUID()
    @State private var chattingID = UUID()
    @State private var calendarID = UUID()
    @State private var etcID = UUID()
    
    
    let btnType: [MenuName] = [.Home, .Management, .Chatting, .Calendar, .Etc]
//    var idList: [UUID] = []
    
    var body: some View {
        let idList: [UUID] = [homeID,managementID,chattingID,calendarID,etcID]
        
        HStack(alignment: .center, spacing: 0){
            ForEach(Array(idList.enumerated()), id: \.offset) { index, id in
                CircleBtnView(vm: btnVM, id: id)
                if index != idList.count-1 {
                    Spacer(minLength: 1)
                }
            }
        }
        .padding(EdgeInsets(top: 12, leading: 24, bottom: 12, trailing: 24))
        
        .background {
            Rectangle()
                .foregroundStyle(Color(.Normal.dark))
                .ignoresSafeArea(edges: .bottom)
        }
        .frame(maxWidth: .infinity)
        .onAppear {
            //["홈", "학습 관리", "채팅", "일정", "더보기"]
//            idList = [homeID,managementID,chattingID,calendarID,etcID]
            
            let btnImage: [Image] = [Image(.Icon.home),Image(.Icon.management),Image(.Icon.chatting),Image(.Icon.calendar),Image(.Icon.etc)]
            
            idList.enumerated().forEach { (index, id) in
                btnVM.btnStates[id] = ButtonState()
                btnVM.setSize(for: id, newWidth: 52, newHeight: 52)
                btnVM.setText(for: id, newText: btnType[index].rawValue,
                              newFont: .nps(font: .bold, size: 6))
                btnVM.setImage(for: id, newImage: btnImage[index])
                if btnType[index] == appVM.menuName {
                    btnVM.setIsSelected(for: id, newValue: true)
                }
                btnVM.setAction(for: id) {
                    appVM.menuName = btnType[index]
                }
            }
        }
        .onChange(of: appVM.menuName) { old, new in
//            let idList: [UUID] = [homeID,managementID,chattingID,calendarID,etcID]

            if let oldID = btnType.firstIndex(of: old) {
                btnVM.setIsSelected(for: idList[oldID], newValue: false)
            }
            if let newID = btnType.firstIndex(of: new) {
                btnVM.setIsSelected(for: idList[newID], newValue: true)
            }
            
        }
        
    }
}
