//
//  BeadRoadView.swift
//  Baccarat
//
//  The Bead Road (also called "Bead Plate" or "Cube Road") shows all results in a simple grid.
//  Results fill top to bottom, then left to right.
//

import SwiftUI
import CasinoKit

/// Displays the Bead Road - a simple grid of all results in order.
/// Results fill columns top-to-bottom, then move right.
struct BeadRoadView: View {
    /// The round results to display.
    let results: [RoundResult]
    
    /// Cell size for the dots.
    var cellSize: CGFloat = Design.RoadMap.bigRoadCellSize
    
    /// Maximum number of rows before wrapping.
    var maxRows: Int = Design.RoadMap.maxRows
    
    // MARK: - Computed Properties
    
    /// Results organized into columns.
    private var columns: [[RoundResult]] {
        guard !results.isEmpty else { return [] }
        
        var cols: [[RoundResult]] = []
        var currentCol: [RoundResult] = []
        
        for result in results {
            currentCol.append(result)
            if currentCol.count >= maxRows {
                cols.append(currentCol)
                currentCol = []
            }
        }
        
        // Add remaining results as final column
        if !currentCol.isEmpty {
            cols.append(currentCol)
        }
        
        return cols
    }
    
    // MARK: - Body
    
    var body: some View {
        ScrollViewReader { proxy in
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(alignment: .top, spacing: Design.RoadMap.cellSpacing) {
                    ForEach(Array(columns.enumerated()), id: \.offset) { columnIndex, column in
                        columnView(for: column, index: columnIndex)
                    }
                    
                    // Invisible anchor for auto-scroll
                    Color.clear
                        .frame(width: 1, height: 1)
                        .id("end")
                }
                .padding(Design.Spacing.small)
            }
            .onChange(of: results.count) {
                withAnimation {
                    proxy.scrollTo("end", anchor: .trailing)
                }
            }
        }
        .background(
            RoundedRectangle(cornerRadius: Design.CornerRadius.medium)
                .fill(Color.black.opacity(Design.Opacity.light))
        )
        .accessibilityElement(children: .combine)
        .accessibilityLabel(accessibilityLabel)
    }
    
    // MARK: - Private Views
    
    @ViewBuilder
    private func columnView(for column: [RoundResult], index: Int) -> some View {
        VStack(spacing: Design.RoadMap.cellSpacing) {
            ForEach(Array(column.enumerated()), id: \.offset) { rowIndex, result in
                BeadRoadCell(
                    result: result,
                    size: cellSize
                )
                .id("\(index)-\(rowIndex)")
            }
            
            // Fill remaining space for consistent column height
            if column.count < maxRows {
                ForEach(0..<(maxRows - column.count), id: \.self) { _ in
                    Color.clear
                        .frame(width: cellSize, height: cellSize)
                }
            }
        }
    }
    
    // MARK: - Accessibility
    
    private var accessibilityLabel: String {
        if results.isEmpty {
            return String(localized: "Bead Road: No results yet")
        }
        
        let playerWins = results.filter { $0.result == .playerWins }.count
        let bankerWins = results.filter { $0.result == .bankerWins }.count
        let ties = results.filter { $0.result == .tie }.count
        
        return String(localized: "Bead Road: \(results.count) results. Player \(playerWins), Banker \(bankerWins), Ties \(ties)")
    }
}

// MARK: - Bead Road Cell

/// A single cell in the Bead Road display.
/// Shows filled circles with P/B/T labels.
struct BeadRoadCell: View {
    let result: RoundResult
    var size: CGFloat = Design.RoadMap.bigRoadCellSize
    
    private var color: Color {
        result.result.color
    }
    
    private var label: String {
        switch result.result {
        case .playerWins: return "P"
        case .bankerWins: return "B"
        case .tie: return "T"
        }
    }
    
    private var markerSize: CGFloat {
        size * 0.25
    }
    
    var body: some View {
        ZStack {
            // Filled circle
            Circle()
                .fill(color)
                .frame(width: size, height: size)
            
            // Border
            Circle()
                .strokeBorder(Color.white.opacity(Design.Opacity.light), lineWidth: Design.LineWidth.thin)
                .frame(width: size, height: size)
            
            // Label
            Text(label)
                .font(.system(size: size * 0.45, weight: .bold))
                .foregroundStyle(.white)
            
            // Pair marker (bottom-left)
            if result.hasPair {
                Circle()
                    .fill(Color.yellow)
                    .frame(width: markerSize, height: markerSize)
                    .overlay(
                        Circle()
                            .strokeBorder(Color.white, lineWidth: Design.LineWidth.thin)
                    )
                    .offset(x: -size * 0.35, y: size * 0.35)
            }
            
            // Natural marker (top-right star)
            if result.isNatural {
                Image(systemName: "star.fill")
                    .font(.system(size: markerSize))
                    .foregroundStyle(.yellow)
                    .offset(x: size * 0.35, y: -size * 0.35)
            }
        }
        .accessibilityElement(children: .ignore)
        .accessibilityLabel(cellAccessibilityLabel)
    }
    
    private var cellAccessibilityLabel: String {
        var label: String
        switch result.result {
        case .playerWins: label = String(localized: "Player win")
        case .bankerWins: label = String(localized: "Banker win")
        case .tie: label = String(localized: "Tie")
        }
        
        if result.isNatural {
            label += ", natural"
        }
        if result.hasPair {
            label += ", pair"
        }
        
        return label
    }
}

// MARK: - Preview

#Preview("Bead Road") {
    ZStack {
        Color.Table.preview
            .ignoresSafeArea()
        
        BeadRoadView(
            results: [
                RoundResult(result: .playerWins, playerValue: 8, bankerValue: 6, playerPair: true),
                RoundResult(result: .playerWins, playerValue: 7, bankerValue: 5),
                RoundResult(result: .bankerWins, playerValue: 4, bankerValue: 7),
                RoundResult(result: .bankerWins, playerValue: 3, bankerValue: 8),
                RoundResult(result: .bankerWins, playerValue: 2, bankerValue: 9, bankerPair: true),
                RoundResult(result: .tie, playerValue: 5, bankerValue: 5),
                RoundResult(result: .playerWins, playerValue: 9, bankerValue: 3),
                RoundResult(result: .playerWins, playerValue: 8, bankerValue: 2),
                RoundResult(result: .bankerWins, playerValue: 4, bankerValue: 6),
                RoundResult(result: .playerWins, playerValue: 7, bankerValue: 4, playerPair: true),
                RoundResult(result: .tie, playerValue: 6, bankerValue: 6),
                RoundResult(result: .bankerWins, playerValue: 1, bankerValue: 8)
            ]
        )
        .frame(height: Design.RoadMap.containerHeight)
        .padding()
    }
}
