//
// Copyright 2025 Element Creations Ltd.
// Copyright 2023-2025 New Vector Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//

import CompoundDesignTokens
import UIKit

public extension UIColor {
    /// The colours used by Element as defined in Compound Design Tokens.
    static let compound = CompoundUIColors()
}

/// The colours used by Element as defined in Compound Design Tokens.
/// This class contains only the colour tokens in a more usable form.
/// Since this can be used by attributed strings which may run in non isolated concurrent contexts,
/// The object needs to be nonisolated.
@Observable
@dynamicMemberLookup
public final nonisolated class CompoundUIColors {
    /// The base colour tokens that form the palette of available colours.
    ///
    /// Normally these shouldn't be necessary, however in practice we may need
    /// access for temporary tokens while waiting for official ones to be formalised.
    private static let coreTokens = CompoundCoreUIColorTokens.self
    /// The main semantic tokens generated from the Style Dictionary.
    private let tokens = CompoundUIColorTokens()
    /// Runtime overrides for the `tokens` property.
    private var overrides = [KeyPath<CompoundUIColorTokens, UIColor>: UIColor]()
    
    public subscript(dynamicMember keyPath: KeyPath<CompoundUIColorTokens, UIColor>) -> UIColor {
        overrides[keyPath] ?? tokens[keyPath: keyPath]
    }
    
    /// Customise the colour at the specified key path with the supplied colour.
    /// Supplying `nil` as the colour will remove any existing customisation.
    public func override(_ keyPath: KeyPath<CompoundUIColorTokens, UIColor>, with color: UIColor?) {
        overrides[keyPath] = color
    }
    
    // MARK: - Awaiting Semantic Tokens
    
    // swiftformat:disable numberFormatting
    /// This token is a placeholder and hasn't been finalised.
    @available(iOS, deprecated: 100000.0, message: "This token should be generated by now.")
    public var _bgCodeBlock: UIColor {
        CompoundUIColors.coreTokens.gray100
    }

    /// This token is a placeholder and hasn't been finalised.
    @available(iOS, deprecated: 100000.0, message: "This token should be generated by now.")
    public let _bgSubtleSecondaryAlpha = coreTokens.alphaGray300
    // swiftformat:enable numberFormatting
}

private extension UITraitCollection {
    /// Whether or not the trait collection contains a `userInterfaceStyle` of `.light`.
    var isLight: Bool {
        userInterfaceStyle == .light
    }
}
