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

class GradientMesh extends StatefulWidget {
  const GradientMesh({super.key});

  @override
  State<GradientMesh> createState() => _GradientMeshState();
}

class _GradientMeshState extends State<GradientMesh>
    with SingleTickerProviderStateMixin {
  late AnimationController _ctrl;

  @override
  void initState() {
    super.initState();
    _ctrl = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 20),
    )..repeat();
  }

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

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _ctrl,
      builder: (context, _) {
        return CustomPaint(
          painter: _MeshPainter(_ctrl.value),
          size: Size.infinite,
        );
      },
    );
  }
}

class _MeshPainter extends CustomPainter {
  final double t;
  _MeshPainter(this.t);

  @override
  void paint(Canvas canvas, Size size) {
    final w = size.width;
    final h = size.height;

    // Blue blob
    final bluePaint = Paint()
      ..shader = RadialGradient(
        colors: [
          AppColors.royalBlue.withValues(alpha: 0.25),
          Colors.transparent,
        ],
      ).createShader(Rect.fromCircle(
        center: Offset(
          w * 0.2 + sin(t * 2 * pi) * w * 0.08,
          h * 0.2 + cos(t * 2 * pi) * h * 0.06,
        ),
        radius: w * 0.5,
      ));
    canvas.drawCircle(
      Offset(
        w * 0.2 + sin(t * 2 * pi) * w * 0.08,
        h * 0.2 + cos(t * 2 * pi) * h * 0.06,
      ),
      w * 0.5,
      bluePaint,
    );

    // Gold blob
    final goldPaint = Paint()
      ..shader = RadialGradient(
        colors: [
          AppColors.gold.withValues(alpha: 0.12),
          Colors.transparent,
        ],
      ).createShader(Rect.fromCircle(
        center: Offset(
          w * 0.8 + cos(t * 2 * pi) * w * 0.06,
          h * 0.8 + sin(t * 2 * pi) * h * 0.08,
        ),
        radius: w * 0.4,
      ));
    canvas.drawCircle(
      Offset(
        w * 0.8 + cos(t * 2 * pi) * w * 0.06,
        h * 0.8 + sin(t * 2 * pi) * h * 0.08,
      ),
      w * 0.4,
      goldPaint,
    );
  }

  @override
  bool shouldRepaint(_MeshPainter old) => old.t != t;
}
