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

typedef MarqueeBuilder = Marquee Function(
    BuildContext context, String text, TextStyle textStyle);
typedef TextBuilder = Text Function(
    BuildContext context, String text, TextStyle textStyle);

class MarqueeText extends StatelessWidget {
  final String text;
  final TextStyle textStyle;
  final double containerWidth;
  final TextBuilder textBuilder;
  final MarqueeBuilder marqueeBuilder;

  const MarqueeText({
    super.key,
    required this.marqueeBuilder,
    required this.textBuilder,
    required this.text,
    required this.textStyle,
    required this.containerWidth,
  });

  static MarqueeText marquee(
      {required String text,
      required TextStyle textStyle,
      required double containerWidth,
      double velocity = 18.0,
      double blankSpace = 20}) {
    return MarqueeText(
      text: text,
      textStyle: textStyle,
      containerWidth: containerWidth,
      textBuilder: (context, text, textStyle) {
        return Text(text, style: textStyle);
      },
      marqueeBuilder: (context, text, textStyle) {
        return Marquee(
            text: text,
            style: textStyle,
            blankSpace: blankSpace,
            pauseAfterRound: Duration(seconds: 2),
            velocity: velocity);
      },
    );
  }

  Size calculateTextSize(String text, TextStyle style) {
    final TextPainter textPainter = TextPainter(
        text: TextSpan(text: text, style: style),
        maxLines: 1,
        textDirection: TextDirection.ltr)
      ..layout(minWidth: 0, maxWidth: double.infinity);
    return textPainter.size;
  }

  @override
  Widget build(BuildContext context) {
    final textWidth = calculateTextSize(text, textStyle).width;
    return textWidth < containerWidth
        ? textBuilder(context, text, textStyle)
        : marqueeBuilder(context, text, textStyle);
  }
}
