#import "LLWebViewManager.h"
#import <WebKit/WebKit.h>
#import "LLWebView.h"
@import Localytics;

@interface LLWebViewManager() <LLCampaignUpdated>

@property (nonatomic, strong) LLMarketingWebViewHandler *webViewHandler;

@end

@implementation LLWebViewManager

RCT_EXPORT_MODULE()

- (UIView *)view {
    _webViewHandler = [Localytics marketingWebViewHandler];
    LLWebView *webView = [[LLWebView alloc] initWithMarketingHandler:self.webViewHandler andCampaignUpdatedBlock:self];
    webView.translatesAutoresizingMaskIntoConstraints = NO;
    webView.navigationDelegate = self.webViewHandler;
    webView.UIDelegate = self.webViewHandler;
    self.webViewHandler.webView = webView;
    return webView;
}

- (void)campaignUpdated {
    // Idempotent: drop any prior registration before adding a new one so we never
    // end up with multiple observers calling -dismiss on a single resign-active.
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIApplicationWillResignActiveNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(dismiss)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:nil];
}

RCT_EXPORT_VIEW_PROPERTY(campaign, NSInteger)

RCT_EXPORT_METHOD(dismiss) {
    [self.webViewHandler tagMarketingDismissAction];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIApplicationWillResignActiveNotification
                                                  object:nil];
    // Drop the manager-side strong reference so the previous handler / WebView
    // can deallocate even if the JS dispatch races the view drop.
    self.webViewHandler = nil;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
