import UIKit
import Capacitor

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Disable WKWebView rubber-band overscroll so the MUI chat layout feels native.
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(disableWebViewBounce),
            name: UIApplication.didBecomeActiveNotification,
            object: nil
        )
        return true
    }

    @objc private func disableWebViewBounce() {
        guard let root = window?.rootViewController else { return }
        applyNoBounce(to: root)
    }

    private func applyNoBounce(to controller: UIViewController) {
        if let bridge = controller as? CAPBridgeViewController,
           let scrollView = bridge.webView?.scrollView {
            scrollView.bounces = false
            scrollView.alwaysBounceVertical = false
            scrollView.alwaysBounceHorizontal = false
        }
        for child in controller.children {
            applyNoBounce(to: child)
        }
        if let presented = controller.presentedViewController {
            applyNoBounce(to: presented)
        }
    }

    func applicationWillResignActive(_ application: UIApplication) {
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        disableWebViewBounce()
    }

    func applicationWillTerminate(_ application: UIApplication) {
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
        return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
    }

    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler)
    }

}
