import SwiftUI
import SwiftData

@main
struct BanYaroGoApp: App {
    @State private var auth = AuthSession()
    @State private var activeDog = ActiveDogStore()
    @State private var pendingGPX: GPXTrack?

    var body: some Scene {
        WindowGroup {
            RootView()
                .environment(auth)
                .environment(activeDog)
                .onOpenURL { url in
                    handleIncoming(url: url)
                }
                .sheet(item: Binding(
                    get: { pendingGPX.map { TrackBox(track: $0) } },
                    set: { pendingGPX = $0?.track }
                )) { box in
                    GPXImportSheet(track: box.track) {
                        pendingGPX = nil
                    }
                }
        }
        .modelContainer(for: [ActiveWalk.self, PhotoLocation.self])
    }

    private func handleIncoming(url: URL) {
        // Nur GPX akzeptieren — andere URLs (Deep-Links) sind anderweitig verdrahtet.
        guard url.pathExtension.lowercased() == "gpx" else { return }

        let didAccess = url.startAccessingSecurityScopedResource()
        defer { if didAccess { url.stopAccessingSecurityScopedResource() } }

        do {
            let data = try Data(contentsOf: url)
            let track = try GPXParser.parse(data: data)
            pendingGPX = track
        } catch {
            print("GPX-Import fehlgeschlagen: \(error)")
        }
    }
}

/// Hilfs-Wrapper, damit GPXTrack als `Identifiable` in `.sheet(item:)` taugt.
private struct TrackBox: Identifiable {
    let id = UUID()
    let track: GPXTrack
}
