import Foundation

/// Flight load data from airline APIs
struct FlightLoad: Sendable {
    let airlineCode: String       // "UA", "AA", "KE", etc.
    let flightNumber: String      // "UA2238"
    let cabins: [CabinLoad]       // Full cabin data (United)
    let standbyList: [StandbyPassenger]
    let upgradeList: [StandbyPassenger]

    /// For airlines that only report available seat counts without capacity (AA)
    /// Keys: "First Class Upgrades", "Economy Standby", etc.
    let seatAvailability: [SeatAvailability]

    /// Total available seats across all cabins
    var totalAvailable: Int { cabins.reduce(0) { $0 + $1.available } }

    /// Total capacity across all cabins
    var totalCapacity: Int { cabins.reduce(0) { $0 + $1.capacity } }

    /// Total standby count from pbts data (sa + revenueStandby + waitList per cabin)
    var totalStandbyFromPBTS: Int {
        cabins.reduce(0) { $0 + $1.revenueStandby + $1.nonRevStandby + $1.waitListCount }
    }

    /// Whether this load has full cabin capacity data (vs just availability counts)
    var hasCabinData: Bool { !cabins.isEmpty }
}

/// Simple available seat count for airlines that don't provide full cabin data
struct SeatAvailability: Identifiable, Sendable {
    let id = UUID()
    let label: String             // "First Class Upgrades", "Economy Standby"
    let available: Int
    let color: SeatAvailabilityColor  // success/warning/failure from API
}

enum SeatAvailabilityColor: String, Sendable {
    case success, warning, failure
}

/// Cabin-level seat data
struct CabinLoad: Identifiable, Sendable {
    let id = UUID()
    let name: String              // "Front", "Middle", "Rear", "First", "Standby"
    let capacity: Int
    let booked: Int
    let revenueStandby: Int       // pbts.revenueStandby
    let nonRevStandby: Int        // pbts.sa (space available)
    var waitListCount: Int = 0    // pbts.waitList
    var jumpSeat: Int = 0         // pbts.jump

    var available: Int { max(0, capacity - booked) }

    var loadFactor: Double {
        guard capacity > 0 else { return 0 }
        return Double(booked) / Double(capacity)
    }

    /// Color name for the load factor
    var loadColor: LoadColor {
        switch loadFactor {
        case ..<0.7: return .green
        case ..<0.9: return .yellow
        default: return .red
        }
    }
}

enum LoadColor {
    case green, yellow, red
}

/// A passenger on a standby or upgrade list
struct StandbyPassenger: Identifiable, Sendable {
    let id = UUID()
    let order: Int                // 1-based position
    let displayName: String       // "BRI, K"
    let cleared: Bool
    let seat: String?             // seat number if cleared
    let listName: String          // "First", "Standby", "Front", etc.
}
