//
//  TravelSegment.swift
//  SportsTime
//

import Foundation
import CoreLocation

struct TravelSegment: Identifiable, Codable, Hashable {
    let id: UUID
    let fromLocation: LocationInput
    let toLocation: LocationInput
    let travelMode: TravelMode
    let distanceMeters: Double
    let durationSeconds: Double
    let scenicScore: Double
    let evChargingStops: [EVChargingStop]
    let routePolyline: String?

    init(
        id: UUID = UUID(),
        fromLocation: LocationInput,
        toLocation: LocationInput,
        travelMode: TravelMode,
        distanceMeters: Double,
        durationSeconds: Double,
        scenicScore: Double = 0.5,
        evChargingStops: [EVChargingStop] = [],
        routePolyline: String? = nil
    ) {
        self.id = id
        self.fromLocation = fromLocation
        self.toLocation = toLocation
        self.travelMode = travelMode
        self.distanceMeters = distanceMeters
        self.durationSeconds = durationSeconds
        self.scenicScore = scenicScore
        self.evChargingStops = evChargingStops
        self.routePolyline = routePolyline
    }

    var distanceMiles: Double { distanceMeters * 0.000621371 }
    var durationHours: Double { durationSeconds / 3600.0 }

    /// Alias for TripPlanningEngine compatibility
    var estimatedDrivingHours: Double { durationHours }
    var estimatedDistanceMiles: Double { distanceMiles }

    var formattedDistance: String {
        String(format: "%.0f mi", distanceMiles)
    }

    var formattedDuration: String {
        let hours = Int(durationHours)
        let minutes = Int((durationHours - Double(hours)) * 60)
        if hours > 0 && minutes > 0 { return "\(hours)h \(minutes)m" }
        else if hours > 0 { return "\(hours)h" }
        else { return "\(minutes)m" }
    }
}

// MARK: - EV Charging Stop

struct EVChargingStop: Identifiable, Codable, Hashable {
    let id: UUID
    let name: String
    let location: LocationInput
    let chargerType: ChargerType
    let estimatedChargeTime: TimeInterval

    init(
        id: UUID = UUID(),
        name: String,
        location: LocationInput,
        chargerType: ChargerType = .dcFast,
        estimatedChargeTime: TimeInterval = 1800
    ) {
        self.id = id
        self.name = name
        self.location = location
        self.chargerType = chargerType
        self.estimatedChargeTime = estimatedChargeTime
    }

    var formattedChargeTime: String {
        "\(Int(estimatedChargeTime / 60)) min"
    }
}

enum ChargerType: String, Codable, CaseIterable {
    case level2
    case dcFast
    case supercharger

    var displayName: String {
        switch self {
        case .level2: return "Level 2"
        case .dcFast: return "DC Fast"
        case .supercharger: return "Supercharger"
        }
    }
}
