import SwiftUI

@main
struct BusinessCardClipApp: App {
    @State private var recordName: String?

    var body: some Scene {
        WindowGroup {
            Group {
                if let recordName {
                    ClipRootView(recordName: recordName)
                } else {
                    ClipLoadingView()
                }
            }
            .onContinueUserActivity(NSUserActivityTypeBrowsingWeb) { activity in
                handleUserActivity(activity)
            }
            .onOpenURL { url in
                handleURL(url)
            }
        }
    }

    private func handleUserActivity(_ activity: NSUserActivity) {
        guard let url = activity.webpageURL else { return }
        handleURL(url)
    }

    private func handleURL(_ url: URL) {
        guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true),
              let id = components.queryItems?.first(where: { $0.name == "id" })?.value else {
            return
        }
        recordName = id
    }
}
