//
//  DealerHandView.swift
//  Blackjack
//
//  Displays the dealer's hand with cards and value.
//

import SwiftUI
import CasinoKit

struct DealerHandView: View {
    let hand: BlackjackHand
    let showHoleCard: Bool
    let showCardCount: Bool
    let showAnimations: Bool
    let dealingSpeed: Double
    let cardWidth: CGFloat
    let cardSpacing: CGFloat
    
    @ScaledMetric(relativeTo: .headline) private var labelFontSize: CGFloat = Design.Size.handLabelFontSize
    @ScaledMetric(relativeTo: .headline) private var badgeHeight: CGFloat = CasinoDesign.Size.valueBadge
    
    /// Scaled animation duration based on dealing speed.
    private var animationDuration: Double {
        Design.Animation.springDuration * dealingSpeed
    }
    
    var body: some View {
        
        VStack(spacing: Design.Spacing.small) {
            // Label and value - fixed height prevents vertical layout shift
            HStack(spacing: Design.Spacing.small) {
                Text(String(localized: "DEALER"))
                    .font(.system(size: labelFontSize, weight: .bold, design: .rounded))
                    .foregroundStyle(.white)
                
                // Badge animates in when cards are dealt
                if !hand.cards.isEmpty {
                    if showHoleCard {
                        // All cards visible - show total hand value
                        ValueBadge(value: hand.value, color: Color.Hand.dealer)
                            .transition(.scale.combined(with: .opacity))
                    } else {
                        // Hole card hidden - show only the first (face-up) card's value
                        ValueBadge(value: hand.cards[0].blackjackValue, color: Color.Hand.dealer)
                            .transition(.scale.combined(with: .opacity))
                    }
                }
            }
            .frame(minHeight: badgeHeight) // Reserve consistent height
            .animation(.spring(duration: Design.Animation.springDuration), value: hand.cards.isEmpty)
            // Cards with result badge overlay (overlay prevents height change)
            HStack(spacing: hand.cards.isEmpty ? Design.Spacing.small : cardSpacing) {
                if hand.cards.isEmpty {
                    CardPlaceholderView(width: cardWidth)
                    CardPlaceholderView(width: cardWidth)
                } else {
                    ForEach(hand.cards.indices, id: \.self) { index in
                        let isFaceUp = index == 0 || showHoleCard
                        CardView(
                            card: hand.cards[index],
                            isFaceUp: isFaceUp,
                            cardWidth: cardWidth
                        )
                        .overlay(alignment: .bottomLeading) {
                            if showCardCount && isFaceUp {
                                HiLoCountBadge(card: hand.cards[index])
                            }
                        }
                        .zIndex(Double(index))
                        .transition(
                            showAnimations
                            ? .asymmetric(
                                insertion: .offset(x: Design.DealAnimation.dealerOffsetX, y: Design.DealAnimation.dealerOffsetY)
                                    .combined(with: .opacity)
                                    .combined(with: .scale(scale: Design.Scale.slightShrink)),
                                removal: .scale.combined(with: .opacity)
                            )
                            : .identity
                        )
                    }
                    
                    // Show placeholder for second card in European mode (no hole card)
                    if hand.cards.count == 1 && !showHoleCard {
                        CardPlaceholderView(width: cardWidth)
                            .opacity(Design.Opacity.medium)
                    }
                }
            }
            .animation(
                showAnimations
                ? .spring(duration: animationDuration, bounce: Design.Animation.springBounce)
                : .none,
                value: hand.cards.count
            )
            .overlay(alignment: .bottom) {
                // Result badge - overlayed so it doesn't add height to the view
                if let result = hand.cards.count >= 2 && showHoleCard ? handResultText : nil {
                    Text(result)
                        .font(.system(size: labelFontSize, weight: .black))
                        .foregroundStyle(.white)
                        .padding(.horizontal, Design.Spacing.medium)
                        .padding(.vertical, Design.Spacing.xSmall)
                        .background(
                            Capsule()
                                .fill(handResultColor)
                                .shadow(color: .black.opacity(Design.Opacity.medium), radius: Design.Shadow.radiusMedium)
                        )
                        .offset(y: Design.Spacing.xLarge)  // Position below cards
                        .transition(.scale.combined(with: .opacity))
                }
            }
        }
        .accessibilityElement(children: .ignore)
        .accessibilityLabel(dealerAccessibilityLabel)
    }
    
    // MARK: - Computed Properties
    
    private var handResultText: String? {
        if hand.isBlackjack {
            return String(localized: "BLACKJACK")
        }
        if hand.isBusted {
            return String(localized: "BUST")
        }
        return nil
    }
    
    private var handResultColor: Color {
        if hand.isBlackjack { return .yellow }
        if hand.isBusted { return .green }  // Good for player
        return .white
    }
    
    private var dealerAccessibilityLabel: String {
        if hand.cards.isEmpty {
            return String(localized: "Dealer: No cards")
        }
        let visibleCards = showHoleCard ? hand.cards : [hand.cards[0]]
        let cardsDescription = visibleCards.map { $0.accessibilityDescription }.joined(separator: ", ")
        return String(localized: "Dealer: \(cardsDescription). Value: \(showHoleCard ? String(hand.value) : "hidden")")
    }
}

#Preview("Empty Hand") {
    ZStack {
        Color.Table.felt.ignoresSafeArea()
        DealerHandView(
            hand: BlackjackHand(),
            showHoleCard: false,
            showCardCount: false,
            showAnimations: true,
            dealingSpeed: 1.0,
            cardWidth: 60,
            cardSpacing: -20
        )
    }
}

#Preview("Two Cards - Hole Hidden") {
    ZStack {
        Color.Table.felt.ignoresSafeArea()
        DealerHandView(
            hand: BlackjackHand(cards: [
                Card(suit: .spades, rank: .ace),
                Card(suit: .hearts, rank: .king)
            ]),
            showHoleCard: false,
            showCardCount: false,
            showAnimations: true,
            dealingSpeed: 1.0,
            cardWidth: 60,
            cardSpacing: -20
        )
    }
}

#Preview("Blackjack - Revealed") {
    ZStack {
        Color.Table.felt.ignoresSafeArea()
        DealerHandView(
            hand: BlackjackHand(cards: [
                Card(suit: .spades, rank: .ace),
                Card(suit: .hearts, rank: .king)
            ]),
            showHoleCard: true,
            showCardCount: true,
            showAnimations: true,
            dealingSpeed: 1.0,
            cardWidth: 60,
            cardSpacing: -20
        )
    }
}

