//
//  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 *vc = window.rootViewController;
    if (!vc) return nil;
    // 展开容器控制器
    while (1) {
        if ([vc isKindOfClass:UINavigationController.class]) {
            vc = ((UINavigationController *)vc).visibleViewController ?: vc;
            continue;
        }
        if ([vc isKindOfClass:UITabBarController.class]) {
            vc = ((UITabBarController *)vc).selectedViewController ?: vc;
            continue;
        }
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
            continue;
        }
        break;
    }
    return vc;
}

@end
