//
//  SpeedButtonsView.swift
//  lichunWebsocket
//
//  Game speed control buttons with cozy styling
//

import SwiftUI

struct SpeedButtonsView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    let buttonSpeedValues = [10000, 1000, 500, 50, 20, 1]

    /// Whether the game is currently paused (speed >= 10000)
    var isPaused: Bool {
        webSocketService.player.gameSpeed >= 10000
    }

    var speedLevel: Int {
        if isPaused {
            return 0 // No icons filled when paused
        }
        if let index = buttonSpeedValues.firstIndex(of: webSocketService.player.gameSpeed) {
            return index + 1
        }
        // For speeds not in the array, estimate based on value
        let speed = webSocketService.player.gameSpeed
        if speed <= 1 { return 6 }
        if speed <= 20 { return 5 }
        if speed <= 50 { return 4 }
        if speed <= 500 { return 3 }
        if speed <= 1000 { return 2 }
        return 1
    }

    var body: some View {
        HStack(spacing: AppSpacing.md) {
            // Decrease speed button
            CozyIconButton(
                icon: "minus",
                color: AppColors.secondary,
                size: 36
            ) {
                webSocketService.sendMessage(message: WebSocketCommands.speed("-"))
            }

            // Visual speed indicator with pause state
            HStack(spacing: 4) {
                if isPaused {
                    // Show pause indicator
                    Image(systemName: "pause.fill")
                        .font(.system(size: 14, weight: .semibold))
                        .foregroundColor(AppColors.warning)
                    Text("PAUSED")
                        .font(.system(size: 10, weight: .bold))
                        .foregroundColor(AppColors.warning)
                } else {
                    // Normal speed indicator
                    ForEach(0..<6) { index in
                        Image(systemName: index < speedLevel ? "play.fill" : "play")
                            .font(.system(size: 12))
                            .foregroundColor(index < speedLevel ? AppColors.primary : AppColors.disabledText.opacity(0.5))
                    }
                }
            }
            .padding(.horizontal, 8)
            .padding(.vertical, 6)
            .background(isPaused ? AppColors.warning.opacity(0.15) : AppColors.surfaceSubtle)
            .cornerRadius(AppSpacing.smallCornerRadius)
            .animation(.easeInOut(duration: 0.2), value: isPaused)

            // Increase speed button
            CozyIconButton(
                icon: "plus",
                color: AppColors.secondary,
                size: 36
            ) {
                webSocketService.sendMessage(message: WebSocketCommands.speed("+"))
            }
        }
        .padding(.vertical, AppSpacing.sm)
    }
}

// MARK: - Preview
// Preview removed - requires backend connection
