import UIKit
import WebKit
import TencentQianWebViewSDK

/// 配置模式 Demo:
/// - 自带一个空 WKWebView
/// - viewDidLoad 调 ``TencentQianWebViewConfigurator.apply`` 套用 SDK 全部能力
/// - 然后 `webView.load(URLRequest)` 加载传入的 URL
final class ConfiguratorDemoViewController: UIViewController {

    private let urlString: String
    private let callbacks: SignCallbacks
    private let config: TencentQianWebViewConfig
    private let webView: WKWebView
    private var handle: TencentQianWebViewConfigurator.Handle?

    init(url: String, callbacks: SignCallbacks) {
        self.urlString = url
        self.callbacks = callbacks
        let config = TencentQianWebViewConfig(userAgentExtra: "qianwv-demo/1.0.0(configurator)")
        let webViewConfig = WKConfigurationFactory.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)
        )

        handle = TencentQianWebViewConfigurator.apply(
            webView: webView,
            hostController: self,
            config: config,
            callbacks: callbacks
        )
        if let url = URL(string: urlString) {
            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 中清理,此处无需额外操作
    }
}
