import 'dart:math';
import 'package:flutter/material.dart';
import '../core/theme/app_colors.dart';

/// Floating particles that drift upward with glow — creates a magical/3D feel.
class ParticleField extends StatefulWidget {
  final int count;
  final Color? color;
  const ParticleField({super.key, this.count = 40, this.color});

  @override
  State<ParticleField> createState() => _ParticleFieldState();
}

class _ParticleFieldState extends State<ParticleField>
    with SingleTickerProviderStateMixin {
  late AnimationController _ctrl;
  late List<_Particle> _particles;
  final _rng = Random();

  @override
  void initState() {
    super.initState();
    _particles = List.generate(widget.count, (_) => _Particle(_rng));
    _ctrl = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 60),
    )..repeat();
  }

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

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _ctrl,
      builder: (context, _) {
        return CustomPaint(
          painter: _ParticlePainter(
            _particles,
            _ctrl.value,
            widget.color ?? AppColors.royalBlue,
          ),
          size: Size.infinite,
        );
      },
    );
  }
}

class _Particle {
  final double x; // 0..1
  final double startY; // 0..1
  final double speed; // 0..1
  final double size; // radius
  final double opacity;
  final double phase; // offset for sin wave

  _Particle(Random rng)
      : x = rng.nextDouble(),
        startY = rng.nextDouble(),
        speed = 0.1 + rng.nextDouble() * 0.4,
        size = 1.0 + rng.nextDouble() * 3.0,
        opacity = 0.15 + rng.nextDouble() * 0.5,
        phase = rng.nextDouble() * 2 * pi;
}

class _ParticlePainter extends CustomPainter {
  final List<_Particle> particles;
  final double t;
  final Color baseColor;

  _ParticlePainter(this.particles, this.t, this.baseColor);

  @override
  void paint(Canvas canvas, Size size) {
    for (final p in particles) {
      final elapsed = (t * 2 + p.startY) % 1.0;
      final y = size.height * (1.0 - elapsed);
      final drift = sin(elapsed * 2 * pi + p.phase) * 20;
      final x = p.x * size.width + drift;

      // Fade in at bottom, fade out at top
      final fadeFactor = sin(elapsed * pi);
      final alpha = (p.opacity * fadeFactor).clamp(0.0, 1.0);

      final paint = Paint()
        ..color = baseColor.withValues(alpha: alpha)
        ..maskFilter = MaskFilter.blur(BlurStyle.normal, p.size * 1.5);

      canvas.drawCircle(Offset(x, y), p.size, paint);

      // Bright core
      final corePaint = Paint()
        ..color = Colors.white.withValues(alpha: alpha * 0.6);
      canvas.drawCircle(Offset(x, y), p.size * 0.3, corePaint);
    }
  }

  @override
  bool shouldRepaint(covariant _ParticlePainter old) => true;
}
