//
//  TrendBadgeView.swift
//  Baccarat
//
//  Displays streak and trend indicators near betting zones.
//

import SwiftUI
import CasinoKit

/// Displays a streak indicator badge.
/// Shows "B×5" or "P×3" format for streaks.
struct TrendBadgeView: View {
    /// The current streak type (nil if no streak).
    let streakType: GameResult?
    
    /// The streak count.
    let streakCount: Int
    
    /// Minimum streak to display.
    var minimumStreak: Int = 2
    
    /// Whether to animate for hot streaks.
    var animateHotStreak: Bool = true
    
    /// Threshold for "hot" streak animation.
    var hotStreakThreshold: Int = 4
    
    // MARK: - State
    
    @State private var isPulsing = false
    
    // MARK: - Scaled Metrics
    
    @ScaledMetric(relativeTo: .caption) private var fontSize: CGFloat = Design.BaseFontSize.small
    @ScaledMetric(relativeTo: .caption) private var badgeHeight: CGFloat = 24
    @ScaledMetric(relativeTo: .caption) private var horizontalPadding: CGFloat = Design.Spacing.small
    
    // MARK: - Computed Properties
    
    private var shouldDisplay: Bool {
        streakType != nil && streakType != .tie && streakCount >= minimumStreak
    }
    
    private var isHotStreak: Bool {
        streakCount >= hotStreakThreshold
    }
    
    private var badgeColor: Color {
        guard let type = streakType else { return .clear }
        return type == .bankerWins ? .red : .blue
    }
    
    private var badgeText: String {
        guard let type = streakType else { return "" }
        let letter = type == .bankerWins ? "B" : "P"
        return "\(letter)×\(streakCount)"
    }
    
    // MARK: - Body
    
    var body: some View {
        if shouldDisplay {
            badgeContent
                .onAppear {
                    if animateHotStreak && isHotStreak {
                        startPulsing()
                    }
                }
                .onChange(of: streakCount) {
                    if animateHotStreak && isHotStreak {
                        startPulsing()
                    } else {
                        isPulsing = false
                    }
                }
        }
    }
    
    @ViewBuilder
    private var badgeContent: some View {
        HStack(spacing: Design.Spacing.xxSmall) {
            // Streak icon
            Image(systemName: "flame.fill")
                .font(.system(size: fontSize))
                .foregroundStyle(isHotStreak ? .yellow : .white.opacity(Design.Opacity.strong))
            
            // Streak text
            Text(badgeText)
                .font(.system(size: fontSize, weight: .bold, design: .rounded))
                .foregroundStyle(.white)
        }
        .padding(.horizontal, horizontalPadding)
        .frame(height: badgeHeight)
        .background(
            Capsule()
                .fill(badgeColor.opacity(isHotStreak ? 0.9 : 0.7))
        )
        .overlay(
            Capsule()
                .stroke(Color.white.opacity(Design.Opacity.light), lineWidth: Design.LineWidth.thin)
        )
        .scaleEffect(isPulsing ? 1.05 : 1.0)
        .shadow(color: isHotStreak ? badgeColor.opacity(0.5) : .clear, radius: isPulsing ? 8 : 4)
        .accessibilityElement(children: .ignore)
        .accessibilityLabel(accessibilityLabel)
    }
    
    // MARK: - Animation
    
    private func startPulsing() {
        withAnimation(.easeInOut(duration: 0.6).repeatForever(autoreverses: true)) {
            isPulsing = true
        }
    }
    
    // MARK: - Accessibility
    
    private var accessibilityLabel: String {
        guard let type = streakType else { return "" }
        let sideName = type == .bankerWins ? 
            String(localized: "Banker") : String(localized: "Player")
        return String(localized: "\(sideName) streak of \(streakCount)")
    }
}

// MARK: - Compact Trend Summary

/// A compact trend summary for the top bar.
struct CompactTrendView: View {
    /// The current streak type (nil if no streak).
    let streakType: GameResult?
    
    /// The streak count.
    let streakCount: Int
    
    /// Minimum streak to display.
    var minimumStreak: Int = 2
    
    @ScaledMetric(relativeTo: .caption2) private var fontSize: CGFloat = Design.BaseFontSize.xSmall
    
    private var shouldDisplay: Bool {
        streakType != nil && streakType != .tie && streakCount >= minimumStreak
    }
    
    private var textColor: Color {
        guard let type = streakType else { return .white }
        return type == .bankerWins ? .red : .blue
    }
    
    private var displayText: String {
        guard let type = streakType else { return "" }
        let letter = type == .bankerWins ? "B" : "P"
        return "\(letter)×\(streakCount)"
    }
    
    var body: some View {
        if shouldDisplay {
            Text(displayText)
                .font(.system(size: fontSize, weight: .bold, design: .rounded))
                .foregroundStyle(textColor)
                .accessibilityLabel(accessibilityLabel)
        }
    }
    
    private var accessibilityLabel: String {
        guard let type = streakType else { return "" }
        let sideName = type == .bankerWins ? 
            String(localized: "Banker") : String(localized: "Player")
        return String(localized: "\(sideName) streak of \(streakCount)")
    }
}

// MARK: - Previews

#Preview("Trend Badge - Banker Streak") {
    ZStack {
        Color.Table.preview
            .ignoresSafeArea()
        
        VStack(spacing: Design.Spacing.large) {
            TrendBadgeView(
                streakType: .bankerWins,
                streakCount: 3
            )
            
            TrendBadgeView(
                streakType: .bankerWins,
                streakCount: 5
            )
            
            TrendBadgeView(
                streakType: .playerWins,
                streakCount: 4
            )
            
            TrendBadgeView(
                streakType: .playerWins,
                streakCount: 7
            )
        }
    }
}

#Preview("Compact Trend") {
    ZStack {
        Color.Table.preview
            .ignoresSafeArea()
        
        HStack(spacing: Design.Spacing.large) {
            CompactTrendView(
                streakType: .bankerWins,
                streakCount: 4
            )
            
            CompactTrendView(
                streakType: .playerWins,
                streakCount: 3
            )
        }
    }
}
