#import "TQWKConfigurationFactory.h"
#import "TQWebViewShared.h"
#import "TQWebView.h"

@implementation TQWKConfigurationFactory

+ (WKWebViewConfiguration *)makeConfiguration:(TQWebViewConfig *)config {
    return [self makeConfigurationWithInjectUserAgent:config.injectUserAgent
                                      userAgentExtra:config.userAgentExtra];
}

+ (WKWebViewConfiguration *)makeConfigurationWithInjectUserAgent:(BOOL)injectUserAgent
                                                 userAgentExtra:(NSString *)userAgentExtra {
    WKWebViewConfiguration *conf = [[WKWebViewConfiguration alloc] init];
    conf.processPool = [TQWebViewShared processPool];
    conf.allowsInlineMediaPlayback = YES;
    conf.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;

    // JS 默认启用（版本自适应）
    // iOS 14+: WKWebpagePreferences.allowsContentJavaScript（推荐路径）
    // iOS 11-13: preferences.javaScriptEnabled（旧 API）
    if (@available(iOS 14.0, *)) {
        WKWebpagePreferences *prefs = [[WKWebpagePreferences alloc] init];
        prefs.allowsContentJavaScript = YES;
        conf.defaultWebpagePreferences = prefs;
    } else {
        conf.preferences.javaScriptEnabled = YES;
    }

    // 默认数据存储(共享 cookie)
    conf.websiteDataStore = [WKWebsiteDataStore defaultDataStore];

    // UA 注入:必须在 WKWebView 创建之前设置在 configuration 上,
    // 因为 WKWebView.configuration 返回的是 copy,创建后再修改不生效。
    if (injectUserAgent) {
        NSString *segment = [NSString stringWithFormat:@"qianwv/%@", [TQWebView sdkVersion]];
        NSString *extra = [userAgentExtra stringByTrimmingCharactersInSet:
                           [NSCharacterSet whitespaceCharacterSet]];
        if (extra.length > 0) {
            segment = [NSString stringWithFormat:@"%@ %@", segment, extra];
        }
        conf.applicationNameForUserAgent = segment;
    }

    return conf;
}

@end
