//
//  XXGWindowManager.m
//  XXGPlayKit
//
//  Created by apple on 2025/2/26.
//

#import "XXGWindowManager.h"
#import "XXGOrientationViewController.h"
#import "XXGPlayKitConfig.h"

@interface XXGWindowManager()
@property (nonatomic, strong) NSMutableArray<UIWindow *> *windowsNoStack;  // 窗口栈管理
@property (nonatomic, strong) NSMutableArray<UIWindow *> *windowsStack;  // 窗口栈管理
@end

@implementation XXGWindowManager

- (instancetype)init {
    self = [super init];
    if (self) {
        _windowsNoStack = [NSMutableArray array];
        _windowsStack = [NSMutableArray array];
    }
    return self;
}

+ (instancetype)shared {
    static id shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[super alloc] init];
    });
    return shared;
}

/// 返回 App 当前第一个 UIWindow
- (UIWindow *)xxpk_firstWindow {
    UIWindow *firstWindow = nil;
    
    if (@available(iOS 13.0, *)) {
        // iOS 13+ 多 Scene 环境下，遍历所有已连接场景
        NSSet<UIScene *> *connectedScenes = [UIApplication sharedApplication].connectedScenes;
        for (UIScene *scene in connectedScenes) {
            // 只取前台激活的 UIWindowScene
            if (scene.activationState == UISceneActivationStateForegroundActive &&
                [scene isKindOfClass:[UIWindowScene class]]) {
                
                UIWindowScene *windowScene = (UIWindowScene *)scene;
                // 如果该场景下有 windows，就返回第一个
                if (windowScene.windows.count > 0) {
                    firstWindow = windowScene.windows.firstObject;
                }
                break;
            }
        }
    } else {
        // iOS 12 及以下，直接从 UIApplication.windows 取第一个
        NSArray<UIWindow *> *windows = [UIApplication sharedApplication].windows;
        if (windows.count > 0) {
            firstWindow = windows.firstObject;
        }
    }
    
    // 备用：如果上面还没拿到，直接从全局 windows 再取一次
    if (!firstWindow) {
        NSArray<UIWindow *> *windows = [UIApplication sharedApplication].windows;
        if (windows.count > 0) {
            firstWindow = windows.firstObject;
        }
    }
    
    return firstWindow;
}


- (UIWindow *)xxpk_currentWindow {
    
    UIWindow *currentWindow = nil;
    
    if (@available(iOS 13.0, *)) {
        NSSet<UIScene *> *connectedScenes = [UIApplication sharedApplication].connectedScenes;
        for (UIScene *scene in connectedScenes) {
            if (scene.activationState == UISceneActivationStateForegroundActive &&
                [scene isKindOfClass:[UIWindowScene class]]) {
                UIWindowScene *windowScene = (UIWindowScene *)scene;
                
                // iOS 15+ 使用 keyWindow 属性
                if (@available(iOS 15.0, *)) {
                    currentWindow = windowScene.keyWindow;
                }
                // iOS 13~14 遍历 windows 查找 keyWindow
                else {
                    for (UIWindow *window in windowScene.windows) {
                        if (window.isKeyWindow) {
                            currentWindow = window;
                            break;
                        }
                    }
                }
                break;
            }
        }
    } else {
        // iOS 12 及以下
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        currentWindow = [UIApplication sharedApplication].keyWindow;
#pragma clang diagnostic pop
    }
    
    // 备用方案：若仍为 nil，从全局 windows 中查找
    if (!currentWindow) {
        NSArray<UIWindow *> *windows = [UIApplication sharedApplication].windows;
        for (UIWindow *window in windows) {
            if (window.isKeyWindow) {
                currentWindow = window;
                break;
            }
        }
    }
    
    return currentWindow;
}

#pragma mark - 窗口管理核心逻辑
- (void)__xxpk_showNoStackWindowWithRootViewController:(UIViewController *)rootVC{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
            // 1. 创建新窗口
            UIWindow *newWindow = [self createWindowWithRootVC:rootVC];
            
            // 2. 设置窗口层级并显示
            [self configureWindowDisplay:newWindow];
            
            [self.windowsNoStack addObject:newWindow];
        } else {
            
            __weak typeof(self) weakSelf = self;
            // 1. 先声明 __block __weak 变量
            __block __weak id obs = nil;
            // 2. 给 obs 赋值（block 捕获的是 obs 本身）
            obs = [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidBecomeActiveNotification
                                                                       object:nil
                                                                        queue:[NSOperationQueue mainQueue]
                                                                   usingBlock:^(NSNotification *note) {
                // 先移除自己
                [[NSNotificationCenter defaultCenter] removeObserver:obs];
                [weakSelf __xxpk_showNoStackWindowWithRootViewController:rootVC];
            }];
        }
    });
}

- (void)xxpk_showWindowWithRootViewController:(UIViewController *)rootVC {
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
            [self xxpk_actuallyCreateWindowWithObject:rootVC];
        } else {
            
            __weak typeof(self) weakSelf = self;
            // 1. 先声明 __block __weak 变量
            __block __weak id obs = nil;
            // 2. 给 obs 赋值（block 捕获的是 obs 本身）
            obs = [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidBecomeActiveNotification
                                                                       object:nil
                                                                        queue:[NSOperationQueue mainQueue]
                                                                   usingBlock:^(NSNotification *note) {
                // 先移除自己
                [[NSNotificationCenter defaultCenter] removeObserver:obs];
                // 直接用捕获到的 view 调用
                [weakSelf xxpk_actuallyCreateWindowWithObject:rootVC];
            }];
        }
    });
}

- (void)xxpk_showWindowWithRootView:(UIView *)view {
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
            [self xxpk_actuallyCreateWindowWithObject:view];
        } else {
            
            __weak typeof(self) weakSelf = self;
            // 1. 先声明 __block __weak 变量
            __block __weak id obs = nil;
            // 2. 给 obs 赋值（block 捕获的是 obs 本身）
            obs = [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidBecomeActiveNotification
                                                                       object:nil
                                                                        queue:[NSOperationQueue mainQueue]
                                                                   usingBlock:^(NSNotification *note) {
                // 先移除自己
                [[NSNotificationCenter defaultCenter] removeObserver:obs];
                // 直接用捕获到的 view 调用
                [weakSelf xxpk_actuallyCreateWindowWithObject:view];
            }];
        }
    });
}

- (void)xxpk_actuallyCreateWindowWithObject:(id)object {
    UIViewController *rootVC = nil;
    
        // 0. 创建RootVC
    if ([object isKindOfClass:[UIViewController class]]) {
        rootVC = object;
    }
    
    if ([object isKindOfClass:[UIView class]]) {
        rootVC = [XXGOrientationViewController new];
        rootVC.view = object;
    }
    
    // 1. 创建新窗口
    UIWindow *newWindow = [self createWindowWithRootVC:rootVC];
    
    // 2. 设置窗口层级并显示
    [self configureWindowDisplay:newWindow];
    
    // 3. 压入窗口栈
    [self.windowsStack addObject:newWindow];
}

- (void)xxpk_onDidBecomeActiveOnce:(NSNotification *)note {
    // 注销自己，保证只执行一次
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIApplicationDidBecomeActiveNotification
                                                  object:nil];
    [self xxpk_showWindowWithRootView:note.object];
}

- (void)xxpk_dismissWindow {
    [self xxpk_dismissLastWindow];
}

- (void)xxpk_dismissLastWindow {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.windowsStack.count == 0) return;

        // 1. 获取并移除最后一个窗口
        UIWindow *lastWindow = [self.windowsStack lastObject];
        [self.windowsStack removeLastObject];

        // 2. 恢复宿主窗口状态
        if (lastWindow.isKeyWindow) {
            [self restoreHostKeyWindow];
        }

        // 3. 隐藏并销毁窗口
        lastWindow.hidden = YES;
        
        // 2. 强制移除所有子视图
        for (UIView *subview in [lastWindow.subviews copy]) {
            [subview removeFromSuperview];
        }
        
        // 3. 将窗口的根视图控制器设为nil
        lastWindow.rootViewController = nil;
        
        // 5. 强制刷新UI
        [CATransaction flush];
        
        // 6. 运行一个短暂的RunLoop，确保UI更新
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]];
    });
}

- (void)xxpk_dismissWindowWithRootViewController:(UIViewController *)rootViewController {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSEnumerator *reverseEnumerator = [self.windowsStack reverseObjectEnumerator];
        UIWindow *window = nil;
        
        // 逆向遍历防止数组突变
        while ((window = [reverseEnumerator nextObject])) {
            if (window.rootViewController == rootViewController) {
                // 处理关键窗口
                if (window.isKeyWindow) {
                    [self restoreHostKeyWindow];
                }
                
                // 执行移除操作
                window.hidden = YES;
                
                // 2. 强制移除所有子视图
                for (UIView *subview in [window.subviews copy]) {
                    [subview removeFromSuperview];
                }
                
                // 3. 将窗口的根视图控制器设为nil
                window.rootViewController = nil;
                
                [self.windowsStack removeObject:window];
                
                // 5. 强制刷新UI
                [CATransaction flush];
                
                // 6. 运行一个短暂的RunLoop，确保UI更新
                [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]];
                
                // 继续查找可能有多个相同 rootVC 的窗口
                reverseEnumerator = [self.windowsStack reverseObjectEnumerator];
            }
        }
    });
}

- (void)xxpk_dismissAllWindows {
    dispatch_async(dispatch_get_main_queue(), ^{
        // 逆向遍历避免快速枚举突变
        for (UIWindow *window in [self.windowsStack reverseObjectEnumerator]) {
            if (window.isKeyWindow) {
                [self restoreHostKeyWindow];
            }
            window.hidden = YES;
            
            // 2. 强制移除所有子视图
            for (UIView *subview in [window.subviews copy]) {
                [subview removeFromSuperview];
            }
            
            // 3. 将窗口的根视图控制器设为nil
            window.rootViewController = nil;
        }
        
        // 4. 清空窗口栈
        [self.windowsStack removeAllObjects];
        
        // 5. 强制刷新UI
        [CATransaction flush];
        
        // 6. 运行一个短暂的RunLoop，确保UI更新
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]];
    });
}

- (void)xxpk_dismissAllWindowsWithCompletion:(void(^)(void))completion {
    // 如果没有窗口，直接完成
    if (self.windowsStack.count == 0) {
        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion();
            });
        }
        return;
    }
    
    // 在主线程中执行
    dispatch_async(dispatch_get_main_queue(), ^{
        // 1. 先将所有窗口标记为隐藏
        NSArray *windowsToRemove = [self.windowsStack copy];
        for (UIWindow *window in windowsToRemove) {
            if (window.isKeyWindow) {
                [self restoreHostKeyWindow];
            }
            window.hidden = YES;
            
            // 2. 强制移除所有子视图
            for (UIView *subview in [window.subviews copy]) {
                [subview removeFromSuperview];
            }
            
            // 3. 将窗口的根视图控制器设为nil
            window.rootViewController = nil;
        }
        
        // 4. 清空窗口栈
        [self.windowsStack removeAllObjects];
        
        // 5. 强制刷新UI
        [CATransaction flush];
        
        // 6. 运行一个短暂的RunLoop，确保UI更新
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
        
        // 7. 使用GCD延迟确保所有操作完成
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (completion) {
                completion();
            }
        });
    });
}

#pragma mark - 窗口创建与配置
- (UIWindow *)createWindowWithRootVC:(UIViewController *)rootVC {
    UIWindow *window = nil;
    
    // 多场景适配（iOS13+）
    if (@available(iOS 13.0, *)) {
        for (UIScene *scene in [UIApplication sharedApplication].connectedScenes) {
            if (scene.activationState == UISceneActivationStateForegroundActive &&
                [scene isKindOfClass:[UIWindowScene class]]) {
                window = [[UIWindow alloc] initWithWindowScene:(UIWindowScene *)scene];
                break;
            }
        }
    }
    
    // 兜底创建方案
    if (!window) {
        window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    
    // 配置基础属性
    window.backgroundColor = [UIColor clearColor];
    window.rootViewController = rootVC;
    return window;
}

- (void)configureWindowDisplay:(UIWindow *)window {
    /* 窗口层级策略
     - 普通视图层：UIWindowLevelNormal（默认）
     - 状态栏层级：UIWindowLevelStatusBar（系统保留）
     - 警告框层级：UIWindowLevelAlert
     
     建议使用介于状态栏和警告框之间的层级，
     保证自定义窗口不会被系统组件覆盖
     */
    window.windowLevel = UIWindowLevelStatusBar + 100;
    [window makeKeyAndVisible];
}

#pragma mark - 宿主窗口管理
- (void)restoreHostKeyWindow {
    UIWindow *hostWindow = [self findHostKeyWindow];
    [hostWindow makeKeyWindow];
    if (!hostWindow.isKeyWindow) {
        [hostWindow becomeKeyWindow];
    }
}

- (UIWindow *)findHostKeyWindow {
    __block UIWindow *hostWindow = nil;
    
    // 多场景兼容方案
    if (@available(iOS 13.0, *)) {
        NSArray<UIWindowScene *> *windowScenes = [self activeWindowScenes];
        [windowScenes enumerateObjectsUsingBlock:^(UIWindowScene * _Nonnull scene, NSUInteger idx, BOOL * _Nonnull stop) {
            // 优先使用场景的keyWindow
            if (@available(iOS 15.0, *)) {
                hostWindow = scene.keyWindow;
            }
            // iOS13-14兼容方案
            if (!hostWindow) {
                hostWindow = [scene.windows firstObject];
            }
            if (hostWindow) *stop = YES;
        }];
    }
    // iOS12及以下
    else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        hostWindow = [UIApplication sharedApplication].keyWindow;
#pragma clang diagnostic pop
    }
    
    // 最终兜底方案
    if (!hostWindow) {
        hostWindow = [UIApplication sharedApplication].windows.firstObject;
    }
    
    return hostWindow;
}

- (NSArray<UIWindowScene *> *)activeWindowScenes {
    NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(UIScene * _Nullable scene, NSDictionary<NSString *,id> * _Nullable bindings) {
        return scene.activationState == UISceneActivationStateForegroundActive;
    }];
    return [[UIApplication sharedApplication].connectedScenes filteredSetUsingPredicate:predicate].allObjects;
}

#pragma mark - 辅助方法
- (UIWindow *)topWindow {
    return [self.windowsStack lastObject];
}

- (NSInteger)windowCount {
    return self.windowsStack.count;
}


@end
