import 'dart:async';
import 'package:flutter/material.dart';

class TypewriterText extends StatefulWidget {
  final String text; // 要显示的完整文本
  final TextStyle? style; // 字体样式
  final Duration speed; // 每个字出现的速度
  final VoidCallback? onComplete; // 打字完成回调
  final bool repeat; // 是否循环播放

  const TypewriterText({
    super.key,
    required this.text,
    this.style,
    this.speed = const Duration(milliseconds: 80),
    this.onComplete,
    this.repeat = false,
  });

  @override
  _TypewriterTextState createState() => _TypewriterTextState();
}

class _TypewriterTextState extends State<TypewriterText> {
  String _displayedText = '';
  int _charIndex = 0;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _startTyping();
  }

  void _startTyping() {
    _displayedText = '';
    _charIndex = 0;
    _timer?.cancel();

    _timer = Timer.periodic(widget.speed, (timer) {
      if (_charIndex < widget.text.length) {
        setState(() {
          _displayedText += widget.text[_charIndex];
        });
        _charIndex++;
      } else {
        _timer?.cancel();
        widget.onComplete?.call();
        if (widget.repeat) {
          Future.delayed(Duration(seconds: 1), _startTyping);
        }
      }
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Text(
      _displayedText,
      style: widget.style ?? const TextStyle(fontSize: 18),
    );
  }
}
