// packages/feature_game_spider/lib/widgets/tableau_pile_widget.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/spider_card.dart';
import '../controllers/spider_game_controller.dart';
import 'card_widget.dart';

class TableauPileWidget extends StatelessWidget {
  final int pileIndex;
  final List<SpiderCard> cards;
  final double cardWidth;
  final double cardHeight;
  final double cardOverlap;

  const TableauPileWidget({
    super.key,
    required this.pileIndex,
    required this.cards,
    required this.cardWidth,
    required this.cardHeight,
    required this.cardOverlap,
  });

  @override
  Widget build(BuildContext context) {
    // 🔽 [수정] 'context.watch'를 사용하여 컨트롤러의 애니메이션 상태를 실시간으로 감지
    final controller = context.watch<SpiderGameController>();

    return DragTarget<List<SpiderCard>>(
      onWillAccept: (draggedCards) {
        if (draggedCards == null) return false;
        
        if (controller.cardsToDealAnimate.isNotEmpty || 
            controller.cardsToAnimateStack.isNotEmpty) {
          return false;
        }
        
        return controller.isValidMove(draggedCards, pileIndex);
      },
      onAccept: (draggedCards) {
        controller.onCardsDropped(draggedCards, pileIndex);
      },
      builder: (context, candidateData, rejectedData) {
        
        final bool isAnimating = controller.cardsToDealAnimate.isNotEmpty ||
                                 controller.cardsToAnimateStack.isNotEmpty;
        final bool isHighlighted = candidateData.isNotEmpty && !isAnimating;

        // 🔽 [로그 추가] "초록 선"의 원인을 추적합니다.
        // (하이라이트되거나, 애니메이션 중이거나, 드래그가 감지되면 로그 출력)
        if (candidateData.isNotEmpty || isAnimating || isHighlighted) {
          debugPrint("[LOG] TableauPileWidget (Pile $pileIndex): "
              "candidateData.isNotEmpty = ${candidateData.isNotEmpty}, "
              "isAnimating = $isAnimating, "
              "==> isHighlighted = $isHighlighted");
        }

        return Container(
          width: cardWidth,
          constraints: BoxConstraints(
            minHeight: cardHeight,
          ),
          decoration: BoxDecoration(
            color: isHighlighted
                ? Colors.green.withOpacity(0.3)
                : (cards.isEmpty ? Colors.black.withOpacity(0.1) : null),
            borderRadius: BorderRadius.circular(cardWidth * 0.08),
          ),
          child: Stack(
            children: List.generate(cards.length, (index) {
              final card = cards[index];
              return Positioned(
                top: index * cardOverlap,
                left: 0,
                child: CardWidget(
                  card: card,
                  width: cardWidth,
                  height: cardHeight,
                ),
              );
            }),
          ),
        );
      },
    );
  }
}