//
//  yobbleApp.swift
//  yobble
//
//  Created by cheykrym on 19.09.2025.
//

import SwiftUI
import CoreData

@main
struct yobbleApp: App {
//    @UIApplicationDelegateAdaptor(PushAppDelegate.self) var appDelegate
    @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate

    @StateObject private var themeManager = ThemeManager()
    @StateObject private var viewModel = LoginViewModel()
    @StateObject private var messageCenter = IncomingMessageCenter()
    private let persistenceController = PersistenceController.shared
    
    var body: some Scene {
        WindowGroup {
            ZStack(alignment: .top) {
                Group {
                    if viewModel.isInitialLoading {
                        SplashScreenView()
                    } else if viewModel.isLoggedIn {
                        MainView(viewModel: viewModel)
                    } else {
                        LoginView(viewModel: viewModel)
                    }
                }

                if let banner = messageCenter.banner {
                    NewMessageBannerView(
                        banner: banner,
                        onOpen: { messageCenter.openCurrentChat() },
                        onDismiss: { messageCenter.dismissBanner() }
                    )
                    .padding(.horizontal, 16)
                    .padding(.top, 12)
                    .transition(.move(edge: .top).combined(with: .opacity))
                    .zIndex(1)
                }
            }
            .animation(.spring(response: 0.35, dampingFraction: 0.8), value: messageCenter.banner != nil)
            .sheet(item: AppConfig.PRESENT_CHAT_AS_SHEET ? $messageCenter.presentedChat : .constant(nil)) { chatItem in
                NavigationView {
                    PrivateChatView(
                        chat: chatItem,
                        currentUserId: messageCenter.currentUserId
                    )
                        .toolbar {
                            ToolbarItem(placement: .cancellationAction) {
                                Button(NSLocalizedString("Закрыть", comment: "")) {
                                    messageCenter.presentedChat = nil
                                }
                            }
                        }
                }
            }
            .environmentObject(messageCenter)
            .environmentObject(themeManager)
            .preferredColorScheme(themeManager.theme.colorScheme)
            .environment(\.managedObjectContext, persistenceController.viewContext)
            .onAppear {
                messageCenter.currentUserId = viewModel.userId.isEmpty ? nil : viewModel.userId
            }
            .onChange(of: viewModel.userId) { newValue in
                messageCenter.currentUserId = newValue.isEmpty ? nil : newValue
            }
        }
    }
}
