//
//  TBLRNTClassicPageDelegate.m
//  TaboolaReactNativePlugin4x
//
//  Created by Daniel Frimet on 11/05/2025.
//

#import "TBLRNTClassicPageDelegate.h"
#import "TBLRNTConstants.h"
#import "TBLRNTClassicUnit.h"

@implementation TBLRNTClassicPageDelegate

- (instancetype)init {
  self = [super init];

  return self;
}

#pragma mark - TBLClassicPageDelegate

/**
 * Controls the SDK behavior for handling click URLs.
 *
 * @discussion
 * Allows publishers to customize how click events are processed:
 *
 * - When `shouldTaboolaHandleOrganicClicks` is `YES`:
 *   - SDK automatically handles opening click URLs for non-organic content
 *   - Recommended for default, seamless user experience
 *
 * - When `shouldTaboolaHandleOrganicClicks` is `NO`:
 *   - SDK prevents automatic URL handling
 *   - Gives publishers full control over click event processing
 *   - Useful for custom navigation or analytics tracking
 *
 * @note Publishers can set this property during unit creation via the build function
 *
 * @example
 * // SDK handles non-organic click URLs
 * [classicPage build:placement mode:mode shouldTaboolaHandleOrganicClicks:YES]
 *
 * // Publisher handles all click URL processing
 * [classicPage build:placement mode:mode shouldTaboolaHandleOrganicClicks:NO]
 *
 *  We are adding unitId to every callback because the RN EventEmitter emits to all JS observers.
 *  If we have more than 2 Units on the same screen, both of their callbacks will be invoked.
 *  Once events are received on the JS side, we filter them by comparing the event unit id.
 *  If it doesn't match, we ignore this event.
 *  for ref see on JS code: TBLRNClassicUnitEventHandler.ts
 */
- (BOOL)classicUnit:(TBLRNTClassicUnit *)classicUnit
didClickPlacementName:(NSString *)placementName
             itemId:(NSString *)itemId
           clickUrl:(NSString *)clickUrl
          isOrganic:(BOOL)organic
         customData:(NSDictionary *)customData {
  if (self.onItemClickCallback) {
    NSDictionary *params = @{
      kPlacementKey : placementName ?: kPlacementNameNotFoundErrorMsg,
      kUnitIdKey : [classicUnit getUnitHashCode],
      kItemIdKey : itemId ?: @"",
      kClickUrlKey : clickUrl ?: @"",
      kIsOrganicKey : @(organic)
    };

    if (customData) {
      NSMutableDictionary *mutableParams = [params mutableCopy];
      [mutableParams setObject:customData forKey:kCustomDataKey];
      params = [mutableParams copy];
    }

    self.onItemClickCallback(params);
  } else {
    NSLog(@"[TBLRNTClassicPageDelegate] onItemClickCallback is nil");
  }
  return [classicUnit shouldTaboolaHandleOrganicClicks];
}

- (void)classicUnit:(TBLRNTClassicUnit *)classicUnit
didLoadOrResizePlacementName:(NSString *)placementName
             height:(CGFloat)height
      placementType:(PlacementType)placementType {
  if (self.onResizeCallback) {
    self.onResizeCallback(@{
      kHeightKey : @(height),
      kUnitIdKey : [classicUnit getUnitHashCode]
    });
  } else {
    NSLog(@"[TBLRNTClassicPageDelegate] onResizeCallback is nil");
  }
}

- (void)adDidReceiveSuccess:(TBLRNTClassicUnit *)classicUnit {
  if (self.onAdReceiveSuccessCallback) {

    self.onAdReceiveSuccessCallback(@{kUnitIdKey : [classicUnit getUnitHashCode]});
  } else {
    NSLog(@"[TBLRNTClassicPageDelegate] onAdReceiveSuccessCallback is nil");
  }
}

- (void)classicUnit:(TBLRNTClassicUnit *)classicUnit
didFailToLoadPlacementName:(NSString *)placementName
       errorMessage:(NSString *)error {
  if (self.onAdReceiveFailCallback) {
    self.onAdReceiveFailCallback(@{
      kUnitIdKey : [classicUnit getUnitHashCode],
      kErrorKey : error ?: kInvalidErrorMessageMsg
    });
  } else {
    NSLog(@"[TBLRNTClassicPageDelegate] onAdReceiveFailCallback is nil");
  }
}

- (void)updateContentDidComplete:(TBLRNTClassicUnit *)classicUnit {
  if (self.onUpdateContentCompletedCallback) {
    self.onUpdateContentCompletedCallback(
                                          @{kUnitIdKey : [classicUnit getUnitHashCode]});
  } else {
    NSLog(
          @"[TBLRNTClassicPageDelegate] onUpdateContentCompletedCallback is nil");
  }
}

- (void)scrollViewDidScrollToTopClassicUnit:(TBLRNTClassicUnit *)classicUnit {
  if (self.onTaboolaWidgetOnTopCallback) {
    self.onTaboolaWidgetOnTopCallback(
                                      @{kUnitIdKey : [classicUnit getUnitHashCode]});

  } else {
    NSLog(@"[TBLRNTClassicPageDelegate] onTaboolaWidgetOnTopCallback is nil");
  }
}

// General event handler
- (void)classicUnit:(TBLRNTClassicUnit *)classicUnit
            onEvent:(ReportActionType)actionType
               data:(NSDictionary *)data {
  if (self.onEventCallback) {
    self.onEventCallback(@{
      kActionTypeKey : @(actionType),
      kUnitIdKey : [classicUnit getUnitHashCode]});
  } else {
    NSLog(@"[TBLRNTClassicPageDelegate] onEventCallback is nil");
  }
}

@end
