import SwiftUI
import UIKit
import UserNotifications

@main
struct piRemoteApp: App {
    @StateObject private var appState = AppState.shared
    @StateObject private var notificationDelegate = NotificationDelegate.shared
    private let pairingService = PairingService()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(appState)
                .onAppear {
                    notificationDelegate.setup()
                    UIApplication.shared.registerForRemoteNotifications()
                }
                .onOpenURL { url in
                    handlePairingURL(url)
                }
        }
    }

    /// Handle `pi-remote://...` deep links — dev / simulator convenience pairing.
    private func handlePairingURL(_ url: URL) {
        guard let parsed = try? PairingService.parseQR(url.absoluteString) else { return }
        Task { @MainActor in
            do {
                let credential = try await pairingService.exchange(
                    host: parsed.host,
                    port: parsed.port,
                    pairingToken: parsed.pairingToken,
                    fingerprint: parsed.fingerprint,
                    name: parsed.name,
                    deviceName: UIDevice.current.name
                )
                appState.didPair(credential: credential)
            } catch {
                print("[pairing] deep-link exchange failed: \(error)")
            }
        }
    }
}
