#import "UIApplication+TopViewController.h"

@implementation UIApplication (TopViewController)

- (UIViewController * _Nullable)topViewController {
    UIWindow *keyWindow = nil;
    
    for (UIScene *scene in self.connectedScenes) {
        if ([scene isKindOfClass:[UIWindowScene class]]) {
            UIWindowScene *windowScene = (UIWindowScene *)scene;
            for (UIWindow *window in windowScene.windows) {
                if (window.isKeyWindow) {
                    keyWindow = window;
                    break;
                }
            }
        }
        if (keyWindow) break;
    }
    
    if (!keyWindow) {
        return nil;
    }
    
    UIViewController *rootViewController = keyWindow.rootViewController;
    if (!rootViewController) {
        return nil;
    }
    
    return [self findTopMostViewControllerFrom:rootViewController];
}

- (UIViewController *)findTopMostViewControllerFrom:(UIViewController *)viewController {
    if (viewController.presentedViewController) {
        return [self findTopMostViewControllerFrom:viewController.presentedViewController];
    }
    
    if ([viewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController *navigationController = (UINavigationController *)viewController;
        return [self findTopMostViewControllerFrom:navigationController.visibleViewController];
    }
    
    if ([viewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabBarController = (UITabBarController *)viewController;
        return [self findTopMostViewControllerFrom:tabBarController.selectedViewController];
    }
    
    return viewController;
}

@end
