//
//  AppLifecycleObserver.swift
//  ylgamehall
//
//  监听 UIApplication 前/后台切换通知，提供 onBackground / onForeground 钩子。
//
//  契约：docs/H5-Native-Contract.md §3.2 ［4］appservice 反向 callback
//    "2" = 进入后台 / "1" = 回到前台（值错位沿用历史 msext WKWebView 路径，
//    参 daoqi/msext NewRootVC.m:1773/1782、gameController.m:1323/1332）
//  Phase 2.11
//

import UIKit

@MainActor
public final class AppLifecycleObserver {

    public static let shared = AppLifecycleObserver()

    public var onBackground: (@MainActor () -> Void)?
    public var onForeground: (@MainActor () -> Void)?

    private var started = false

    public init() {}

    public func start() {
        guard !started else { return }
        started = true
        let nc = NotificationCenter.default
        nc.addObserver(
            forName: UIApplication.didEnterBackgroundNotification,
            object: nil,
            queue: .main
        ) { [weak self] _ in
            MainActor.assumeIsolated {
                self?.onBackground?()
            }
        }
        nc.addObserver(
            forName: UIApplication.willEnterForegroundNotification,
            object: nil,
            queue: .main
        ) { [weak self] _ in
            MainActor.assumeIsolated {
                self?.onForeground?()
            }
        }
    }
}
