//
//  NexverseAdBridge.mm
//  NexversePlugin
//
//  Created by Devesh Beniwal on 21/11/25.
//

#import "NexverseAdBridge.h"
#import "BannerHandler.h"
#import "InterstitialHandler.h"
#include "RewardedHandler.h"
#include "platform/apple/JsbBridgeWrapper.h"
@import Nexverse;

@interface NexverseAdBridge ()
@property (nonatomic, strong) BannerHandler *bannerHandler;
@property (nonatomic, strong) InterstitialHandler *interstitialHandler;
@property (nonatomic, strong) RewardedHandler *rewardedHandler;
@end

@implementation NexverseAdBridge

static void RunOnMain(dispatch_block_t block)
{
    if ([NSThread isMainThread]) block();
    else dispatch_async(dispatch_get_main_queue(), block);
}

+ (instancetype)sharedInstance {
    static NexverseAdBridge *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (void)setupBridge
{
    JsbBridgeWrapper *bridge = [JsbBridgeWrapper sharedInstance];
    [bridge addScriptEventListener:@"InitSDK" listener:^(NSString *data) {
        [[NexverseAdBridge sharedInstance] InitSDK:data];
    }];
    [bridge addScriptEventListener:@"createBanner" listener:^(NSString *data) {
        [[NexverseAdBridge sharedInstance] createBanner:data];
    }];
    [bridge addScriptEventListener:@"destroyBanner" listener:^(NSString *data) {
        [[NexverseAdBridge sharedInstance] destroyBanner];
    }];
    [bridge addScriptEventListener:@"loadInterstitial" listener:^(NSString *data) {
        [[NexverseAdBridge sharedInstance] loadInterstitial:data];
    }];
    [bridge addScriptEventListener:@"showInterstitial" listener:^(NSString *data) {
        [[NexverseAdBridge sharedInstance] showInterstitial];
    }];
    [bridge addScriptEventListener:@"loadRewarded" listener:^(NSString *data) {
        [[NexverseAdBridge sharedInstance] loadRewarded:data];
    }];
    [bridge addScriptEventListener:@"showRewarded" listener:^(NSString *data) {
        [[NexverseAdBridge sharedInstance] showRewarded];
    }];
    [bridge addScriptEventListener:@"setTestMode" listener:^(NSString *data) {
        [[NexverseAdBridge sharedInstance] setTestMode:[data boolValue]];
    }];
    [bridge addScriptEventListener:@"shareGeoLocation" listener:^(NSString *data) {
        [[NexverseAdBridge sharedInstance] shareGeoLocation:[data boolValue]];
    }];
    [bridge addScriptEventListener:@"setGlobalOrtbConfig" listener:^(NSString *data) {
        [[NexverseAdBridge sharedInstance] setGlobalOrtbConfig:data];
    }];
    [bridge addScriptEventListener:@"setGDPRConsentString" listener:^(NSString *data) {
        [[NexverseAdBridge sharedInstance] setGDPRConsentString:data];
    }];
    [bridge addScriptEventListener:@"setSubjectToGDPR" listener:^(NSString *data) {
        [[NexverseAdBridge sharedInstance] setSubjectToGDPR:data];
    }];
    [bridge addScriptEventListener:@"setSubjectToCOPPA" listener:^(NSString *data) {
        [[NexverseAdBridge sharedInstance] setSubjectToCOPPA:[data boolValue]];
    }];
    
    NSLog(@"[NexverseAdBridge] JSB callback registered.");
}

- (void)sendEvent:(NSString *)eventName data:(NSString *)data
{
    RunOnMain(^{
        NSLog(@"[NexverseAdBridge] Sending: %@ Data: %@", eventName, data);
        JsbBridgeWrapper *bridge = [JsbBridgeWrapper sharedInstance];
        [bridge dispatchEventToScript:eventName arg:data];
    });
}


- (void)InitSDK:(NSString *)data
{
    // Parse JSON string
    NSData *jsondata = [data dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsondata options:0 error:nil];

    int account_id = [json[@"accountId"] intValue];
    int app_id = [json[@"appId"] intValue];

    InitConfig* config = [[InitConfig alloc] initWithNexverseAccountId:account_id nexverseAppId:app_id];
    [NexverseAdManager initialise:config
                                 :^(enum NexverseInitializationStatus status,
                                     NSError * _Nullable error) {
        switch (status) {
            case NexverseInitializationStatusSucceeded:
                NSLog(@"[NexverseAdBridge] Success");
                [self sendEvent:@"OnSdkInitialized" data:@""];
                break;
            case NexverseInitializationStatusServerStatusWarning:
                NSLog(@"[NexverseAdBridge] Warning %@", error.description);
                [self sendEvent:@"OnSdkInitializedWithWarning" data:error.description];
                break;
            case NexverseInitializationStatusFailed:
            default:
                NSLog(@"[NexverseAdBridge] Failed %@", error.description);
                [self sendEvent:@"OnSdkFailed" data:error.description];
                break;
        }
    }];
}




- (void)createBanner:(NSString *)data {
    // Parse JSON string
    NSData *jsondata = [data dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsondata options:0 error:nil];
    
    [self destroyBanner];
    
    NSString *configId = json[@"configId"];
    int width = [json[@"widthPx"] intValue];
    int height = [json[@"heightPx"] intValue];
    int placement = [json[@"gravity"] intValue];
    int autoRefresh = [json[@"autoRefreshSec"] intValue];
    BOOL video = [json[@"video"] boolValue];
    
    self.bannerHandler = [[BannerHandler alloc] init];
    [self.bannerHandler load:configId width:320 height:50 placement:placement autoRefresh:autoRefresh video:video];
}

- (void)destroyBanner {
    if (self.bannerHandler) {
        [self.bannerHandler destroy];
    }
}




- (void)loadInterstitial:(NSString *)data {
    // Parse JSON string
    NSData *jsondata = [data dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsondata options:0 error:nil];
    
    NSString *configId = json[@"configId"];
    int format = [json[@"format"] intValue];
    
    self.interstitialHandler = [[InterstitialHandler alloc] init];
    [self.interstitialHandler load:configId format:format];
}

- (void)showInterstitial {
    if (self.interstitialHandler) {
        [self.interstitialHandler show];
    }
}




- (void)loadRewarded:(NSString *)data {
    // Parse JSON string
    NSData *jsondata = [data dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsondata options:0 error:nil];
    
    NSString *configId = json[@"configId"];
  
    self.rewardedHandler = [[RewardedHandler alloc] init];
    [self.rewardedHandler load:configId];
}

- (void)showRewarded {
    if (self.rewardedHandler) {
        [self.rewardedHandler show];
    }
}





- (void)setGDPRConsentString:(NSString *)value {
    [[Targeting shared] setGdprConsentString:value];
}

- (void)setGlobalOrtbConfig:(NSString *)value {
    [[Targeting shared] setGlobalORTBConfig:value];
}

- (void)setSubjectToCOPPA:(Boolean)value {
    [[Targeting shared] setCoppa:value ? @1 : @0];
}

- (void)setSubjectToGDPR:(Boolean *)value {
    [[Targeting shared] setSubjectToGDPR:value ? @1 : @0];
}

- (void)setTestMode:(Boolean)value {
    [NexverseAdManager setIsTestMode:value];
}

- (void)shareGeoLocation:(Boolean)value {
    [NexverseAdManager setShareGeoLocation:value];
}

@end
