#import "TQWebViewController.h"
#import "TQWebViewConfigurator.h"
#import "TQWKConfigurationFactory.h"
#import "TQL10n.h"
#import <WebKit/WebKit.h>

#pragma mark - UIColor 兼容（iOS 11-12 回退静态颜色）

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

@interface TQWebViewController ()
@property (nonatomic, copy, readwrite) NSString *url;
@property (nonatomic, copy, readwrite) TQWebViewConfig *config;
@property (nonatomic, strong, readwrite) TQSignCallbacks *callbacks;

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIView *topBar;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, strong) UIProgressView *progressBar;

@property (nonatomic, strong, nullable) TQWebViewHandle *handle;
@property (nonatomic, assign) BOOL kvoRegistered;
@end

static void *kTQProgressContext = &kTQProgressContext;

@implementation TQWebViewController

- (instancetype)initWithUrl:(NSString *)url
                     config:(TQWebViewConfig *)config
                  callbacks:(TQSignCallbacks *)callbacks {
    if (self = [super initWithNibName:nil bundle:nil]) {
        _url = [url copy];
        _config = [config copy];
        _callbacks = callbacks;
        // 页面容器每次新建独立 WKWebView（不复用预热实例）。
        // 原因：iOS WKWebView 无 clear-history API，复用加载过 warmup.html 的预热实例会导致
        // warmup.html 残留在 backForwardList 中（返回键退回 warmup 页）且无法清除。
        // 预热收益仍通过共享 WKProcessPool（进程复用）+ 共享 defaultDataStore（磁盘缓存跨实例命中）承接。
        WKWebViewConfiguration *webViewConfig = [TQWKConfigurationFactory makeConfiguration:_config];
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:webViewConfig];
        self.modalPresentationStyle = UIModalPresentationFullScreen;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = TQColorBackground();
    [self setupTopBar];
    [self setupWebView];
    [self setupProgressBar];

    // 复用 Configurator 注入逻辑(避免重复)
    __weak __typeof(self) weakSelf = self;
    TQSignCallbacks *bridged = [TQSignCallbacks callbacksWithOnSignResult:^(TQSignResult *result) {
        __strong __typeof(weakSelf) self = weakSelf;
        if (!self) return;
        if (self.callbacks.onSignResult) self.callbacks.onSignResult(result);
        // 协议回调到达后,容器自动关闭
        [self dismissSelfAnimated:YES];
    } onEvent:^(id<TQSdkEvent> event) {
        __strong __typeof(weakSelf) self = weakSelf;
        if (!self) return;
        [self handleEvent:event];
        if (self.callbacks.onEvent) self.callbacks.onEvent(event);
    }];
    self.handle = [TQWebViewConfigurator applyToWebView:self.webView
                                          hostController:self
                                                  config:self.config
                                               callbacks:bridged];

    NSURL *u = [NSURL URLWithString:self.url];
    if (u) {
        [self.handle loadURL:u];
    } else {
        // 非法 URL 直接关
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    switch (self.config.statusBarStyle) {
        case TQStatusBarStyleLightContent: return UIStatusBarStyleLightContent;
        case TQStatusBarStyleDarkContent:
            if (@available(iOS 13.0, *)) { return UIStatusBarStyleDarkContent; }
            return UIStatusBarStyleDefault;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 注意:不在此处移除进度 KVO。
    // 原因:iOS 交互式 pop 手势(从左边缘滑动)开始时就会触发 viewWillDisappear,
    // 如果用户取消手势(滑到一半松手),页面回来后 KVO 已失效,进度条不再更新。
    // KVO 的清理统一在 dealloc 中执行。
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.handle attemptBlankRecoveryIfNeeded];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    // 仅页面真正离开时销毁，系统模态覆盖时不销毁
    if (self.isBeingDismissed || self.isMovingFromParentViewController) {
        [self.handle detachAndDestroy];
        self.handle = nil;
    }
}

- (void)dealloc {
    if (_kvoRegistered) {
        @try {
            [_webView removeObserver:self forKeyPath:@"estimatedProgress" context:kTQProgressContext];
        } @catch (__unused NSException *e) {}
        _kvoRegistered = NO;
    }
}

#pragma mark - UI 搭建

- (void)setupTopBar {
    UIView *bar = [[UIView alloc] init];
    bar.backgroundColor = self.config.topBarBackgroundColor ?: TQColorBackground();
    bar.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:bar];
    self.topBar = bar;

    UILabel *title = [[UILabel alloc] init];
    title.text = self.config.topBarTitle.length == 0 ? [TQL10n defaultTitle] : self.config.topBarTitle;
    title.textColor = self.config.topBarTextColor ?: TQColorLabel();
    title.font = [UIFont systemFontOfSize:17 weight:UIFontWeightSemibold];
    title.textAlignment = NSTextAlignmentCenter;
    title.translatesAutoresizingMaskIntoConstraints = NO;
    [bar addSubview:title];
    self.titleLabel = title;

    UIButton *back = [UIButton buttonWithType:UIButtonTypeSystem];
    if (@available(iOS 13.0, *)) {
        [back setImage:[UIImage systemImageNamed:@"chevron.left"] forState:UIControlStateNormal];
    } else {
        [back setTitle:@"‹" forState:UIControlStateNormal];
        back.titleLabel.font = [UIFont systemFontOfSize:28];
    }
    back.tintColor = self.config.topBarTextColor ?: TQColorLabel();
    [back addTarget:self action:@selector(onBack) forControlEvents:UIControlEventTouchUpInside];
    back.translatesAutoresizingMaskIntoConstraints = NO;
    [bar addSubview:back];
    self.backButton = back;

    UIButton *close = [UIButton buttonWithType:UIButtonTypeSystem];
    if (@available(iOS 13.0, *)) {
        [close setImage:[UIImage systemImageNamed:@"xmark"] forState:UIControlStateNormal];
    } else {
        [close setTitle:@"✕" forState:UIControlStateNormal];
        close.titleLabel.font = [UIFont systemFontOfSize:20];
    }
    close.tintColor = self.config.topBarTextColor ?: TQColorLabel();
    close.hidden = !self.config.showCloseButton;
    [close addTarget:self action:@selector(onClose) forControlEvents:UIControlEventTouchUpInside];
    close.translatesAutoresizingMaskIntoConstraints = NO;
    [bar addSubview:close];
    self.closeButton = close;

    bar.hidden = !self.config.showTopBar;

    [NSLayoutConstraint activateConstraints:@[
        [bar.topAnchor      constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
        [bar.leadingAnchor  constraintEqualToAnchor:self.view.leadingAnchor],
        [bar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [bar.heightAnchor   constraintEqualToConstant:44],

        [back.leadingAnchor constraintEqualToAnchor:bar.leadingAnchor constant:8],
        [back.centerYAnchor constraintEqualToAnchor:bar.centerYAnchor],
        [back.widthAnchor   constraintEqualToConstant:44],
        [back.heightAnchor  constraintEqualToConstant:44],

        [close.trailingAnchor constraintEqualToAnchor:bar.trailingAnchor constant:-8],
        [close.centerYAnchor  constraintEqualToAnchor:bar.centerYAnchor],
        [close.widthAnchor    constraintEqualToConstant:44],
        [close.heightAnchor   constraintEqualToConstant:44],

        [title.leadingAnchor  constraintEqualToAnchor:back.trailingAnchor constant:8],
        [title.trailingAnchor constraintEqualToAnchor:close.leadingAnchor constant:-8],
        [title.centerYAnchor  constraintEqualToAnchor:bar.centerYAnchor],
    ]];
}

- (void)setupWebView {
    self.webView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.webView];

    NSLayoutYAxisAnchor *topAnchor = self.config.showTopBar
        ? self.topBar.bottomAnchor
        : self.view.safeAreaLayoutGuide.topAnchor;
    [NSLayoutConstraint activateConstraints:@[
        [self.webView.topAnchor      constraintEqualToAnchor:topAnchor],
        [self.webView.leadingAnchor  constraintEqualToAnchor:self.view.leadingAnchor],
        [self.webView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.webView.bottomAnchor   constraintEqualToAnchor:self.view.bottomAnchor],
    ]];
}

- (void)setupProgressBar {
    UIProgressView *pb = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    pb.translatesAutoresizingMaskIntoConstraints = NO;
    pb.alpha = 0;
    [self.view addSubview:pb];
    self.progressBar = pb;

    NSLayoutYAxisAnchor *topAnchor = self.config.showTopBar
        ? self.topBar.bottomAnchor
        : self.view.safeAreaLayoutGuide.topAnchor;
    [NSLayoutConstraint activateConstraints:@[
        [pb.topAnchor      constraintEqualToAnchor:topAnchor],
        [pb.leadingAnchor  constraintEqualToAnchor:self.view.leadingAnchor],
        [pb.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [pb.heightAnchor   constraintEqualToConstant:2],
    ]];

    [self.webView addObserver:self
                   forKeyPath:@"estimatedProgress"
                      options:NSKeyValueObservingOptionNew
                      context:kTQProgressContext];
    self.kvoRegistered = YES;
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                       context:(void *)context {
    if (context == kTQProgressContext && [keyPath isEqualToString:@"estimatedProgress"]) {
        double progress = self.webView.estimatedProgress;
        self.progressBar.progress = (float)progress;
        [UIView animateWithDuration:0.2 animations:^{
            self.progressBar.alpha = progress >= 1.0 ? 0 : 1;
        }];
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - 顶栏按钮

- (void)onBack {
    if (self.webView.canGoBack) {
        [self.webView goBack];
    } else {
        [self attemptCloseWithConfirm];
    }
}

- (void)onClose {
    [self attemptCloseWithConfirm];
}

- (void)attemptCloseWithConfirm {
    if (!self.config.confirmBeforeClose) {
        [self dismissSelfAnimated:YES];
        return;
    }
    NSString *title = self.config.confirmCloseTitle.length > 0
        ? self.config.confirmCloseTitle
        : [TQL10n confirmCloseTitle];
    NSString *message = self.config.confirmCloseMessage.length > 0
        ? self.config.confirmCloseMessage
        : [TQL10n confirmCloseMessage];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:[TQL10n confirmStay]
                                              style:UIAlertActionStyleCancel
                                            handler:nil]];
    __weak __typeof(self) weakSelf = self;
    [alert addAction:[UIAlertAction actionWithTitle:[TQL10n confirmLeave]
                                              style:UIAlertActionStyleDestructive
                                            handler:^(UIAlertAction *_) {
        [weakSelf dismissSelfAnimated:YES];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)dismissSelfAnimated:(BOOL)animated {
    UINavigationController *nav = self.navigationController;
    if (nav && nav.viewControllers.firstObject != self) {
        [nav popViewControllerAnimated:animated];
    } else {
        [self dismissViewControllerAnimated:animated completion:nil];
    }
}

- (void)handleEvent:(id<TQSdkEvent>)event {
    // 容器内部观察:进度条已由 KVO 处理,此处保留扩展点
    (void)event;
}

@end
