//
//  UnitAddToWalletButtonNativeView.m
//  UnitReactNativeComponents
//
//  Created by  Nogah Melamed on 10/03/2025.
//  Copyright © 2025 Facebook. All rights reserved.
//
#import "UnitAddToWalletButtonNativeView.h"

#ifdef RCT_NEW_ARCH_ENABLED

#import <Foundation/Foundation.h>
#import <PassKit/PassKit.h>
#import <UIKit/UIKit.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
#import <React/RCTFabricComponentsPlugins.h>
#import <react/renderer/components/RNUnitComponentsSdkViewSpec/ComponentDescriptors.h>
#import <react/renderer/components/view/ViewComponentDescriptor.h>


using namespace facebook::react;

@implementation UnitAddToWalletButtonNativeViewComponentView {
  PKAddPassButton *_addPassButton;
}

// Required class methods for Fabric component registration
+ (ComponentDescriptorProvider)componentDescriptorProvider
{
  return concreteComponentDescriptorProvider<UnitAddToWalletButtonNativeViewComponentDescriptor>();
}

+ (NSString *)moduleName
{
  return @"UnitAddToWalletButtonNativeView";
}

- (instancetype)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
    [self addSubview:self.addPassButton];
    [self centerAddPassButton:self.addPassButton];
  }
  return self;
}

- (void)centerAddPassButton:(PKAddPassButton *)addPassButton {
  addPassButton.translatesAutoresizingMaskIntoConstraints = NO;
  [NSLayoutConstraint activateConstraints:@[
    [addPassButton.leadingAnchor constraintEqualToAnchor:self.leadingAnchor],
    [addPassButton.trailingAnchor constraintEqualToAnchor:self.trailingAnchor],
    [addPassButton.topAnchor constraintEqualToAnchor:self.topAnchor],
    [addPassButton.bottomAnchor constraintEqualToAnchor:self.bottomAnchor]
  ]];
}

- (void)sendUpdate:(UITapGestureRecognizer *)sender {
  __weak __typeof__(self) weakSelf = self;
  __typeof__(self) strongSelf = weakSelf;

  std::dynamic_pointer_cast<const facebook::react::UnitAddToWalletButtonNativeViewEventEmitter>(strongSelf->_eventEmitter)->onAddToWalletClicked({});
}

- (PKAddPassButton *)addPassButton {
  if (!_addPassButton) {
    _addPassButton = [[PKAddPassButton alloc] initWithAddPassButtonStyle:PKAddPassButtonStyleBlack];
    [_addPassButton addTarget:self action:@selector(sendUpdate:) forControlEvents:UIControlEventTouchUpInside];
  }
  return _addPassButton;
}

@end

// Register component with Fabric system
Class<RCTComponentViewProtocol> UnitAddToWalletButtonNativeViewCls(void)
{
  return UnitAddToWalletButtonNativeViewComponentView.class;
}

#endif
