//
//  RoadMapGridView.swift
//  Baccarat
//
//  A grid-based road map for landscape mode sidebar.
//  Reads columns top-to-bottom, left-to-right (traditional baccarat style).
//

import SwiftUI
import CasinoKit

/// A grid-based road map for the landscape sidebar.
/// Results fill columns from top to bottom, then move right.
/// Rows are calculated dynamically based on available height.
struct RoadMapGridView: View {
    let results: [RoundResult]
    
    /// Size of each dot
    var dotSize: CGFloat = 32
    
    /// Spacing between dots
    var spacing: CGFloat = 10
    
    /// Calculate number of rows that fit in given height
    private func rowCount(for height: CGFloat) -> Int {
        let availableHeight = height - (spacing * 2) // Account for padding
        let cellHeight = dotSize + spacing
        let count = Int(availableHeight / cellHeight)
        return max(count, 1) // At least 1 row
    }
    
    /// Arrange results into columns based on row count
    private func columns(rows: Int) -> [[RoundResult]] {
        guard rows > 0 else { return [] }
        
        var cols: [[RoundResult]] = []
        var currentCol: [RoundResult] = []
        
        for result in results {
            currentCol.append(result)
            if currentCol.count >= rows {
                cols.append(currentCol)
                currentCol = []
            }
        }
        
        // Add remaining items as last column
        if !currentCol.isEmpty {
            cols.append(currentCol)
        }
        
        return cols
    }
    
    var body: some View {
        GeometryReader { geometry in
            let rows = rowCount(for: geometry.size.height)
            let cols = columns(rows: rows)
            
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(alignment: .top, spacing: spacing) {
                    ForEach(Array(cols.enumerated()), id: \.offset) { colIndex, column in
                        VStack(spacing: spacing) {
                            ForEach(Array(column.enumerated()), id: \.offset) { rowIndex, result in
                                GridDot(
                                    result: result.result,
                                    size: dotSize,
                                    hasPair: result.hasPair,
                                    isNatural: result.isNatural
                                )
                            }
                            
                            // Fill remaining rows with empty space for alignment
                            if column.count < rows {
                                ForEach(0..<(rows - column.count), id: \.self) { _ in
                                    Color.clear
                                        .frame(width: dotSize, height: dotSize)
                                }
                            }
                        }
                    }
                }
                .padding(spacing)
            }
            .padding(.leading, spacing)
        }
    }
}

/// A compact dot for the grid display
private struct GridDot: View {
    let result: GameResult
    let size: CGFloat
    var hasPair: Bool = false
    var isNatural: Bool = false
    
    private var color: Color {
        switch result {
        case .playerWins: return .blue
        case .bankerWins: return .red
        case .tie: return .green
        }
    }
    
    private var label: String {
        switch result {
        case .playerWins: return "P"
        case .bankerWins: return "B"
        case .tie: return "T"
        }
    }
    
    var body: some View {
        ZStack {
            Circle()
                .fill(color)
                .frame(width: size, height: size)
            
            Text(label)
                .font(.system(size: size * 0.5, weight: .bold))
                .foregroundStyle(.white)
            
            // Pair indicator (small yellow dot)
            if hasPair {
                Circle()
                    .fill(Color.yellow)
                    .frame(width: size * 0.25, height: size * 0.25)
                    .offset(x: -size * 0.3, y: size * 0.3)
            }
            
            // Natural indicator (star)
            if isNatural {
                Image(systemName: "star.fill")
                    .font(.system(size: size * 0.25))
                    .foregroundStyle(.yellow)
                    .offset(x: size * 0.3, y: -size * 0.3)
            }
        }
    }
}

// MARK: - Previews

#Preview("Grid Road Map") {
    ZStack {
        Color.Table.preview
            .ignoresSafeArea()
        
        RoadMapGridView(
            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)
            ],
            dotSize: 32
        )
        .frame(width: 240, height: 400)
        .background(Color.black.opacity(0.3))
    }
}

