//
//  Icon.swift
//  ThemeKit
//  Created by İsa Mercan on 23.06.2026.
//

import SwiftUI

public enum IconSize: String, CaseIterable {
    case xs, sm, md, lg, xl

    /// Point size, aligned with the type scale.
    public var value: CGFloat {
        switch self {
        case .xs: return 12
        case .sm: return 16
        case .md: return 20
        case .lg: return 24
        case .xl: return 32
        }
    }

    /// Font for a Font-Awesome glyph at this size (when the FA font is bundled).
    public func font(weight: Font.Weight = .regular) -> Font {
        Font.system(size: value, weight: weight)
    }
}

/// Icon system. The Figma design system uses Font Awesome Pro, which is a
/// licensed font and cannot be bundled here. `Icon` renders an SF Symbol by
/// default; to switch to Font Awesome, bundle the FA Pro `.ttf` and render a
/// glyph with `IconSize.font` instead.
public struct Icon: View {
    private let systemName: String
    // Appearance/config — mutated only through the modifiers below (R2).
    private var size: IconSize = .md
    private var color: Color?

    /// Renders an SF Symbol at a token size.
    public init(systemName: String) {   // R1 — content only
        self.systemName = systemName
    }

    public var body: some View {
        Image(systemName: systemName)
            .font(.system(size: size.value))
            .foregroundStyle(color ?? Color.primary)
    }
}

// MARK: - Modifiers (R2 copy-on-write · R5 standard vocabulary)

public extension Icon {
    /// Size tier: xs / sm / md / lg / xl (12/16/20/24/32 pt).
    func size(_ s: IconSize) -> Self { copy { $0.size = s } }

    /// Tint color; `nil` (default) inherits the surrounding `foregroundStyle`.
    func color(_ c: Color?) -> Self { copy { $0.color = c } }

    private func copy(_ mutate: (inout Self) -> Void) -> Self {   // R2 — single mutation point
        var c = self
        mutate(&c)
        return c
    }
}

#Preview {
    @Previewable @Environment(\.theme) var theme
    HStack(spacing: 12) {
        ForEach(IconSize.allCases, id: \.self) { s in
            Icon(systemName: "star.fill").size(s).color(theme.foreground(.fgHero))
        }
    }
    .padding()
}
