//
//  BigRoadView.swift
//  Baccarat
//
//  The Big Road is the primary road map in Baccarat.
//  Results stack vertically when the same side wins; a new column starts when the winner changes.
//

import SwiftUI
import CasinoKit

/// Displays the Big Road - the primary Baccarat road map.
/// Shows streaks as vertical columns that start a new column when the winner changes.
struct BigRoadView: View {
    /// The round results to display.
    let results: [RoundResult]
    
    /// Optional cell size override.
    var cellSize: CGFloat = Design.RoadMap.bigRoadCellSize
    
    /// Whether to show natural and pair markers.
    var showMarkers: Bool = true
    
    // MARK: - Computed Properties
    
    private var entries: [BigRoadEntry] {
        RoadMapBuilder.buildBigRoad(from: results)
    }
    
    private var columns: [BigRoadColumn] {
        RoadMapBuilder.buildBigRoadColumns(from: entries)
    }
    
    // MARK: - Body
    
    var body: some View {
        ScrollViewReader { proxy in
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(alignment: .top, spacing: Design.RoadMap.cellSpacing) {
                    ForEach(columns) { column in
                        columnView(for: column)
                    }
                    
                    // 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: BigRoadColumn) -> some View {
        VStack(spacing: Design.RoadMap.cellSpacing) {
            ForEach(column.entries) { entry in
                BigRoadCell(
                    entry: entry,
                    size: cellSize,
                    showMarkers: showMarkers
                )
            }
            
            // Fill remaining space for consistent column height
            if column.entries.count < Design.RoadMap.maxRows {
                ForEach(0..<(Design.RoadMap.maxRows - column.entries.count), id: \.self) { _ in
                    Color.clear
                        .frame(width: cellSize, height: cellSize)
                }
            }
        }
    }
    
    // MARK: - Accessibility
    
    private var accessibilityLabel: String {
        if results.isEmpty {
            return String(localized: "Big 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: "Big Road: \(results.count) results. Player \(playerWins), Banker \(bankerWins), Ties \(ties)")
    }
}

// MARK: - Big Road Cell

/// A single cell in the Big Road display.
struct BigRoadCell: View {
    let entry: BigRoadEntry
    var size: CGFloat = Design.RoadMap.bigRoadCellSize
    var showMarkers: Bool = true
    
    private var markerSize: CGFloat {
        size * 0.25
    }
    
    var body: some View {
        ZStack {
            // Main circle (hollow)
            Circle()
                .stroke(entry.color, lineWidth: Design.RoadMap.hollowStrokeWidth)
                .frame(width: size, height: size)
            
            // Tie indicator (green diagonal line)
            if entry.tieCount > 0 {
                tieIndicator
            }
            
            // Pair marker (bottom-left)
            if showMarkers && entry.hasPair {
                Circle()
                    .fill(Color.yellow)
                    .frame(width: markerSize, height: markerSize)
                    .offset(x: -size * 0.35, y: size * 0.35)
            }
            
            // Natural marker (top-right star)
            if showMarkers && entry.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)
    }
    
    @ViewBuilder
    private var tieIndicator: some View {
        if entry.tieCount == 1 {
            // Single tie: diagonal green line
            Path { path in
                path.move(to: CGPoint(x: size * 0.25, y: size * 0.75))
                path.addLine(to: CGPoint(x: size * 0.75, y: size * 0.25))
            }
            .stroke(Color.green, lineWidth: Design.LineWidth.medium)
            .frame(width: size, height: size)
        } else {
            // Multiple ties: show count
            Text("\(entry.tieCount)")
                .font(.system(size: size * 0.4, weight: .bold))
                .foregroundStyle(.green)
        }
    }
    
    private var cellAccessibilityLabel: String {
        var label = entry.result == .playerWins ? 
            String(localized: "Player win") : String(localized: "Banker win")
        
        if entry.tieCount > 0 {
            label += ", \(entry.tieCount) \(entry.tieCount == 1 ? "tie" : "ties")"
        }
        if entry.isNatural {
            label += ", natural"
        }
        if entry.hasPair {
            label += ", pair"
        }
        
        return label
    }
}

// MARK: - Preview

#Preview("Big Road") {
    ZStack {
        Color.Table.preview
            .ignoresSafeArea()
        
        BigRoadView(
            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()
    }
}
