//
//  BatteryMonitor.swift
//  ylgamehall
//
//  UIDevice.batteryLevelDidChangeNotification 的最简 wrap：
//  提供 currentLevel 同步快照 + onChange 主线程回调。
//
//  契约：docs/H5-Native-Contract.md §3.2 ［2］getBattery 反向 callback
//  Phase 2.9
//

import UIKit

@MainActor
public final class BatteryMonitor {

    public static let shared = BatteryMonitor()

    /// 当前电量 0.0…1.0；模拟器无电池硬件返回 -1，BatteryMonitor.start() 后兜底为 0
    public private(set) var currentLevel: Float = 0

    /// 电量变化回调（主线程触发）
    public var onChange: (@MainActor (Float) -> Void)?

    private var started = false

    public init() {}

    public func start() {
        guard !started else { return }
        started = true
        UIDevice.current.isBatteryMonitoringEnabled = true
        currentLevel = max(UIDevice.current.batteryLevel, 0)
        NotificationCenter.default.addObserver(
            forName: UIDevice.batteryLevelDidChangeNotification,
            object: nil,
            queue: .main
        ) { [weak self] _ in
            // forName: + queue: .main 的 block 闭包在 main 队列触发；
            // 用 MainActor.assumeIsolated 把它桥到 main actor 隔离
            MainActor.assumeIsolated {
                guard let self else { return }
                let level = max(UIDevice.current.batteryLevel, 0)
                self.currentLevel = level
                self.onChange?(level)
            }
        }
    }
}
