//
//  ConfettiView.swift
//  CasinoKit
//
//  A reusable confetti celebration effect for wins.
//

import SwiftUI

/// A single confetti particle that falls and rotates.
public struct ConfettiPiece: View {
    let color: Color
    let containerSize: CGSize
    
    @State private var position: CGPoint = .zero
    @State private var rotation: Double = 0
    @State private var opacity: Double = 1
    
    private let confettiWidth: CGFloat = 8
    private let confettiHeight: CGFloat = 12
    
    public init(color: Color, containerSize: CGSize) {
        self.color = color
        self.containerSize = containerSize
    }
    
    public var body: some View {
        Rectangle()
            .fill(color)
            .frame(width: confettiWidth, height: confettiHeight)
            .rotationEffect(.degrees(rotation))
            .position(position)
            .opacity(opacity)
            .onAppear {
                let startX = Double.random(in: 0...containerSize.width)
                position = CGPoint(x: startX, y: -20)
                
                withAnimation(.easeIn(duration: Double.random(in: 2...4))) {
                    position = CGPoint(
                        x: startX + Double.random(in: -100...100),
                        y: containerSize.height + 50
                    )
                    rotation = Double.random(in: 360...1080)
                    opacity = 0
                }
            }
    }
}

/// A confetti celebration overlay for wins.
public struct ConfettiView: View {
    /// The colors to use for confetti pieces.
    public let colors: [Color]
    
    /// The number of confetti pieces to show.
    public let count: Int
    
    /// Creates a confetti view with custom colors.
    /// - Parameters:
    ///   - colors: The colors to randomly assign to confetti pieces.
    ///   - count: The number of confetti pieces (default: 50).
    public init(
        colors: [Color] = [.red, .blue, .green, .yellow, .orange, .purple, .pink],
        count: Int = 50
    ) {
        self.colors = colors
        self.count = count
    }
    
    public var body: some View {
        GeometryReader { geometry in
            ZStack {
                ForEach(0..<count, id: \.self) { _ in
                    ConfettiPiece(
                        color: colors.randomElement() ?? .yellow,
                        containerSize: geometry.size
                    )
                }
            }
        }
        .ignoresSafeArea()
        .allowsHitTesting(false)
        .accessibilityHidden(true)
    }
}

#Preview {
    ZStack {
        Color.black.ignoresSafeArea()
        ConfettiView()
    }
}

