// iOS 15.4+; Swift 5.7+
// iOS: configure the following privacy entries in the host app target Info.plist.
// Copy the XML without // into <dict>; customize the purpose strings.
// Attachment photo/video capture needs a camera purpose string.
// <key>NSCameraUsageDescription</key>
// <string>Take photos or record videos to send in chat.</string>
// Attachment video recording with audio needs a microphone purpose string.
// <key>NSMicrophoneUsageDescription</key>
// <string>Record sound for videos you send in chat.</string>
// Configure a photo-library purpose string if the host reads library assets; system-picker-only selection does not need it.
// <key>NSPhotoLibraryUsageDescription</key>
// <string>Access your photo library to select photos and videos to send in chat.</string>

import UIKit
import WebKit
import Network

final class WeakBridge: NSObject, WKScriptMessageHandler {
    weak var owner: KnocketViewController?
    init(_ owner: KnocketViewController) { self.owner = owner }
    func userContentController(_ controller: WKUserContentController,
                               didReceive message: WKScriptMessage) {
        owner?.handle(message)
    }
}

final class KnocketViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {
    private let chatURL = URL(string: "https://knocket.ai/mu/YOUR_IDENTIFIER")!
    private var webView: WKWebView!
    private var bridge: WeakBridge!
    private let networkMonitor = NWPathMonitor()

    override func viewDidLoad() {
        super.viewDidLoad()
        let config = WKWebViewConfiguration()
        config.websiteDataStore = .default()
        config.allowsInlineMediaPlayback = true
        config.mediaTypesRequiringUserActionForPlayback = .all
        bridge = WeakBridge(self)
        config.userContentController.add(bridge, name: "closeWebView")
        webView = WKWebView(frame: .zero, configuration: config)
        webView.navigationDelegate = self
        webView.uiDelegate = self
        webView.scrollView.contentInsetAdjustmentBehavior = .never
        webView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(webView)
        NSLayoutConstraint.activate([
            // The page handles iOS safe areas; keep the WebView full-screen without extra safe-area padding.
            webView.topAnchor.constraint(equalTo: view.topAnchor),
            webView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            webView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
        ])
        NotificationCenter.default.addObserver(self, selector: #selector(resume),
            name: UIApplication.didBecomeActiveNotification, object: nil)
        webView.load(URLRequest(url: chatURL))
        networkMonitor.pathUpdateHandler = { [weak self] path in
            if path.status == .satisfied {
                DispatchQueue.main.async {
                    if UIApplication.shared.applicationState == .active { self?.resume() }
                }
            }
        }
        networkMonitor.start(queue: DispatchQueue(label: "knocket.network"))
    }

    private func isChat(_ url: URL) -> Bool {
        guard url.scheme == chatURL.scheme,
              url.host == chatURL.host,
              url.port == chatURL.port else { return false }
        let expectedPath = chatURL.path.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
        let actualPath = url.path.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
        return actualPath == expectedPath
    }
    private func openExternal(_ url: URL) {
        if ["https", "http", "mailto", "tel"].contains(url.scheme ?? "") {
            UIApplication.shared.open(url, options: [:]) { [weak self] opened in
                if !opened {
                    let alert = UIAlertController(title: "Unable to open link",
                        message: "Please try again.", preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .default))
                    self?.present(alert, animated: true)
                }
            }
        }
    }
    private func loadFailed() {
        guard presentedViewController == nil else { return }
        let alert = UIAlertController(title: "Unable to load chat",
            message: "Check your connection and try again.", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Retry", style: .default) { [weak self] _ in
            guard let self else { return }
            self.webView.load(URLRequest(url: self.chatURL))
        })
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
        present(alert, animated: true)
    }
    // Keep the bridge channel and host-control command names unchanged.
    func handle(_ message: WKScriptMessage) {
        guard message.frameInfo.isMainFrame,
              let frameURL = message.frameInfo.request.url, isChat(frameURL),
              let body = message.body as? [String: Any] else { return }
        if body["type"] as? String == "closeWebView" {
            if let navigation = navigationController, navigation.viewControllers.first != self {
                navigation.popViewController(animated: true)
            } else if presentingViewController != nil || navigationController?.presentingViewController != nil {
                dismiss(animated: true)
            } else {
                let alert = UIAlertController(title: "Unable to close chat",
                    message: "Open this screen from an app route.", preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .default))
                present(alert, animated: true)
            }
        } else if body["type"] as? String == "openExternal",
                  let value = body["url"] as? String, let url = URL(string: value) {
            openExternal(url)
        }
    }
    func webView(_ view: WKWebView, decidePolicyFor action: WKNavigationAction,
                 decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        guard let url = action.request.url else { decisionHandler(.cancel); return }
        if action.targetFrame?.isMainFrame == false { decisionHandler(.cancel); return }
        if action.targetFrame?.isMainFrame == true && isChat(url) {
            decisionHandler(.allow)
        } else { openExternal(url); decisionHandler(.cancel) }
    }
    func webView(_ view: WKWebView, createWebViewWith config: WKWebViewConfiguration,
                 for action: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        if let url = action.request.url { openExternal(url) }
        return nil
    }
    func webView(_ view: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!,
                 withError error: Error) {
        if (error as NSError).code != NSURLErrorCancelled { loadFailed() }
    }
    func webView(_ view: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        if (error as NSError).code != NSURLErrorCancelled { loadFailed() }
    }
    func webView(_ view: WKWebView, decidePolicyFor response: WKNavigationResponse,
                 decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        if response.isForMainFrame, let http = response.response as? HTTPURLResponse,
           http.statusCode >= 400 {
            decisionHandler(.cancel)
            loadFailed()
        } else { decisionHandler(.allow) }
    }
    func webViewWebContentProcessDidTerminate(_ view: WKWebView) {
        view.load(URLRequest(url: chatURL))
    }
    @objc private func resume() {
        webView.evaluateJavaScript("window.dispatchEvent(new Event('online'))")
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
        networkMonitor.cancel()
        webView?.configuration.userContentController.removeScriptMessageHandler(forName: "closeWebView")
    }
}
// Open from an existing app screen, not as the app root.
// let screen = KnocketViewController()
// screen.modalPresentationStyle = .fullScreen
// present(screen, animated: true)