//
//  GameControlsCard.swift
//  lichunWebsocket
//
//  Game speed and action controls
//

import SwiftUI

struct GameControlsCard: View {
    @EnvironmentObject var webSocketService: WebSocketService

    // T014: guard the destructive Restart behind an explicit confirmation.
    @State private var showRestartConfirm = false

    let buttonSpeedValues = Constants.GameSpeed.allLevels

    /// How many of the 6 pips are lit. The pip meter and the named label
    /// (Slow / Normal / Fast / Instant) describe the SAME underlying scale.
    var speedLevel: Int {
        if let index = buttonSpeedValues.firstIndex(of: webSocketService.player.gameSpeed) {
            return index + 1
        }
        return 0
    }

    /// Unified named speed (single source of truth in Constants.GameSpeed).
    private var speedName: String {
        Constants.GameSpeed.label(for: webSocketService.player.gameSpeed)
    }

    var body: some View {
        BaseCard {
            VStack(spacing: AppSpacing.md) {
                // PRIMARY CONTROL: time speed. This is the main thing players
                // touch on Home (the game auto-starts, so there is no Start).
                VStack(spacing: AppSpacing.sm) {
                    HStack {
                        Text("Speed of Time")
                            .font(.appBodyBold)
                            .foregroundColor(AppColors.primaryText)
                        Spacer()
                        Text(speedName)
                            .font(.appCaptionBold)
                            .foregroundColor(AppColors.primary)
                            .padding(.horizontal, AppSpacing.sm)
                            .padding(.vertical, AppSpacing.xxs)
                            .background(AppColors.primary.opacity(0.12))
                            .cornerRadius(AppSpacing.smallCornerRadius)
                            .contentTransition(.opacity)
                            .animation(.easeInOut(duration: 0.2), value: speedName)
                    }

                    HStack(spacing: AppSpacing.sm) {
                        CozyIconButton(icon: "minus", color: AppColors.secondary, size: 44) {
                            webSocketService.sendMessage(message: WebSocketCommands.speed("-"))
                        }
                        .accessibilityLabel("Slow down time")

                        // Visual speed meter — same scale as the named label.
                        HStack(spacing: 5) {
                            ForEach(0..<6) { index in
                                Image(systemName: index < speedLevel ? "play.fill" : "play")
                                    .font(.system(size: 14))
                                    .foregroundColor(index < speedLevel ? AppColors.primary : AppColors.disabledText.opacity(0.5))
                            }
                        }
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 10)
                        .background(AppColors.surfaceSubtle)
                        .cornerRadius(AppSpacing.smallCornerRadius)
                        .accessibilityElement()
                        .accessibilityLabel("Speed \(speedName)")

                        CozyIconButton(icon: "plus", color: AppColors.secondary, size: 44) {
                            webSocketService.sendMessage(message: WebSocketCommands.speed("+"))
                        }
                        .accessibilityLabel("Speed up time")
                    }
                }

                Divider()
                    .background(AppColors.disabledText.opacity(0.3))

                // Demoted, guarded life action. Restart ends the current life,
                // so it sits below the fold and asks for confirmation first.
                SecondaryButton(
                    title: "Start a New Life",
                    action: {
                        showRestartConfirm = true
                    },
                    color: AppColors.warning
                )
                .accessibilityHint("Ends your current life and begins a new one")
            }
        }
        .confirmationDialog(
            "Start a new life?",
            isPresented: $showRestartConfirm,
            titleVisibility: .visible
        ) {
            Button("Start New Life", role: .destructive) {
                hapticNotification(type: .warning)
                webSocketService.sendMessage(message: WebSocketCommands.command("restart"))
            }
            Button("Keep Playing", role: .cancel) {}
        } message: {
            Text("This ends your current life and starts over from birth. Your current character's progress will be lost.")
        }
    }
}

// MARK: - Preview
#Preview {
    let service = WebSocketService(urlSession: URLSession.shared, delegateQueue: OperationQueue())
    GameControlsCard()
        .environmentObject(service)
        .padding()
        .background(AppColors.background)
}
