import Foundation

public extension TimeInterval {
    /// Formats the interval as "m:ss", e.g. 65 → "1:05"
    var format_m_ss: String {
        guard !self.isNaN && !self.isInfinite else { return "0:00" }
        let totalSeconds = Int(self)
        let minutes = totalSeconds / 60
        let seconds = totalSeconds % 60
        return String(format: "%d:%02d", minutes, seconds)
    }

    var format_s: String {
        let totalSeconds = Int(self)
        let seconds = totalSeconds
        return String(format: "%2d", seconds)
    }

    /// Formats a start and end time as "m:ss / m:ss"
    static func formattedTimeRange(currentTime: TimeInterval, duration: TimeInterval) -> String {
        return "\(currentTime.format_m_ss) / \(duration.format_m_ss)"
    }

    /// Formats a start and end time as "m:ss • m:ss"
    static func formattedStartEndTimeRange(_ timeRange: ClosedRange<TimeInterval>) -> String {
        return "\(timeRange.lowerBound.format_m_ss) • \(timeRange.upperBound.format_m_ss)"
    }

    /// Formats a start and end time as "s"
    static func formattedDurationTimeRange(_ timeRange: ClosedRange<TimeInterval>) -> String {
        var duration = (timeRange.upperBound - timeRange.lowerBound)
        duration.round()
        return duration.format_s
    }

    /// Formats the interval with conditional minute padding - "0:30" for < 1 min, "1:30" for >= 1 min
    var formatTimeConditional: String {
        guard !self.isNaN && !self.isInfinite else { return "0:00" }
        let totalSeconds = Int(self)
        let minutes = totalSeconds / 60
        let seconds = totalSeconds % 60

        if minutes >= 1 {
            return String(format: "%d:%02d", minutes, seconds)
        } else {
            return String(format: "%02d:%02d", minutes, seconds)
        }
    }

    /// Formats the interval as human-readable duration - "30s" for < 1 min, "1m30s" for >= 1 min
    var formatDurationReadable: String {
        guard !self.isNaN && !self.isInfinite else { return "0" }

        // Create a static formatter for performance
        enum Formatters {
            static let duration: DateComponentsFormatter = {
                let formatter = DateComponentsFormatter()
                formatter.unitsStyle = .abbreviated
                formatter.allowedUnits = [.minute, .second]
                formatter.zeroFormattingBehavior = .dropLeading
                return formatter
            }()
        }

        // This handles all cases including 0 seconds properly localized
        return Formatters.duration.string(from: self) ?? "0"
    }
}
