//
//  AgreementWebViewController.swift
//  suixinkan
//

import SnapKit
import UIKit
import WebKit

/// 应用内 WebView 页面，用于展示协议 H5、内置帮助 HTML 等文档内容。
final class AgreementWebViewController: BaseViewController {
    private let pageTitle: String
    private let url: URL

    private let webView = WKWebView(frame: .zero)
    private let loadingIndicator = UIActivityIndicatorView(style: .medium)

    init(title: String, url: URL) {
        pageTitle = title
        self.url = url
        super.init(nibName: nil, bundle: nil)
    }

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

    override func setupNavigationBar() {
        title = pageTitle
    }

    override func setupUI() {
        view.backgroundColor = AppColor.cardBackground
        webView.navigationDelegate = self
        view.addSubview(webView)
        view.addSubview(loadingIndicator)
        loadingIndicator.hidesWhenStopped = true
        loadingIndicator.startAnimating()
        loadContent()
    }

    private func loadContent() {
        if url.isFileURL {
            webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
        } else {
            webView.load(URLRequest(url: url))
        }
    }

    override func setupConstraints() {
        webView.snp.makeConstraints { make in
            make.edges.equalTo(view.safeAreaLayoutGuide)
        }
        loadingIndicator.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
    }
}

extension AgreementWebViewController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        loadingIndicator.stopAnimating()
    }

    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        loadingIndicator.stopAnimating()
        showToast(error.localizedDescription)
    }

    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        loadingIndicator.stopAnimating()
        showToast(error.localizedDescription)
    }
}
