//
//  AppDelegate.swift
//  AI Companion for Meet
//
//  Created by Dev Mac 1 on 06/04/2026.
//

import Cocoa
import UserNotifications

@main
class AppDelegate: NSObject, NSApplicationDelegate {
    private let darkModeDefaultsKey = "settings.darkModeEnabled"
    private var statusBarController: StatusBarController?

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Always sync to current macOS appearance on launch.
        // (User can still toggle in-app later.)
        let darkEnabled = systemPrefersDarkMode()
        UserDefaults.standard.set(darkEnabled, forKey: darkModeDefaultsKey)
        NSApp.appearance = NSAppearance(named: darkEnabled ? .darkAqua : .aqua)
        UNUserNotificationCenter.current().delegate = self
        MeetingReminderManager.shared.requestPermissionIfNeeded()
        DesktopWidgetWindowManager.shared.restore()
        statusBarController = StatusBarController()
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

    func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
        return true
    }

    private func systemPrefersDarkMode() -> Bool {
        // Use the system-wide appearance setting (not app/window effective appearance).
        // When the key is missing, macOS is in Light mode.
        let global = UserDefaults.standard.persistentDomain(forName: UserDefaults.globalDomain)
        let style = global?["AppleInterfaceStyle"] as? String
        return style?.lowercased() == "dark"
    }

}

extension AppDelegate: UNUserNotificationCenterDelegate {

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {
        NSRunningApplication.current.activate(options: [.activateAllWindows, .activateIgnoringOtherApps])
        NSApp.activate(ignoringOtherApps: true)
        completionHandler()
    }

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
    ) {
        completionHandler([.banner, .sound])
    }
}

