import 'package:flutter/cupertino.dart';

class SCKeybordUtil {
  static final List<Function(bool)> _lst = [];
  static bool _kbVis = false;
  static double _kbHt = 0.0;

  /// 添加全局键盘监听
  static void onChange(Function(bool visible) listener) {
    _lst.add(listener);
    // 立即通知当前状态
    listener(_kbVis);
  }

  /// 移除监听器
  static void removeListener(Function(bool visible) listener) {
    _lst.remove(listener);
  }

  /// 初始化键盘监听（必须在MaterialApp外层调用）
  static void init() {
    WidgetsBinding.instance.addObserver(_KbObs());
  }

  /// 获取当前键盘是否可见
  static bool get isVisible => _kbVis;

  /// 获取当前键盘高度
  static double get height => _kbHt;

  /// 隐藏键盘
  static void hide(BuildContext context) {
    FocusScope.of(context).unfocus();
  }

  /// 更新键盘状态（内部使用）
  static void _updSt(bool visible, double height) {
    if (visible != _kbVis || height != _kbHt) {
      _kbVis = visible;
      _kbHt = height;

      // 通知所有监听器
      for (final listener in _lst) {
        listener(visible);
      }
    }
  }
}

// 键盘状态观察者
class _KbObs extends WidgetsBindingObserver {
  @override
  void didChangeMetrics() {
    final view = WidgetsBinding.instance.platformDispatcher.views.first;

    if (view.viewInsets.bottom > 0) {
      // 键盘弹出
      SCKeybordUtil._updSt(true, view.viewInsets.bottom);
    } else {
      // 键盘收起
      SCKeybordUtil._updSt(false, 0.0);
    }
  }
}