#import "FGPrefix.h"
#import "FGSpoofer.h"
#import "FGStore.h"
#import "FGFloatingButton.h"
#import "FGRootViewController.h"
#import "FGAppBridge.h"
#import "FGToast.h"

/// Quan sát vòng đời ứng dụng chủ để giữ nút nổi và trạng thái luôn đúng.
@interface FGEntryObserver : NSObject
@property (nonatomic, assign) BOOL didAutoOpen;
@end

@implementation FGEntryObserver

+ (instancetype)shared {
    static FGEntryObserver *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[FGEntryObserver alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self
                   selector:@selector(appDidBecomeActive:)
                       name:UIApplicationDidBecomeActiveNotification
                     object:nil];
        [center addObserver:self
                   selector:@selector(floatingSettingChanged:)
                       name:FGFloatingButtonSettingChangedNotification
                     object:nil];
        [center addObserver:self
                   selector:@selector(storeChanged:)
                       name:FGStoreDidChangeNotification
                     object:nil];
    }
    return self;
}

- (void)appDidBecomeActive:(NSNotification *)note {
    [[FGFloatingButton shared] install];

    if ([FGStore isEnabled] && [FGStore hasCoordinate]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)),
                       dispatch_get_main_queue(), ^{
            UIWindow *window = [FGAppBridge keyWindow];
            [FGToast show:@"FakeGPS: đang giả lập vị trí" inView:window];
        });
    }
}

- (void)floatingSettingChanged:(NSNotification *)note {
    [[FGFloatingButton shared] refresh];
}

- (void)storeChanged:(NSNotification *)note {
    // Không làm gì nặng ở đây; chỉ đồng bộ nút nổi khi cần.
}

@end

__attribute__((constructor))
static void FGEntryInitialize(void) {
    @autoreleasepool {
        // Không chạy trong app extension (bị cấm truy cập UIApplication).
        NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
        if ([bundlePath hasSuffix:@".appex"]) {
            return;
        }
        if ([FGAppBridge isRunningInExtension]) {
            return;
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            [[FGSpoofer shared] installHooks];
            [[FGSpoofer shared] start];
            [FGEntryObserver shared];
            [[FGFloatingButton shared] install];

            // Nếu người dùng tắt nút nổi, mở panel một lần mỗi phiên để vẫn
            // truy cập được các tính năng.
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)),
                           dispatch_get_main_queue(), ^{
                FGEntryObserver *observer = [FGEntryObserver shared];
                if (observer.didAutoOpen) return;
                observer.didAutoOpen = YES;
                if (![FGStore floatingButtonEnabled]) {
                    [[FGFloatingButton shared] openPanel];
                }
            });

            FGLog(@"FakeGPS Reborn đã nạp vào %@", [[NSBundle mainBundle] bundleIdentifier]);
        });
    }
}
