//
//  TimeSegment.swift
//  TheNoiseClock
//
//  Created by Matt Bruce on 9/9/25.
//

import SwiftUI

/// Component for displaying a time segment (hours, minutes, seconds) with fixed-width digits
struct TimeSegment: View {
    let text: String
    let fontSize: CGFloat
    let opacity: Double
    let digitColor: Color
    let glowIntensity: Double
    let fontFamily: String
    let fontWeight: String
    let fontDesign: String
    
    var body: some View {
        HStack(alignment: .center, spacing: 0) {
            ForEach(Array(text.enumerated()), id: \.offset) { index, character in
                DigitView(
                    digit: String(character),
                    fontSize: fontSize,
                    opacity: clampedOpacity,
                    digitColor: digitColor,
                    glowIntensity: glowIntensity,
                    fontFamily: fontFamily,
                    fontWeight: fontWeight,
                    fontDesign: fontDesign,
                    digitWidth: singleDigitWidth,
                    digitHeight: singleDigitHeight
                )
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
    
    // MARK: - Computed Properties
    private var clampedOpacity: Double {
        ColorUtils.clampOpacity(opacity)
    }
    
    private var customFont: UIFont {
        FontUtils.customUIFont(
            size: fontSize,
            family: fontFamily,
            weight: fontWeight,
            design: fontDesign
        )
    }
    
    private var singleDigitWidth: CGFloat {
        calculateMaxTextWidth(font: customFont, text: "8")
    }
    
    private var singleDigitHeight: CGFloat {
        calculateMaxTextHeight(font: customFont, text: "8")
    }
    
    // Calculate width of text for the given font - this ensures consistent width
    private func calculateMaxTextWidth(font: UIFont, text: String = "8") -> CGFloat {
        let attributes = [NSAttributedString.Key.font: font]
        let size = (text as NSString).size(withAttributes: attributes)
        return size.width
    }
    
    // Calculate height of text for the given font - this ensures consistent height
    private func calculateMaxTextHeight(font: UIFont, text: String = "8") -> CGFloat {
        let attributes = [NSAttributedString.Key.font: font]
        let size = (text as NSString).size(withAttributes: attributes)
        return size.height
    }
}

// MARK: - Preview
#Preview {
    let segment = TimeSegment(
        text: "12",
        fontSize: 80,
        opacity: 1.0,
        digitColor: .white,
        glowIntensity: 0.2,
        fontFamily: "System",
        fontWeight: "Regular",
        fontDesign: "Default"
    )
    
    return segment
        .background(Color.black)
        .frame(width: 200, height: 100)
}
