//
//  DerivedRoadView.swift
//  Baccarat
//
//  Displays derived roads: Big Eye Boy, Small Road, and Cockroach Pig.
//  These roads use hollow circles: red = pattern repeating, blue = pattern breaking.
//

import SwiftUI
import CasinoKit

/// Displays a derived road (Big Eye Boy, Small Road, or Cockroach Pig).
/// Uses hollow circles where red indicates pattern repeating and blue indicates pattern breaking.
struct DerivedRoadView: View {
    /// The road type being displayed.
    let roadType: RoadType
    
    /// The round results to analyze.
    let results: [RoundResult]
    
    /// Cell size for the circles.
    var cellSize: CGFloat = Design.RoadMap.cellSize
    
    // MARK: - Computed Properties
    
    private var entries: [DerivedRoadEntry] {
        let bigRoad = RoadMapBuilder.buildBigRoad(from: results)
        let columns = RoadMapBuilder.buildBigRoadColumns(from: bigRoad)
        return RoadMapBuilder.buildDerivedRoad(from: columns, roadType: roadType)
    }
    
    private var columns: [[DerivedRoadEntry]] {
        guard !entries.isEmpty else { return [] }
        
        var cols: [Int: [DerivedRoadEntry]] = [:]
        for entry in entries {
            cols[entry.column, default: []].append(entry)
        }
        
        // Convert to sorted array
        let maxColumn = entries.map(\.column).max() ?? 0
        var result: [[DerivedRoadEntry]] = []
        for col in 0...maxColumn {
            result.append(cols[col] ?? [])
        }
        
        return result
    }
    
    // MARK: - Body
    
    var body: some View {
        if entries.isEmpty {
            emptyState
        } else {
            roadContent
        }
    }
    
    @ViewBuilder
    private var roadContent: 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)
    }
    
    @ViewBuilder
    private var emptyState: some View {
        VStack(spacing: Design.Spacing.small) {
            Image(systemName: roadType.icon)
                .font(.system(size: Design.IconSize.large))
                .foregroundStyle(.white.opacity(Design.Opacity.medium))
            
            Text(String(localized: "Not enough data"))
                .font(.system(size: Design.BaseFontSize.small))
                .foregroundStyle(.white.opacity(Design.Opacity.medium))
            
            Text(roadType.shortDescription)
                .font(.system(size: Design.BaseFontSize.xSmall))
                .foregroundStyle(.white.opacity(Design.Opacity.light))
                .multilineTextAlignment(.center)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(
            RoundedRectangle(cornerRadius: Design.CornerRadius.medium)
                .fill(Color.black.opacity(Design.Opacity.light))
        )
    }
    
    // MARK: - Private Views
    
    @ViewBuilder
    private func columnView(for column: [DerivedRoadEntry], index: Int) -> some View {
        VStack(spacing: Design.RoadMap.cellSpacing) {
            ForEach(column) { entry in
                DerivedRoadCell(
                    entry: entry,
                    size: cellSize
                )
            }
            
            // Fill remaining space for consistent column height
            if column.count < Design.RoadMap.maxRows {
                ForEach(0..<(Design.RoadMap.maxRows - column.count), id: \.self) { _ in
                    Color.clear
                        .frame(width: cellSize, height: cellSize)
                }
            }
        }
    }
    
    // MARK: - Accessibility
    
    private var accessibilityLabel: String {
        if entries.isEmpty {
            return "\(roadType.displayName): Not enough data yet"
        }
        
        let redCount = entries.filter(\.isRed).count
        let blueCount = entries.count - redCount
        
        return "\(roadType.displayName): \(entries.count) entries. \(redCount) red (pattern), \(blueCount) blue (break)"
    }
}

// MARK: - Derived Road Cell

/// A single cell in a derived road display.
/// Shows hollow circles with red or blue color.
struct DerivedRoadCell: View {
    let entry: DerivedRoadEntry
    var size: CGFloat = Design.RoadMap.cellSize
    
    var body: some View {
        Circle()
            .stroke(entry.color, lineWidth: Design.RoadMap.hollowStrokeWidth)
            .frame(width: size, height: size)
            .accessibilityElement(children: .ignore)
            .accessibilityLabel(entry.isRed ? 
                String(localized: "Red, pattern repeating") : 
                String(localized: "Blue, pattern breaking"))
    }
}

// MARK: - Previews

#Preview("Big Eye Boy") {
    ZStack {
        Color.Table.preview
            .ignoresSafeArea()
        
        VStack(spacing: Design.Spacing.medium) {
            Text("Big Eye Boy")
                .foregroundStyle(.white)
            
            DerivedRoadView(
                roadType: .bigEyeBoy,
                results: sampleResults
            )
            .frame(height: Design.RoadMap.containerHeight)
        }
        .padding()
    }
}

#Preview("Small Road") {
    ZStack {
        Color.Table.preview
            .ignoresSafeArea()
        
        VStack(spacing: Design.Spacing.medium) {
            Text("Small Road")
                .foregroundStyle(.white)
            
            DerivedRoadView(
                roadType: .smallRoad,
                results: sampleResults
            )
            .frame(height: Design.RoadMap.containerHeight)
        }
        .padding()
    }
}

#Preview("Cockroach Pig") {
    ZStack {
        Color.Table.preview
            .ignoresSafeArea()
        
        VStack(spacing: Design.Spacing.medium) {
            Text("Cockroach Pig")
                .foregroundStyle(.white)
            
            DerivedRoadView(
                roadType: .cockroachPig,
                results: sampleResults
            )
            .frame(height: Design.RoadMap.containerHeight)
        }
        .padding()
    }
}

#Preview("Empty State") {
    ZStack {
        Color.Table.preview
            .ignoresSafeArea()
        
        DerivedRoadView(
            roadType: .bigEyeBoy,
            results: []
        )
        .frame(height: Design.RoadMap.containerHeight)
        .padding()
    }
}

// Sample results for previews
private let sampleResults: [RoundResult] = [
    RoundResult(result: .playerWins, playerValue: 8, bankerValue: 6),
    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),
    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),
    RoundResult(result: .bankerWins, playerValue: 1, bankerValue: 8),
    RoundResult(result: .bankerWins, playerValue: 2, bankerValue: 7),
    RoundResult(result: .playerWins, playerValue: 6, bankerValue: 3),
    RoundResult(result: .playerWins, playerValue: 5, bankerValue: 4),
    RoundResult(result: .playerWins, playerValue: 8, bankerValue: 1),
    RoundResult(result: .bankerWins, playerValue: 3, bankerValue: 9)
]
