#import "ConfiguratorDemoViewController.h"
#import <WebKit/WebKit.h>

static UIColor *DemoBackground(void) {
    if (@available(iOS 13.0, *)) { return [UIColor systemBackgroundColor]; }
    return [UIColor whiteColor];
}

@interface ConfiguratorDemoViewController ()
@property (nonatomic, copy) NSString *urlString;
@property (nonatomic, strong) TQSignCallbacks *callbacks;
@property (nonatomic, strong) TQWebViewConfig *config;
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong, nullable) TQWebViewHandle *handle;
@end

@implementation ConfiguratorDemoViewController

- (instancetype)initWithUrl:(NSString *)url callbacks:(TQSignCallbacks *)callbacks {
    if (self = [super initWithNibName:nil bundle:nil]) {
        _urlString = [url copy];
        _callbacks = callbacks;
        TQWebViewConfig *cfg = [TQWebViewConfig defaultConfig];
        cfg.userAgentExtra = @"qianwv-demo/1.0.0(configurator)";
        _config = cfg;
        WKWebViewConfiguration *webViewConfig = [TQWKConfigurationFactory makeConfiguration:cfg];
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:webViewConfig];
        self.title = @"配置模式 Demo";
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = DemoBackground();

    self.webView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.webView];
    [NSLayoutConstraint activateConstraints:@[
        [self.webView.topAnchor      constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
        [self.webView.leadingAnchor  constraintEqualToAnchor:self.view.leadingAnchor],
        [self.webView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.webView.bottomAnchor   constraintEqualToAnchor:self.view.bottomAnchor],
    ]];

    self.navigationItem.leftBarButtonItem =
        [[UIBarButtonItem alloc] initWithTitle:@"关闭"
                                          style:UIBarButtonItemStylePlain
                                         target:self
                                         action:@selector(onClose)];

    self.handle = [TQWebViewConfigurator applyToWebView:self.webView
                                          hostController:self
                                                  config:self.config
                                               callbacks:self.callbacks];
    NSURL *url = [NSURL URLWithString:self.urlString];
    if (url) {
        [self.handle loadURL:url];
    }
}

- (void)onClose {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    // 提前在主线程清理 WebView 资源,避免 dealloc 可能在非主线程执行 UIKit 操作。
    [self.handle detachAndDestroy];
    self.handle = nil;
}

@end
