//
//  ActionButtonsView.swift
//  Blackjack
//
//  Container for game action buttons (betting, player turn).
//

import SwiftUI
import CasinoKit

struct ActionButtonsView: View {
    @Bindable var state: GameState
    
    // Scaled container height - base 60pt, scales with accessibility
    @ScaledMetric(relativeTo: .body) private var containerHeight: CGFloat = 60
    
    var body: some View {
        VStack(spacing: Design.Spacing.small) {
            // Primary actions
            HStack(spacing: Design.Spacing.medium) {
                switch state.currentPhase {
                case .betting:
                    bettingButtons
                        .transition(.opacity.combined(with: .scale(scale: 0.9)))
                case .playerTurn:
                    playerTurnButtons
                        .transition(.opacity.combined(with: .scale(scale: 0.9)))
                case .roundComplete:
                    // Empty - handled by result banner
                    EmptyView()
                default:
                    // Dealing, dealer turn - show nothing
                    EmptyView()
                }
            }
            .animation(.spring(duration: Design.Animation.springDuration), value: state.currentPhase)
        }
        .frame(height: containerHeight)
        .padding(.horizontal, Design.Spacing.large)
    }
    
    // MARK: - Betting Phase Buttons
    
    @ViewBuilder
    private var bettingButtons: some View {
        BettingActionsView(
            hasBet: state.currentBet > 0,
            canDeal: state.canDeal,
            amountNeededForMinimum: state.isBetBelowMinimum ? state.amountNeededForMinimum : nil,
            onClear: { state.clearBet() },
            onDeal: { Task { await state.deal() } }
        )
        .sherpaTag(BlackjackWalkthroughTags.dealButton)
    }
    
    // MARK: - Player Turn Buttons
    
    /// Available player actions based on current game state.
    private var availableActions: [PlayerAction] {
        PlayerAction.allCases.filter { action in
            switch action {
            case .hit: state.canHit
            case .stand: state.canStand
            case .double: state.canDouble
            case .split: state.canSplit
            case .surrender: state.canSurrender
            }
        }
    }
    
    /// Tracks available actions for animation purposes.
    @State private var animatedActions: [PlayerAction] = []
    
    @ViewBuilder
    private var playerTurnButtons: some View {
        HStack(spacing: Design.Spacing.medium) {
            ForEach(animatedActions) { action in
                ActionButton(
                    action.title,
                    style: .custom(action.color)
                ) {
                    Task { await performAction(action) }
                }
                .transition(.scale.combined(with: .opacity))
            }
        }
        .onAppear {
            animatedActions = availableActions
        }
        .onChange(of: availableActions) { _, newActions in
            withAnimation(.spring(duration: Design.Animation.springDuration, bounce: 0.15)) {
                animatedActions = newActions
            }
        }
    }
    
    /// Performs the given player action.
    private func performAction(_ action: PlayerAction) async {
        switch action {
        case .hit: await state.hit()
        case .stand: await state.stand()
        case .double: await state.doubleDown()
        case .split: await state.split()
        case .surrender: await state.surrender()
        }
    }
}

// MARK: - Player Action

/// Represents a player action button during their turn.
private enum PlayerAction: String, CaseIterable, Identifiable {
    case hit
    case stand
    case double
    case split
    case surrender
    
    var id: String { rawValue }
    
    var title: String {
        switch self {
        case .hit: String(localized: "Hit")
        case .stand: String(localized: "Stand")
        case .double: String(localized: "Double")
        case .split: String(localized: "Split")
        case .surrender: String(localized: "Surrender")
        }
    }
    
    var color: Color {
        switch self {
        case .hit: Color.Button.hit
        case .stand: Color.Button.stand
        case .double: Color.Button.doubleDown
        case .split: Color.Button.split
        case .surrender: Color.Button.surrender
        }
    }
}

// MARK: - Previews

#Preview("Betting Phase - No Bet") {
    ZStack {
        Color.Table.felt.ignoresSafeArea()
        ActionButtonsView(state: {
            let state = GameState(settings: GameSettings())
            return state
        }())
    }
}

#Preview("Betting Phase - With Bet") {
    ZStack {
        Color.Table.felt.ignoresSafeArea()
        ActionButtonsView(state: {
            let state = GameState(settings: GameSettings())
            state.placeBet(amount: 100)
            return state
        }())
    }
}

#Preview("Betting Phase - Below Minimum") {
    ZStack {
        Color.Table.felt.ignoresSafeArea()
        ActionButtonsView(state: {
            let state = GameState(settings: GameSettings())
            state.placeBet(amount: 25)
            return state
        }())
    }
}

// MARK: - Player Turn Button Previews

/// Preview helper that shows player turn button layouts without needing real game state.
private struct PlayerTurnButtonsPreview: View {
    let showHit: Bool
    let showStand: Bool
    let showDouble: Bool
    let showSplit: Bool
    let showSurrender: Bool
    
    private let containerHeight: CGFloat = 120
    
    var body: some View {
        ZStack {
            Color.clear
                .frame(height: containerHeight)
            
            // Single row of buttons matching actual game layout
            HStack(spacing: Design.Spacing.medium) {
                if showHit {
                    ActionButton("Hit", style: .custom(Color.Button.hit)) {}
                }
                if showStand {
                    ActionButton("Stand", style: .custom(Color.Button.stand)) {}
                }
                if showDouble {
                    ActionButton("Double", style: .custom(Color.Button.doubleDown)) {}
                }
                if showSplit {
                    ActionButton("Split", style: .custom(Color.Button.split)) {}
                }
                if showSurrender {
                    ActionButton("Surrender", style: .custom(Color.Button.surrender)) {}
                }
            }
        }
        .padding(.horizontal, Design.Spacing.large)
    }
}

#Preview("Player Turn - Hit & Stand Only") {
    ZStack {
        Color.Table.felt.ignoresSafeArea()
        PlayerTurnButtonsPreview(
            showHit: true,
            showStand: true,
            showDouble: false,
            showSplit: false,
            showSurrender: false
        )
    }
}

#Preview("Player Turn - With Double") {
    ZStack {
        Color.Table.felt.ignoresSafeArea()
        PlayerTurnButtonsPreview(
            showHit: true,
            showStand: true,
            showDouble: true,
            showSplit: false,
            showSurrender: false
        )
    }
}

#Preview("Player Turn - With Split") {
    ZStack {
        Color.Table.felt.ignoresSafeArea()
        PlayerTurnButtonsPreview(
            showHit: true,
            showStand: true,
            showDouble: true,
            showSplit: true,
            showSurrender: false
        )
    }
}

#Preview("Player Turn - With Surrender") {
    ZStack {
        Color.Table.felt.ignoresSafeArea()
        PlayerTurnButtonsPreview(
            showHit: true,
            showStand: true,
            showDouble: true,
            showSplit: false,
            showSurrender: true
        )
    }
}

#Preview("Player Turn - All Options") {
    ZStack {
        Color.Table.felt.ignoresSafeArea()
        PlayerTurnButtonsPreview(
            showHit: true,
            showStand: true,
            showDouble: true,
            showSplit: true,
            showSurrender: true
        )
    }
}

#Preview("Player Turn - After Hit (No Double/Split)") {
    ZStack {
        Color.Table.felt.ignoresSafeArea()
        PlayerTurnButtonsPreview(
            showHit: true,
            showStand: true,
            showDouble: false,
            showSplit: false,
            showSurrender: false
        )
    }
}

#Preview("Player Turn - Split Hand (No Resplit)") {
    ZStack {
        Color.Table.felt.ignoresSafeArea()
        PlayerTurnButtonsPreview(
            showHit: true,
            showStand: true,
            showDouble: true,
            showSplit: false,
            showSurrender: false
        )
    }
}

