//
//  WiredTransferHelpDocView.swift
//  suixinkan
//

import SwiftUI
import WebKit

/// 有线传图帮助文档 H5 页。
struct WiredTransferHelpDocView: View {
    let url: URL
    @State private var isLoading = true

    var body: some View {
        ZStack {
            WiredTransferHelpWebView(url: url, isLoading: $isLoading)
            if isLoading {
                ProgressView()
                    .controlSize(.large)
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .background(Color.white.opacity(0.4))
            }
        }
        .background(WiredTransferDesign.pageBackground.ignoresSafeArea())
        .navigationTitle("帮助文档")
        .navigationBarTitleDisplayMode(.inline)
    }
}

private struct WiredTransferHelpWebView: UIViewRepresentable {
    let url: URL
    @Binding var isLoading: Bool

    func makeCoordinator() -> Coordinator {
        Coordinator(isLoading: $isLoading)
    }

    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        webView.navigationDelegate = context.coordinator
        return webView
    }

    func updateUIView(_ webView: WKWebView, context: Context) {
        guard webView.url != url else { return }
        isLoading = true
        webView.load(URLRequest(url: url))
    }

    final class Coordinator: NSObject, WKNavigationDelegate {
        @Binding var isLoading: Bool

        init(isLoading: Binding<Bool>) {
            _isLoading = isLoading
        }

        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            isLoading = false
        }

        func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
            isLoading = false
        }
    }
}
