#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <SafariServices/SafariServices.h>
#import <WebKit/WebKit.h>
#import <React/RCTViewUtils.h>
#import <FluentAdFlowWidgetSpec/FluentAdFlowWidgetSpec.h>
#import <React/RCTBridgeModule.h>
#import <ReactCommon/RCTTurboModule.h>
#import <FluentAdFlowAdsWidget/FluentAdFlowAdsWidget-Swift.h>

using namespace facebook;
using namespace react;

@interface FluentAdFlowModule : NSObject <NativeFluentAdFlowModuleSpec>
@end

@implementation FluentAdFlowModule {
  FluentAdFlowAdsSdk *_adsSdk;
}

RCT_EXPORT_MODULE();

- (instancetype)init {
  if (self = [super init]) {
    _adsSdk = [FluentAdFlowAdsSdk new];
  }
  return self;
}

- (std::shared_ptr<TurboModule>)getTurboModule:
    (const ObjCTurboModule::InitParams &)params
{
  return std::make_shared<NativeFluentAdFlowModuleSpecJSI>(params);
}

- (void)init:(NSString *)apiKey
       referrer:(NSString *)referrer
        resolve:(RCTPromiseResolveBlock)resolve
         reject:(RCTPromiseRejectBlock)reject
{
  if (!_adsSdk) {
    _adsSdk = [FluentAdFlowAdsSdk new];
  }

  [_adsSdk initSdk:apiKey
    withReferrer:referrer.length ? referrer : nil
    onInitializedSucceed:^{
      if (resolve) {
        resolve(nil); // Resolve with no data
      }
    } onInitializedFailure:^(NSInteger code, NSString * _Nonnull message) {
      if (reject) {
        reject([NSString stringWithFormat:@"%ld", (long)code],
              message ?: @"Unknown error",
              nil);
      }
    }
  ];
}

@end
