import SwiftUI

enum Theme {
    static let background = Color(hex: 0x0C0F12)
    static let surface = Color(hex: 0x1C2228)
    static let border = Color(hex: 0x323B43)
    static let buttonBlue = Color(hex: 0x2563EB)
    static let accent = Color(hex: 0x15B884)
    static let accentDeep = Color(hex: 0x077656)
    static let accentLight = Color(hex: 0x5EEAB6)
    static let selected = Color(hex: 0xE5F8F0)
    static let progressTrack = Color(hex: 0xE0E7EB)
    static let progressTrackDark = Color(hex: 0x373E46)
    static let lightBorder = Color(hex: 0xDAE2E8)
    static let overlay = Color(red: 9.0 / 255.0, green: 12.0 / 255.0, blue: 16.0 / 255.0, opacity: 0.7)
    static let overlayFaint = Color(red: 9.0 / 255.0, green: 12.0 / 255.0, blue: 16.0 / 255.0, opacity: 0.2)
    static let textDark = Color(hex: 0x12181F)
    static let textMuted = Color(hex: 0x97A2AE)
    static let textSubtle = Color(hex: 0x58626C)
    static let textOverlay = Color(hex: 0xA3ACB6)

    static func formatTime(_ ms: Int64) -> String {
        if ms < 0 {
            return "--:--"
        }
        let totalSeconds = ms / 1000
        let hours = Int(totalSeconds / 3600)
        let minutes = Int((totalSeconds % 3600) / 60)
        let seconds = Int(totalSeconds % 60)
        if hours > 0 {
            return String(format: "%d:%02d:%02d", hours, minutes, seconds)
        }
        return String(format: "%02d:%02d", minutes, seconds)
    }

    static func formatSpeed(_ speed: Float) -> String {
        var value = String(format: "%.2f", speed)
        while value.hasSuffix("0") {
            value.removeLast()
        }
        if value.hasSuffix(".") {
            value.removeLast()
        }
        return "\(value)x"
    }
}

extension Color {
    init(hex: UInt32) {
        self.init(
            .sRGB,
            red: Double((hex >> 16) & 0xFF) / 255.0,
            green: Double((hex >> 8) & 0xFF) / 255.0,
            blue: Double(hex & 0xFF) / 255.0,
            opacity: 1
        )
    }
}

extension PlayerController {
    /// 与安卓端 playbackStatus() 一致的播放状态文案。
    func playbackStatusText(_ snapshot: PlaybackSnapshot) -> String {
        let state: String
        if snapshot.isPlaying {
            state = "播放中"
        } else if snapshot.state == .buffering {
            state = "缓冲中"
        } else if snapshot.state == .ended {
            state = "已结束"
        } else {
            state = "已暂停"
        }
        if let index = snapshot.sentenceIndex {
            return "\(state) · 第 \(index + 1) 句"
        }
        return state
    }
}
