//
//  UIKitExample.swift
//  Navvo Maps SDK for iOS — minimal runnable UIKit example.
//
//  Drop this view controller into any iOS app that depends on the NavvoMaps
//  package. Replace the API key with your own (from navvo.io/developer).
//

import UIKit
import NavvoMaps

final class MapViewController: UIViewController, NavvoMapViewDelegate {

    private var mapView: NavvoMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // 1. Configure once (usually in AppDelegate).
        NavvoMaps.configure(apiKey: "nvvo_YOUR_KEY")

        // 2. Create the map over Amman.
        var options = NavvoMapView.Options()
        options.style = .standard
        options.camera = CameraPosition(target: LatLng(31.95, 35.91), zoom: 12)
        mapView = NavvoMapView(frame: view.bounds, options: options)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        mapView.delegate = self
        view.addSubview(mapView)

        // 3. Add a marker with a tap callback.
        let marker = NavvoMarker(
            position: LatLng(31.9539, 35.9106),
            title: "Downtown Amman"
        )
        marker.onTap = { tapped in
            print("Marker tapped: \(tapped.title ?? "?")")
        }
        mapView.addMarker(marker)

        // 4. Plan a route and draw it.
        Task { await drawRoute() }
    }

    private func drawRoute() async {
        do {
            let plan = try await NavvoServices.shared.plan(
                RoutePlanRequest(
                    locations: [
                        PlanStop(LatLng(31.95, 35.91), name: "Origin"),
                        PlanStop(LatLng(31.99, 35.86), name: "Destination"),
                    ],
                    costing: .auto,
                    preference: .fastest
                )
            )
            print("Route: \(plan.distanceKm ?? 0) km, \(plan.durationMinutes ?? 0) min")

            mapView.addPolyline(id: "route", path: plan.geometry, color: .systemBlue, width: 6)
            if let bounds = LatLngBounds(fitting: plan.geometry) {
                mapView.fit(
                    bounds: bounds,
                    padding: UIEdgeInsets(top: 60, left: 40, bottom: 60, right: 40)
                )
            }
        } catch let error as NavvoError {
            switch error {
            case .scope(let missing, _):
                print("API key is missing a scope: \(missing ?? "?")")
            case .rateLimit(let retryAfter, _):
                print("Rate limited; retry after \(retryAfter ?? 2)s")
            case .engineUnavailable:
                print("Routing temporarily unavailable — try again shortly")
            default:
                print("Navvo error: \(error.localizedDescription)")
            }
        } catch {
            print("Unexpected error: \(error)")
        }
    }

    // MARK: NavvoMapViewDelegate

    func mapView(_ mapView: NavvoMapView, didTapAt coordinate: LatLng) {
        print("Map tapped at \(coordinate)")
        Task {
            if let hit = try? await NavvoServices.shared.reverseGeocode(coordinate) {
                print("You tapped near: \(hit.displayName ?? "unknown")")
            }
        }
    }

    func mapViewDidFinishLoadingStyle(_ mapView: NavvoMapView) {
        print("Style loaded: \(mapView.style)")
    }
}
