//
//  ChipStackView.swift
//  CasinoKit
//
//  A visual stack of chips representing a bet amount.
//

import SwiftUI

/// A stack of chips representing a total bet amount.
public struct ChipStackView: View {
    let amount: Int
    let theme: any CasinoTheme
    
    public init(amount: Int, theme: any CasinoTheme = DefaultCasinoTheme()) {
        self.amount = amount
        self.theme = theme
    }
    
    // MARK: - Layout Constants
    
    private let chipSize: CGFloat = 30
    private let stackOffset: CGFloat = -8
    private let maxChipsToShow = 5
    
    /// Break down the amount into chip denominations.
    private var chipBreakdown: [ChipDenomination] {
        var remaining = amount
        var chips: [ChipDenomination] = []
        
        // Start from highest denomination
        let denominations = ChipDenomination.allCases.reversed()
        
        for denomination in denominations {
            while remaining >= denomination.rawValue && chips.count < maxChipsToShow {
                chips.append(denomination)
                remaining -= denomination.rawValue
            }
        }
        
        return chips
    }
    
    public var body: some View {
        ZStack {
            ForEach(chipBreakdown.indices, id: \.self) { index in
                ChipView(
                    denomination: chipBreakdown[index],
                    size: chipSize,
                    isSelected: false,
                    theme: theme
                )
                .offset(y: CGFloat(index) * stackOffset)
            }
        }
        .accessibilityElement(children: .ignore)
        .accessibilityLabel(String(localized: "\(amount) dollar bet", bundle: .module))
    }
}

/// A simplified chip for displaying bets on the table.
public struct ChipOnTableView: View {
    let amount: Int
    let showMax: Bool
    let size: CGFloat
    let theme: any CasinoTheme
    
    public init(
        amount: Int,
        showMax: Bool = false,
        size: CGFloat = 36,
        theme: any CasinoTheme = DefaultCasinoTheme()
    ) {
        self.amount = amount
        self.showMax = showMax
        self.size = size
        self.theme = theme
    }
    
    // MARK: - Layout Constants (relative to size)
    
    private var chipSize: CGFloat { size }
    private var innerRingSize: CGFloat { size * 0.72 }  // 26/36
    private var gradientEndRadius: CGFloat { size * 0.56 }  // 20/36
    private var maxBadgeFontSize: CGFloat { size * 0.22 }  // 8/36
    private var maxBadgeOffsetX: CGFloat { size * 0.17 }  // 6/36
    private var maxBadgeOffsetY: CGFloat { size * -0.11 }  // -4/36
    
    // MARK: - Computed Properties
    
    private var chipColor: Color {
        // Find the closest denomination for coloring
        let denomination = ChipDenomination.allCases.last { $0.rawValue <= amount } ?? .one
        return theme.chipColors(for: denomination).primary
    }
    
    private var displayText: String {
        amount >= 1000 ? "\(amount / 1000)K" : "\(amount)"
    }
    
    /// Text font size scales with chip size
    private var textFontSize: CGFloat {
        let baseFontSize = amount >= 1000 ? size * 0.25 : size * 0.30
        return baseFontSize
    }
    
    // MARK: - Accessibility
    
    private var accessibilityDescription: String {
        let base = String(localized: "\(amount) dollar bet", bundle: .module)
        if showMax {
            return base + ", " + String(localized: "maximum bet", bundle: .module)
        }
        return base
    }
    
    // MARK: - Body
    
    public var body: some View {
        ZStack {
            Circle()
                .fill(
                    RadialGradient(
                        colors: [chipColor.opacity(CasinoDesign.Opacity.nearOpaque), chipColor],
                        center: .topLeading,
                        startRadius: 0,
                        endRadius: gradientEndRadius
                    )
                )
                .frame(width: chipSize, height: chipSize)
            
            Circle()
                .strokeBorder(
                    Color.white.opacity(CasinoDesign.Opacity.heavy),
                    lineWidth: CasinoDesign.LineWidth.medium
                )
                .frame(width: chipSize, height: chipSize)
            
            Circle()
                .strokeBorder(
                    Color.white.opacity(CasinoDesign.Opacity.light),
                    lineWidth: CasinoDesign.LineWidth.thin
                )
                .frame(width: innerRingSize, height: innerRingSize)
            
            Text(displayText)
                .font(.system(size: textFontSize, weight: .bold))
                .foregroundStyle(.white)
        }
        .shadow(
            color: .black.opacity(CasinoDesign.Opacity.light),
            radius: CasinoDesign.Shadow.radiusSmall,
            x: CasinoDesign.Shadow.offsetSmall,
            y: CasinoDesign.Shadow.offsetMedium
        )
        .overlay(alignment: .topTrailing) {
            if showMax {
                Text("MAX")
                    .font(.system(size: maxBadgeFontSize, weight: .black))
                    .foregroundStyle(.white)
                    .padding(.horizontal, CasinoDesign.Spacing.xSmall)
                    .padding(.vertical, CasinoDesign.Spacing.xxSmall)
                    .background(
                        Capsule()
                            .fill(Color.red)
                    )
                    .offset(x: maxBadgeOffsetX, y: maxBadgeOffsetY)
                    .accessibilityHidden(true) // Included in parent label
            }
        }
        .accessibilityLabel(accessibilityDescription)
    }
}

#Preview {
    ZStack {
        Color(red: 0.05, green: 0.35, blue: 0.15)
            .ignoresSafeArea()
        
        HStack(spacing: CasinoDesign.Spacing.xxLarge) {
            ChipStackView(amount: 1750)
            ChipOnTableView(amount: 500)
            ChipOnTableView(amount: 5000, showMax: true)
        }
    }
}

