import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:forui/forui.dart';


List<FItemGroupMixin> autoDismissMenuBuilder(
  BuildContext context,
  FPopoverController controller,
  List<FItemGroupMixin>? menu,
) {
  final groups = menu ?? const <FItemGroupMixin>[];
  if (groups.isEmpty) return groups;
  return [
    _AutoDismissMenuGroup(controller: controller, children: groups),
  ];
}

class _AutoDismissMenuGroup extends StatelessWidget with FItemGroupMixin {
  final FPopoverController controller;
  final List<FItemGroupMixin> children;

  const _AutoDismissMenuGroup({
    required this.controller,
    required this.children,
  });

  @override
  Widget build(BuildContext context) {
    final parent = FInheritedItemCallbacks.maybeOf(context);
    return FInheritedItemCallbacks(
      onHoverEnter: parent?.onHoverEnter,
      onHoverExit: parent?.onHoverExit,
      onPress: () {
        parent?.onPress?.call();
        unawaited(controller.hide());
      },
      onLongPress: () {
        parent?.onLongPress?.call();
        unawaited(controller.hide());
      },
      child: FItemGroup.merge(children: children),
    );
  }
}
