import SwiftUI

struct ClockStyle: Codable, Equatable {
    var use24Hour: Bool = true
    var showSeconds: Bool = false
    var showAmPmBadge: Bool = false
    
    // Default to white digits
    var digitColorHex: String = "#FFFFFF"
    var randomizeColor: Bool = false
    
    var glowIntensity: Double = 0.6 // 0...1
    // Interpreted as 0.0...1.0 percentage of fitted size when stretched == false
    var digitScale: Double = 1.0
    
    // Stretched layout that auto-fits the available space (default: true)
    var stretched: Bool = true
    
    var backgroundHex: String = "#000000"
    var showBattery: Bool = true
    var showDate: Bool = true
    
    // Overall opacity for the main clock digits/separators (0.0...1.0)
    var clockOpacity: Double = 0.5
    
    // New: Independent opacity for the top overlay (battery/date) (0.0...1.0)
    var overlayOpacity: Double = 0.5
    
    // Codable <-> Color helpers
    var digitColor: Color {
        Color(hex: digitColorHex) ?? .white
    }
    var backgroundColor: Color {
        Color(hex: backgroundHex) ?? .black
    }
}

extension ClockStyle {
    static let appStorageKey = "ClockStyle_JSON"
}

extension Color {
    init?(hex: String) {
        let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
        var int: UInt64 = 0
        guard Scanner(string: hex).scanHexInt64(&int) else { return nil }
        let r, g, b, a: UInt64
        switch hex.count {
        case 3: (r, g, b, a) = (int >> 8, int >> 4 & 0xF, int & 0xF, 0xF)
        case 6: (r, g, b, a) = (int >> 16, int >> 8 & 0xFF, int & 0xFF, 0xFF)
        case 8: (r, g, b, a) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
        default: return nil
        }
        self.init(.sRGB,
                  red: Double(r) / 255,
                  green: Double(g) / 255,
                  blue: Double(b) / 255,
                  opacity: Double(a) / 255)
    }
    
    func toHex() -> String? {
        let uic = UIColor(self)
        var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
        guard uic.getRed(&r, green: &g, blue: &b, alpha: &a) else { return nil }
        let rgb: Int = Int(r*255)<<16 | Int(g*255)<<8 | Int(b*255)<<0
        return String(format: "#%06x", rgb)
    }
}
