//
//  UIViewController+Extension.m
//  keyBoard
//
//  Created by Mac on 2025/11/3.
//

#import "UIViewController+Extension.h"

@implementation UIViewController (Extension)

/// Find the app's active window in a scene-friendly way (iOS 13+ safe)
static inline __kindof UIWindow *KBActiveWindow(void) {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    if (window) return window;
    // Fallbacks when keyWindow is nil (e.g. iOS 13+ with scenes)
    if (@available(iOS 13.0, *)) {
        for (UIScene *scene in [UIApplication sharedApplication].connectedScenes) {
            if (scene.activationState != UISceneActivationStateForegroundActive) { continue; }
            if (![scene isKindOfClass:[UIWindowScene class]]) { continue; }
            UIWindowScene *ws = (UIWindowScene *)scene;
            for (UIWindow *w in ws.windows) {
                if (w.isKeyWindow) { return w; }
            }
            if (ws.windows.firstObject) { return ws.windows.firstObject; }
        }
    }
    // iOS 12 and earlier fallback
    for (UIWindow *w in [UIApplication sharedApplication].windows) {
        if (w.isKeyWindow) { return w; }
    }
    return [UIApplication sharedApplication].windows.firstObject;
}

+ (UIViewController *)kb_topMostViewController {
    UIWindow *window = KBActiveWindow();
    UIViewController *root = window.rootViewController;
    if (!root) return nil;
    UIViewController *top = root;
    while (top.presentedViewController) {
        top = top.presentedViewController;
    }
    return top;
}

@end
