import 'package:flutter/material.dart';

/// 三击检测器
class TripleTapDetector extends StatefulWidget {
  final Widget child;
  final VoidCallback onTripleTap;
  final int requiredTaps;
  final Duration tapInterval;

  const TripleTapDetector({
    super.key,
    required this.child,
    required this.onTripleTap,
    this.requiredTaps = 5,
    this.tapInterval = const Duration(milliseconds: 500),
  });

  @override
  State<TripleTapDetector> createState() => _TripleTapDetectorState();
}

class _TripleTapDetectorState extends State<TripleTapDetector> {
  int _tapCount = 0;
  DateTime? _lastTapTime;

  void _handleTap() {
    final now = DateTime.now();

    if (_lastTapTime == null) {
      _tapCount = 1;
    } else {
      // 检查点击间隔是否在指定时间内
      if (now.difference(_lastTapTime!) <= widget.tapInterval) {
        _tapCount++;
      } else {
        _tapCount = 1;
      }
    }

    _lastTapTime = now;

    // 达到指定点击次数时触发回调
    if (_tapCount == widget.requiredTaps) {
      widget.onTripleTap();
      _tapCount = 0;
      _lastTapTime = null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Listener(
      onPointerDown: (event) {
        _handleTap();
      },
      behavior: HitTestBehavior.translucent,
      child: widget.child,
    );
  }
}
