//
//  ResultBannerView.swift
//  Blackjack
//
//  Displays the result of a round with breakdown.
//  Uses the shared ResultBannerView from CasinoKit.
//

import SwiftUI
import CasinoKit

/// Result banner for Blackjack using the shared CasinoKit component.
struct ResultBannerView: View {
    let result: RoundResult
    let currentBalance: Int
    let minBet: Int
    let onNewRound: () -> Void
    let onPlayAgain: () -> Void
    
    // MARK: - Computed
    
    /// Overall result text based on total winnings
    private var overallResultText: String {
        if result.totalWinnings > 0 {
            return String(localized: "WIN!")
        } else if result.totalWinnings < 0 {
            return String(localized: "LOSE")
        } else {
            return String(localized: "PUSH")
        }
    }
    
    /// Color based on overall result
    private var overallResultColor: Color {
        if result.totalWinnings > 0 { return .green }
        if result.totalWinnings < 0 { return .red }
        return .blue
    }
    
    var body: some View {
        CasinoResultBannerView(
            resultText: overallResultText,
            resultColor: overallResultColor,
            totalWinnings: result.totalWinnings,
            currentBalance: currentBalance,
            minBet: minBet,
            breakdownContent: {
                ResultBreakdownCard {
                    // Hand results
                    ForEach(result.handResults.indices, id: \.self) { index in
                        let handResult = result.handResults[index]
                        let handWinnings = index < result.handWinnings.count ? result.handWinnings[index] : nil
                        let handLabel = result.handResults.count > 1
                            ? String(localized: "Hand \(index + 1)")
                            : String(localized: "Main Hand")
                        let showAmount = result.hadSplit && handWinnings != nil
                        
                        HandResultRow(
                            label: handLabel,
                            result: handResult,
                            amount: showAmount ? handWinnings : nil
                        )
                    }
                    
                    // Insurance result
                    if let insuranceResult = result.insuranceResult {
                        let showInsAmount = result.insuranceWinnings != 0
                        HandResultRow(
                            label: String(localized: "Insurance"),
                            result: insuranceResult,
                            amount: showInsAmount ? result.insuranceWinnings : nil
                        )
                    }
                    
                    // Side bet results
                    if let ppResult = result.perfectPairsResult {
                        SideBetResultRow(
                            label: String(localized: "Perfect Pairs"),
                            resultText: ppResult.displayName,
                            isWin: ppResult.isWin,
                            amount: result.perfectPairsWinnings
                        )
                    }
                    
                    if let topResult = result.twentyOnePlusThreeResult {
                        SideBetResultRow(
                            label: String(localized: "21+3"),
                            resultText: topResult.displayName,
                            isWin: topResult.isWin,
                            amount: result.twentyOnePlusThreeWinnings
                        )
                    }
                }
            },
            onNewRound: onNewRound,
            onPlayAgain: onPlayAgain
        )
    }
}

// MARK: - Hand Result Row

/// Row displaying a single hand result with optional amount.
private struct HandResultRow: View {
    let label: String
    let result: HandResult
    var amount: Int? = nil
    
    @ScaledMetric(relativeTo: .body) private var fontSize: CGFloat = Design.BaseFontSize.medium
    
    private var statusIcon: String {
        switch result {
        case .blackjack, .win, .insuranceWin:
            return "checkmark.circle.fill"
        case .lose, .bust, .insuranceLose:
            return "xmark.circle.fill"
        case .push:
            return "arrow.left.arrow.right.circle.fill"
        case .surrender:
            return "flag.circle.fill"
        }
    }
    
    private var amountText: String? {
        guard let amount = amount else { return nil }
        if amount > 0 {
            return "+\(amount)"
        } else if amount < 0 {
            return "\(amount)"
        } else {
            return nil
        }
    }
    
    private var amountColor: Color {
        guard let amount = amount else { return .white }
        if amount > 0 { return .green }
        if amount < 0 { return .red }
        return .blue
    }
    
    var body: some View {
        HStack(spacing: Design.Spacing.small) {
            // Status icon
            Image(systemName: statusIcon)
                .font(.system(size: fontSize))
                .foregroundStyle(result.color)
            
            // Label
            Text(label)
                .font(.system(size: fontSize, weight: .medium))
                .foregroundStyle(.white.opacity(Design.Opacity.heavy))
            
            Spacer()
            
            // Amount (if provided)
            if let amountText = amountText {
                Text(amountText)
                    .font(.system(size: fontSize, weight: .semibold, design: .rounded))
                    .foregroundStyle(amountColor)
            }
            
            // Result text
            Text(result.displayText)
                .font(.system(size: fontSize + 2, weight: .bold))
                .foregroundStyle(result.color)
                .lineLimit(1)
                .minimumScaleFactor(Design.MinScaleFactor.comfortable)
        }
    }
}

// MARK: - Side Bet Result Row

/// Row displaying a side bet result.
private struct SideBetResultRow: View {
    let label: String
    let resultText: String
    let isWin: Bool
    let amount: Int
    
    @ScaledMetric(relativeTo: .body) private var fontSize: CGFloat = Design.BaseFontSize.medium
    
    private var statusIcon: String {
        isWin ? "checkmark.circle.fill" : "xmark.circle.fill"
    }
    
    private var amountText: String {
        if amount > 0 {
            return "+\(amount)"
        } else if amount < 0 {
            return "\(amount)"
        } else {
            return "$0"
        }
    }
    
    private var amountColor: Color {
        if amount > 0 { return .green }
        if amount < 0 { return .red }
        return .blue
    }
    
    private var resultColor: Color {
        isWin ? .green : .red
    }
    
    var body: some View {
        HStack(spacing: Design.Spacing.small) {
            // Status icon
            Image(systemName: statusIcon)
                .font(.system(size: fontSize))
                .foregroundStyle(resultColor)
            
            // Label
            Text(label)
                .font(.system(size: fontSize, weight: .medium))
                .foregroundStyle(.white.opacity(Design.Opacity.heavy))
            
            Spacer()
            
            // Amount
            Text(amountText)
                .font(.system(size: fontSize, weight: .semibold, design: .rounded))
                .foregroundStyle(amountColor)
            
            // Result text
            Text(resultText)
                .font(.system(size: fontSize + 2, weight: .bold))
                .foregroundStyle(resultColor)
                .lineLimit(1)
                .minimumScaleFactor(Design.MinScaleFactor.comfortable)
        }
    }
}

// MARK: - Previews

#Preview("Single Hand") {
    ResultBannerView(
        result: RoundResult(
            handResults: [.blackjack],
            handWinnings: [150],
            insuranceResult: nil,
            insuranceWinnings: 0,
            totalWinnings: 150,
            wasBlackjack: true
        ),
        currentBalance: 10150,
        minBet: 10,
        onNewRound: {},
        onPlayAgain: {}
    )
}

#Preview("Multiple Split Hands") {
    ResultBannerView(
        result: RoundResult(
            handResults: [.bust, .win, .push],
            handWinnings: [-100, 100, 0],
            insuranceResult: nil,
            insuranceWinnings: 0,
            totalWinnings: 0,
            wasBlackjack: false
        ),
        currentBalance: 1000,
        minBet: 10,
        onNewRound: {},
        onPlayAgain: {}
    )
}

#Preview("Split with Insurance") {
    ResultBannerView(
        result: RoundResult(
            handResults: [.lose, .win],
            handWinnings: [-100, 200],
            insuranceResult: .insuranceWin,
            insuranceWinnings: 100,
            totalWinnings: 200,
            wasBlackjack: false
        ),
        currentBalance: 1200,
        minBet: 10,
        onNewRound: {},
        onPlayAgain: {}
    )
}

#Preview("With Side Bets") {
    ResultBannerView(
        result: RoundResult(
            handResults: [.win],
            handWinnings: [100],
            insuranceResult: nil,
            insuranceWinnings: 0,
            perfectPairsResult: .coloredPair,
            perfectPairsWinnings: 300,
            twentyOnePlusThreeResult: .nothing,
            twentyOnePlusThreeWinnings: -25,
            totalWinnings: 375,
            wasBlackjack: false
        ),
        currentBalance: 1375,
        minBet: 10,
        onNewRound: {},
        onPlayAgain: {}
    )
}

#Preview("Game Over") {
    ResultBannerView(
        result: RoundResult(
            handResults: [.bust],
            handWinnings: [-100],
            insuranceResult: nil,
            insuranceWinnings: 0,
            totalWinnings: -100,
            wasBlackjack: false
        ),
        currentBalance: 0,
        minBet: 10,
        onNewRound: {},
        onPlayAgain: {}
    )
}
