import UIKit
import WidgetKit

@main
final class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    private var context: AppContext?

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
    ) -> Bool {
        let window = UIWindow(frame: UIScreen.main.bounds)
        let context = AppContext(window: window)
        self.context = context
        window.rootViewController = context.makeRootController()
        window.makeKeyAndVisible()
        self.window = window
        context.notifications.start()
        context.showStartupErrorIfNeeded()
        if let url = launchOptions?[.url] as? URL {
            context.route(widgetURL: url)
        }
        return true
    }

    func application(
        _ application: UIApplication,
        open url: URL,
        options: [UIApplication.OpenURLOptionsKey: Any] = [:]
    ) -> Bool {
        context?.route(widgetURL: url) ?? false
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        WidgetCenter.shared.reloadAllTimelines()
        context?.notifications.applicationDidBecomeActive()
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        context?.notifications.applicationDidEnterBackground()
    }
}
