//
//  TA134RiveButtonView.swift
//  TimeAwake
//
//  v134 引导页通用 Rive 继续按钮。
//

import RiveRuntime
import SnapKit
import TCBusinessKit
import UIKit

/// 通用 Rive 按钮样式。
///
/// 颜色使用十六进制字符串，方便按设计稿直接配置；字体通过 Rive 的 FontProperty 绑定。
struct TA134RiveButtonStyle {

    /// 按钮背景色，默认 `#FFFFFF`。
    var ta_backgroundColor: String = "#FFFFFF"

    /// 按钮描边色，无描边时与背景色保持一致。
    var ta_borderColor: String = "#FFFFFF"

    /// 描边宽度。
    var ta_borderSize: Double = 0

    /// 圆角半径。
    var ta_rounded: Double = 30.0.p12_adapter

    /// 按钮文案。
    var ta_textContent: String = TCLocalizableManager.localValue("Continue")

    /// 文字颜色。
    var ta_textColor: String = "#1C1C1E"

    /// 文字字体。
    var ta_textFont: UIFont = UIFont(name: TCPingFangSemibold, size: 17.0.p12_adapter)
        ?? UIFont.systemFont(ofSize: 17.0.p12_adapter, weight: .semibold)

    /// 箭头颜色，无箭头时与背景色保持一致。
    var ta_arrowColor: String = "#FFFFFF"

    /// 箭头位置，0 ~ 100。
    var ta_arrowLocation: Double = 95
}

/// v134 引导页通用 Rive 继续按钮。
///
/// 使用 `riv_continue_conmon_btn.riv` 的 `ViewModel1` 数据绑定驱动按钮样式，
/// 对外仅暴露 `ta_config(style:)` 与点击回调，便于不同引导子页面复用。
final class TA134RiveButtonView: UIView {

    /// 点击回调。
    var ta_clickBlock: (() -> Void)?

    /// 当前样式。
    private var ta_style = TA134RiveButtonStyle()

    /// Rive 文件名。
    private let ta_riveFileName = "riv_continue_common_btn"

    /// Rive ViewModel 名称。
    private let ta_viewModelName = "ViewModel1"

    /// Rive 状态机名称。
    private let ta_stateMachineName = "State Machine 1"

    /// Rive 渲染所需对象，需持有避免提前释放。
    private var ta_worker: Worker?
    private var ta_file: File?
    private var ta_artboard: Artboard?
    private var ta_viewModelInstance: ViewModelInstance?
    private var ta_stateMachine: StateMachine?
    private var ta_rive: Rive?
    private var ta_riveView: RiveUIView?

    /// 样式配置是否已写入 Rive 实例。
    private var ta_isStyleApplied = false

    /// 是否正在加载 Rive。
    private var ta_isLoading = false

    override init(frame: CGRect) {
        super.init(frame: frame)
        ta_setupView()
        ta_loadRive()
    }

    @available(*, unavailable)
    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    /// 更新按钮样式。
    ///
    /// Rive 尚未加载完成时会缓存样式，加载完成后自动应用。
    /// - Parameter style: 按钮样式。
    func ta_config(style: TA134RiveButtonStyle) {
        ta_style = style
        guard ta_viewModelInstance != nil else { return }
        ta_applyCurrentStyle()
    }

    /// 仅更新按钮文案。
    /// - Parameter text: 按钮文案。
    func ta_updateText(_ text: String) {
        ta_style.ta_textContent = text
        guard ta_viewModelInstance != nil else { return }
        ta_applyCurrentStyle()
    }
}

// MARK: - UI

private extension TA134RiveButtonView {

    /// 配置基础视图与点击手势。
    func ta_setupView() {
        #if DEBUG
        /// Debug 构建打开 Rive 运行时日志，便于在真机排查属性路径解析
        /// （`*AtPath:found:`）与字体解码（`decodeFont failed:`）问题。
        RiveLogger.isEnabled = true
        #endif

        backgroundColor = .clear
        isUserInteractionEnabled = true
        isAccessibilityElement = true
        accessibilityTraits = .button

        let ta_tap = UITapGestureRecognizer(target: self, action: #selector(ta_buttonTapped))
        addGestureRecognizer(ta_tap)
    }

    /// 点击事件。
    @objc func ta_buttonTapped() {
        ta_clickBlock?()
    }
}

// MARK: - Rive

private extension TA134RiveButtonView {

    /// 异步加载 Rive 文件并创建渲染视图。
    func ta_loadRive() {
        guard !ta_isLoading else { return }
        ta_isLoading = true

        Task { @MainActor [weak self] in
            guard let self = self else { return }
            do {
                let ta_worker = try await Worker()
                let ta_file = try await File(source: .local(self.ta_riveFileName, .main), worker: ta_worker)
                let ta_artboard = try await ta_file.createArtboard()
                let ta_instance = try await ta_file.createViewModelInstance(
                    .viewModelDefault(from: .artboardDefault(ta_artboard))
                )

                let ta_stateMachine = try await ta_artboard.createStateMachine(
                    self.ta_stateMachineName,
                    binding: ta_instance
                )
                self.ta_worker = ta_worker
                self.ta_file = ta_file
                self.ta_artboard = ta_artboard
                self.ta_viewModelInstance = ta_instance
                self.ta_stateMachine = ta_stateMachine

                /// 对齐 Rive2123Bindings 的调用时机：创建实例后、首次 advance 前，
                /// 先解码字体并一次性写入全部样式，再创建 Rive 对象与渲染视图。
                await self.ta_apply(style: self.ta_style, to: ta_instance, worker: ta_worker)
                ta_stateMachine.advance(by: 0)
                self.ta_isStyleApplied = true
                self.accessibilityLabel = self.ta_style.ta_textContent

                let ta_rive = try await Rive(
                    file: ta_file,
                    artboard: ta_artboard,
                    stateMachine: ta_stateMachine,
                    fit: .fill(alignment: .center)
                )
                let ta_riveView = RiveUIView(rive: ta_rive)
                ta_riveView.backgroundColor = .clear
                ta_riveView.isUserInteractionEnabled = false
                self.ta_rive = ta_rive
                self.ta_riveView = ta_riveView

                self.addSubview(ta_riveView)
                ta_riveView.snp.makeConstraints { make in
                    make.edges.equalToSuperview()
                }
                self.sendSubviewToBack(ta_riveView)
            } catch {
                self.ta_isLoading = false
                debugPrint("TA134RiveButtonView load rive failed: \(error)")
            }
        }
    }

    /// 重新应用当前样式。
    func ta_applyCurrentStyle() {
        guard let ta_instance = ta_viewModelInstance,
              let ta_worker = ta_worker else { return }

        Task { @MainActor [weak self] in
            guard let self = self else { return }
            await self.ta_apply(style: self.ta_style, to: ta_instance, worker: ta_worker)
            self.accessibilityLabel = self.ta_style.ta_textContent
        }
    }

    /// 将样式写入 Rive ViewModel 实例。
    ///
    /// 对齐 `Rive2123Bindings` 的顺序：先解码并写入字体（FontProperty 排最前），
    /// 再写入文本、颜色等其余属性；字体解码失败会输出日志，不影响其余样式。
    /// - Parameters:
    ///   - style: 按钮样式。
    ///   - instance: Rive ViewModel 实例。
    ///   - worker: Rive Worker，用于解码字体。
    func ta_apply(
        style: TA134RiveButtonStyle,
        to instance: ViewModelInstance,
        worker: Worker
    ) async {
        do {
            let ta_font = try await worker.decodeFont(from: style.ta_textFont)
            instance.setValue(of: FontProperty(path: "textFont"), to: ta_font)
        } catch {
            debugPrint("TA134RiveButtonView decodeFont failed: \(style.ta_textFont.fontName), \(error)")
        }

        instance.setValue(of: StringProperty(path: "textContent"), to: style.ta_textContent)
        instance.setValue(of: ColorProperty(path: "textColor"), to: ta_riveColor(from: style.ta_textColor))
        instance.setValue(of: ColorProperty(path: "arrowColor"), to: ta_riveColor(from: style.ta_arrowColor))
        instance.setValue(of: NumberProperty(path: "arrowLocation"), to: Float(style.ta_arrowLocation))
        instance.setValue(of: ColorProperty(path: "backgroundColor"), to: ta_riveColor(from: style.ta_backgroundColor))
        instance.setValue(of: ColorProperty(path: "borderColor"), to: ta_riveColor(from: style.ta_borderColor))
        instance.setValue(of: NumberProperty(path: "borderSize"), to: Float(style.ta_borderSize))
        instance.setValue(of: NumberProperty(path: "rounded"), to: Float(style.ta_rounded))

        /// 写入 ViewModel 后推进零时长帧，令绑定值即时同步到 Artboard 与 RiveUIView。
        /// 状态机静止（无播放中的动画）时，不推进帧则所有绑定值都不会生效。
        ta_stateMachine?.advance(by: 0)
    }

    /// 十六进制颜色转换为 Rive 颜色。
    /// - Parameter hex: `#RRGGBB` 格式颜色字符串。
    /// - Returns: Rive 颜色。
    func ta_riveColor(from hex: String) -> RiveRuntime.Color {
        let ta_color = UIColor(var_hex: hex)
        var ta_red: CGFloat = 0
        var ta_green: CGFloat = 0
        var ta_blue: CGFloat = 0
        var ta_alpha: CGFloat = 0
        ta_color.getRed(&ta_red, green: &ta_green, blue: &ta_blue, alpha: &ta_alpha)

        /// 将 0 ~ 1 的颜色分量转换为 0 ~ 255。
        func ta_component(_ value: CGFloat) -> UInt8 {
            UInt8(max(0, min(255, (value * 255).rounded())))
        }

        return RiveRuntime.Color(
            red: ta_component(ta_red),
            green: ta_component(ta_green),
            blue: ta_component(ta_blue),
            alpha: ta_component(ta_alpha)
        )
    }
}
