import 'package:flutter/material.dart';

class StaggeredEntrance extends StatefulWidget {
  final List<Widget> children;
  final Duration delay;
  final Duration duration;
  final double offsetY;

  const StaggeredEntrance({
    super.key,
    required this.children,
    this.delay = const Duration(milliseconds: 80),
    this.duration = const Duration(milliseconds: 500),
    this.offsetY = 30,
  });

  @override
  State<StaggeredEntrance> createState() => _StaggeredEntranceState();
}

class _StaggeredEntranceState extends State<StaggeredEntrance>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  final List<Animation<double>> _fadeAnims = [];
  final List<Animation<Offset>> _slideAnims = [];

  @override
  void initState() {
    super.initState();
    final total = widget.delay * widget.children.length + widget.duration;
    _controller = AnimationController(vsync: this, duration: total);

    for (int i = 0; i < widget.children.length; i++) {
      final start = (widget.delay.inMilliseconds * i) / total.inMilliseconds;
      final end = (widget.delay.inMilliseconds * i + widget.duration.inMilliseconds) /
          total.inMilliseconds;

      _fadeAnims.add(CurvedAnimation(
        parent: _controller,
        curve: Interval(start.clamp(0.0, 1.0), end.clamp(0.0, 1.0), curve: Curves.easeOut),
      ));

      _slideAnims.add(Tween<Offset>(
        begin: Offset(0, widget.offsetY),
        end: Offset.zero,
      ).animate(CurvedAnimation(
        parent: _controller,
        curve: Interval(start.clamp(0.0, 1.0), end.clamp(0.0, 1.0), curve: Curves.easeOutCubic),
      )));
    }

    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: List.generate(widget.children.length, (i) {
        return FadeTransition(
          opacity: _fadeAnims[i],
          child: AnimatedBuilder(
            animation: _slideAnims[i],
            builder: (context, child) => Transform.translate(
              offset: _slideAnims[i].value,
              child: child,
            ),
            child: widget.children[i],
          ),
        );
      }),
    );
  }
}
