import SwiftUI
import WebKit

struct WebPortalView: NSViewRepresentable {
    private let serverURL = URL(string: "https://nitin.sbs/tim/?source=macapp")!
    private let apiBase = "https://nitin.sbs/tim"

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeNSView(context: Context) -> WKWebView {
        let configuration = WKWebViewConfiguration()
        configuration.websiteDataStore = .default()
        configuration.preferences.javaScriptCanOpenWindowsAutomatically = true
        configuration.userContentController.addUserScript(
            WKUserScript(
                source: "window.TIME_MANAGEMENT_API_BASE='\(apiBase)'; window.TIME_MANAGEMENT_MAC_APP=true;",
                injectionTime: .atDocumentStart,
                forMainFrameOnly: true
            )
        )

        let webView = WKWebView(frame: .zero, configuration: configuration)
        webView.navigationDelegate = context.coordinator
        webView.allowsBackForwardNavigationGestures = true
        context.coordinator.loadOnlineOrOffline(webView)
        return webView
    }

    func updateNSView(_ webView: WKWebView, context: Context) {}

    final class Coordinator: NSObject, WKNavigationDelegate {
        private let parent: WebPortalView
        private var didFallbackToLocal = false

        init(_ parent: WebPortalView) {
            self.parent = parent
        }

        func loadOnlineOrOffline(_ webView: WKWebView) {
            var request = URLRequest(url: parent.serverURL)
            request.cachePolicy = .reloadIgnoringLocalCacheData
            request.timeoutInterval = 4

            URLSession.shared.dataTask(with: request) { _, response, _ in
                DispatchQueue.main.async {
                    if let http = response as? HTTPURLResponse, (200..<500).contains(http.statusCode) {
                        webView.load(URLRequest(url: self.parent.serverURL))
                    } else {
                        self.loadLocalPortal(webView)
                    }
                }
            }.resume()
        }

        func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
            loadLocalPortal(webView)
        }

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

        private func loadLocalPortal(_ webView: WKWebView) {
            guard !didFallbackToLocal else { return }
            didFallbackToLocal = true
            guard let url = localPortalURL() else {
                webView.loadHTMLString("<h1>Time Management</h1><p>Local portal file missing.</p>", baseURL: nil)
                return
            }
            webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
        }

        private func localPortalURL() -> URL? {
            let resourceURL = Bundle.main.resourceURL
            let candidates = [
                resourceURL?.appendingPathComponent("workflow-fixed.html"),
                resourceURL?.appendingPathComponent("TimeManagementMac_TimeManagementMac.bundle/workflow-fixed.html"),
                Bundle.module.url(forResource: "workflow-fixed", withExtension: "html")
            ]
            return candidates.compactMap { $0 }.first { FileManager.default.fileExists(atPath: $0.path) }
        }
    }
}
