import SwiftUI

struct Theme {
    static let background = Color(red: 0.055, green: 0.052, blue: 0.067)
    static let panel = Color(red: 0.112, green: 0.105, blue: 0.135)
    static let panel2 = Color(red: 0.170, green: 0.157, blue: 0.205)
    static let stroke = Color(red: 0.475, green: 0.425, blue: 0.545)
    static let text = Color(red: 0.965, green: 0.930, blue: 0.760)
    static let muted = Color(red: 0.640, green: 0.585, blue: 0.710)
    static let accent = Color(red: 1.000, green: 0.812, blue: 0.176)
    static let ready = Color(red: 0.350, green: 0.820, blue: 1.000)
    static let amber = Color(red: 1.000, green: 0.570, blue: 0.240)
    static let red = Color(red: 1.000, green: 0.310, blue: 0.340)

    static let corner: CGFloat = 0
    static let smallCorner: CGFloat = 0

    static func pixel(_ size: CGFloat, weight: Font.Weight = .regular) -> Font {
        .custom("PixelifySans-Regular", size: size).weight(weight)
    }

    static func mono(_ size: CGFloat, weight: Font.Weight = .regular) -> Font {
        pixel(size, weight: weight).monospacedDigit()
    }

    static let bodyFont = pixel(16)
    static let headlineFont = pixel(19, weight: .semibold)
    static let captionFont = pixel(13)
    static let microFont = mono(11, weight: .semibold)
    static func display(_ size: CGFloat) -> Font { pixel(size, weight: .bold) }
}

extension View {
    func panel() -> some View {
        self
            .padding(14)
            .background(Theme.panel)
            .overlay(
                RoundedRectangle(cornerRadius: Theme.corner)
                    .stroke(Theme.stroke, lineWidth: 1)
            )
            .clipShape(RoundedRectangle(cornerRadius: Theme.corner))
    }

    func rowStyle(isActive: Bool = false) -> some View {
        self
            .padding(10)
            .background(isActive ? Theme.panel2.opacity(1.0) : Theme.panel2.opacity(0.76))
            .overlay(
                RoundedRectangle(cornerRadius: Theme.corner)
                    .stroke(isActive ? Theme.accent : Theme.stroke.opacity(0.38), lineWidth: 1)
            )
            .clipShape(RoundedRectangle(cornerRadius: Theme.corner))
    }

    func textFieldStyle() -> some View {
        self
            .padding(12)
            .foregroundStyle(Theme.text)
            .background(Theme.panel2)
            .overlay(
                RoundedRectangle(cornerRadius: Theme.corner)
                    .stroke(Theme.stroke, lineWidth: 1)
            )
            .clipShape(RoundedRectangle(cornerRadius: Theme.corner))
    }
}

func formatTime(_ ms: Int64) -> String {
    let total = max(0, Int(ms / 1000))
    return "\(total / 60):" + String(format: "%02d", total % 60)
}

func formatDuration(_ duration: TimeInterval) -> String {
    guard duration.isFinite, duration > 0 else { return "--:--" }
    return formatTime(Int64(duration * 1000))
}
