//
//  RewardedHandler.m
//  NexversePlugin
//
//  Created by Devesh Beniwal on 25/11/25.
//

#import "RewardedHandler.h"
#import "NexverseAdBridge.h"
@import Nexverse;

@interface RewardedHandler ()
@property (nonatomic, strong) RewardedAdUnit *rewardedView;

@end

@implementation RewardedHandler

- (void)load:(NSString *)configId
{
    self.rewardedView = [[RewardedAdUnit alloc] initWithConfigID:configId bidFloor:@0.1];

    // 2. Configure RewardedAdUnit
    self.rewardedView.delegate = self;
    self.rewardedView.redirectionType = RedirectionTypeExternalBrowser; // defaults to RedirectionTypeInternalBrowser

    // Set below properties to determine whether video controls are visibile or not.
    self.rewardedView.isPlaybackButtonVisible = YES;
    self.rewardedView.isMuteButtonVisible = YES;

    // 3. Load the interstitial ad
    [self.rewardedView loadAd];
}

- (void)show{
    if(self.rewardedView && self.rewardedView.isReady){
        UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
        [self.rewardedView showFrom:rootVC];
    }
}


// MARK: - RewardedAdUnitDelegate
- (void)rewardedAdDidReceiveAd:(RewardedAdUnit *)rewardedAd {
    // Show rewardedAd from a viewController
    [[NexverseAdBridge sharedInstance] sendEvent:@"RewardAdLoaded" data:@""];
}

- (void)rewardedAd:(RewardedAdUnit *)rewardedAd didFailToReceiveAdWithError:(NSError *)error {
    // Handle ad load failure
    [[NexverseAdBridge sharedInstance] sendEvent:@"RewardAdFailed" data:error.description];
}

- (void)rewardedAd:(RewardedAdUnit *)rewardedAd didFailToShowAdWithError:(NSError *)error {
    // Handle ad show failure
    [[NexverseAdBridge sharedInstance] sendEvent:@"RewardAdShowError" data:error.description];
}

- (void)rewardedAdUserDidEarnReward:(RewardedAdUnit *)rewardedAd reward:(NexverseReward *)reward {
    // Handle reward distribution
    NSDictionary *rewardDict = @{
        @"type": reward.type ? reward.type : @"",
        @"ext": reward.ext ? reward.ext : @"",
        @"count": (reward.count)
    };
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:rewardDict options:0 error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    [[NexverseAdBridge sharedInstance] sendEvent:@"RewardAdReward" data:jsonString];
}

- (void)rewardedAdWillPresentAd:(RewardedAdUnit *)rewardedAd {
    // Handle ad presentation
    [[NexverseAdBridge sharedInstance] sendEvent:@"RewardAdDisplayed" data:@""];
}

- (void)rewardedAdDidDismissAd:(RewardedAdUnit *)rewardedAd {
    // Handle ad dismissal
    [[NexverseAdBridge sharedInstance] sendEvent:@"RewardAdClosed" data:@""];
}

- (void)rewardedAdWillLeaveApplication:(RewardedAdUnit *)rewardedAd {
    // Handle app leaving foreground
}

- (void)rewardedAdDidClickAd:(RewardedAdUnit *)rewardedAd {
    // Handle ad click
    [[NexverseAdBridge sharedInstance] sendEvent:@"RewardAdClicked" data:@""];
}
@end
