import 'package:flutter/material.dart';

class CardBackground extends StatefulWidget {
  const CardBackground({super.key, this.background, this.cardKey});

  final Widget? background;
  final GlobalKey? cardKey;

  @override
  State<CardBackground> createState() => _CardBackgroundState();
}

class _CardBackgroundState extends State<CardBackground> {
  Size _cardSize = Size.zero;

  @override
  void initState() {
    super.initState();
    if (widget.background != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _resizeCard();
      });
    }
  }

  @override
  void didUpdateWidget(covariant CardBackground oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.background != null) {
      _resizeCard();
    }
  }

  void _resizeCard() {
    final RenderObject? renderBox =
        widget.cardKey?.currentContext?.findRenderObject();
    if (renderBox != null) {
      setState(() {
        _cardSize =
            Size(renderBox.paintBounds.width, renderBox.paintBounds.height);
      });
    }
  }

  @override
  Widget build(BuildContext context) => SizedBox(
        width: _cardSize.width,
        height: _cardSize.height,
        child: Center(child: widget.background),
      );
}
