import UIKit
import WebKit
import TencentQianWebView

/// 配置模式 Demo(纯 Swift 消费 OC SDK)。
///
/// - 自带一个空 WKWebView
/// - viewDidLoad 调 OC `TQWebViewConfigurator.apply(...)` 套用 SDK 全部能力
/// - 然后 `handle.load(url)` 加载传入的 URL
final class ConfiguratorDemoViewController: UIViewController {

    private let urlString: String
    private let callbacks: TQSignCallbacks
    private let config: TQWebViewConfig
    private let webView: WKWebView
    private var handle: TQWebViewHandle?

    init(url: String, callbacks: TQSignCallbacks) {
        self.urlString = url
        self.callbacks = callbacks
        // OC: `+defaultConfig` → Swift(实测): `default()`
        let config = TQWebViewConfig.default()
        config.userAgentExtra = "qianwv-demo-swift/1.0.0(configurator)"
        // OC: `+makeConfiguration:` → Swift(实测): `makeConfiguration(_:)`(首参无标签)
        let webViewConfig = TQWKConfigurationFactory.makeConfiguration(config)
        self.config = config
        self.webView = WKWebView(frame: .zero, configuration: webViewConfig)
        super.init(nibName: nil, bundle: nil)
        title = "配置模式 Demo"
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("not supported")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = DemoCompat.background

        webView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(webView)
        NSLayoutConstraint.activate([
            webView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            webView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            webView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])

        navigationItem.leftBarButtonItem = UIBarButtonItem(
            title: "关闭",
            style: .plain,
            target: self,
            action: #selector(onClose)
        )

        // OC: `+applyToWebView:hostController:config:callbacks:`
        // Swift 桥接(实测):`apply(to:hostController:config:callbacks:)`("WebView" 匹配参数名被吸收)
        handle = TQWebViewConfigurator.apply(to: webView,
                                             hostController: self,
                                             config: config,
                                             callbacks: callbacks)
        if let url = URL(string: urlString) {
            // OC: `-loadURL:` → Swift: `load(_:)`("URL" 匹配参数名 "url",被吸收为首参 _)
            handle?.load(url)
        }
    }

    @objc private func onClose() {
        dismiss(animated: true)
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if isBeingDismissed || isMovingFromParent {
            handle?.detachAndDestroy()
            handle = nil
        }
    }

    deinit {
        // handle 已在 viewDidDisappear 中清理,此处无需额外操作
    }
}
