import 'package:asciineverdie/src/shared/animation/canvas/ascii_canvas_painter.dart';
import 'package:asciineverdie/src/shared/animation/canvas/ascii_layer.dart';
import 'package:asciineverdie/src/shared/theme/ascii_colors.dart';
import 'package:flutter/material.dart';

/// ASCII Canvas 위젯 (RepaintBoundary 포함)
///
/// AsciiCanvasPainter를 감싸는 위젯.
/// RepaintBoundary로 성능 최적화.
/// willChange를 애니메이션 상태에 따라 동적 설정.
/// 테마 인식 색상 자동 적용 (Phase 5).
class AsciiCanvasWidget extends StatelessWidget {
  const AsciiCanvasWidget({
    super.key,
    required this.layers,
    this.gridWidth = 60,
    this.gridHeight = 8,
    this.backgroundOpacity = 0.5,
    this.isAnimating = true,
    this.layerVersion = 0,
  });

  /// 렌더링할 레이어 목록
  final List<AsciiLayer> layers;

  /// 그리드 너비 (열 수)
  final int gridWidth;

  /// 그리드 높이 (행 수)
  final int gridHeight;

  /// 배경 투명도 (0.0 ~ 1.0, 기본값 0.5 = 50%)
  final double backgroundOpacity;

  /// 애니메이션 활성 상태 (willChange 최적화용)
  final bool isAnimating;

  /// 레이어 버전 (변경 감지용, shouldRepaint 최적화)
  final int layerVersion;

  @override
  Widget build(BuildContext context) {
    // 테마 인식 색상 (다크/라이트 모드 자동 전환)
    final bgColor = AsciiColors.backgroundOf(context);
    final objColor = AsciiColors.objectOf(context);
    final posColor = AsciiColors.positiveOf(context);
    final negColor = AsciiColors.negativeOf(context);

    // 무기 등급 색상 (Phase 9)
    final uncommonColor = AsciiColors.rarityUncommonOf(context);
    final rareColor = AsciiColors.rarityRareOf(context);
    final epicColor = AsciiColors.rarityEpicOf(context);
    final legendaryColor = AsciiColors.rarityLegendaryOf(context);

    return RepaintBoundary(
      child: CustomPaint(
        painter: AsciiCanvasPainter(
          layers: layers,
          gridWidth: gridWidth,
          gridHeight: gridHeight,
          backgroundColor: bgColor,
          backgroundOpacity: backgroundOpacity,
          layerVersion: layerVersion,
          objectColor: objColor,
          positiveColor: posColor,
          negativeColor: negColor,
          rarityUncommonColor: uncommonColor,
          rarityRareColor: rareColor,
          rarityEpicColor: epicColor,
          rarityLegendaryColor: legendaryColor,
        ),
        size: Size.infinite,
        isComplex: true,
        // 애니메이션 중일 때만 willChange 활성화
        willChange: isAnimating,
      ),
    );
  }
}
