//
//  RoadMapContainerView.swift
//  Baccarat
//
//  Container view for displaying road maps with a tabbed interface.
//  Allows switching between Bead Road, Big Road, and derived roads.
//

import SwiftUI
import CasinoKit

/// Container view for road map displays with road type selection.
struct RoadMapContainerView: View {
    /// The round results to display.
    let results: [RoundResult]
    
    /// The currently selected road type.
    @Binding var selectedRoad: RoadType
    
    /// Whether to show the road selector tabs.
    var showSelector: Bool = true
    
    /// Cell size for road displays.
    var cellSize: CGFloat = Design.RoadMap.bigRoadCellSize
    
    /// Whether to show the info button.
    var showInfoButton: Bool = true
    
    // MARK: - State
    
    @State private var showRoadInfo = false
    
    // MARK: - Body
    
    var body: some View {
        VStack(spacing: Design.Spacing.xSmall) {
            if showSelector {
                headerWithSelector
            }
            
            roadContent
        }
    }
    
    // MARK: - Header
    
    @ViewBuilder
    private var headerWithSelector: some View {
        HStack(spacing: Design.Spacing.small) {
            // Road type picker
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: Design.Spacing.xSmall) {
                    ForEach(RoadType.allCases) { roadType in
                        roadTypeButton(for: roadType)
                    }
                }
            }
            
            Spacer(minLength: 0)
            
            // Info button
            if showInfoButton {
                Button {
                    showRoadInfo = true
                } label: {
                    Image(systemName: "info.circle")
                        .font(.system(size: Design.IconSize.small))
                        .foregroundStyle(.white.opacity(Design.Opacity.medium))
                }
                .accessibilityLabel(String(localized: "Information about \(selectedRoad.displayName)"))
            }
        }
        .sheet(isPresented: $showRoadInfo) {
            RoadInfoSheet(roadType: selectedRoad)
        }
    }
    
    @ViewBuilder
    private func roadTypeButton(for roadType: RoadType) -> some View {
        Button {
            withAnimation(.easeInOut(duration: Design.Animation.quick)) {
                selectedRoad = roadType
            }
        } label: {
            HStack(spacing: Design.Spacing.xxSmall) {
                Image(systemName: roadType.icon)
                    .font(.system(size: Design.BaseFontSize.xSmall))
                
                Text(roadType.displayName)
                    .font(.system(size: Design.BaseFontSize.xSmall, weight: .medium))
            }
            .padding(.horizontal, Design.Spacing.small)
            .padding(.vertical, Design.Spacing.xSmall)
            .background(
                Capsule()
                    .fill(selectedRoad == roadType ? 
                          Color.white.opacity(Design.Opacity.light) : 
                          Color.clear)
            )
            .foregroundStyle(selectedRoad == roadType ? .white : .white.opacity(Design.Opacity.medium))
        }
        .buttonStyle(.plain)
        .accessibilityLabel("\(roadType.displayName), \(selectedRoad == roadType ? "selected" : "not selected")")
    }
    
    // MARK: - Road Content
    
    @ViewBuilder
    private var roadContent: some View {
        switch selectedRoad {
        case .bead:
            BeadRoadView(results: results, cellSize: cellSize)
            
        case .big:
            BigRoadView(results: results, cellSize: cellSize)
            
        case .bigEyeBoy, .smallRoad, .cockroachPig:
            DerivedRoadView(roadType: selectedRoad, results: results, cellSize: cellSize)
        }
    }
}

// MARK: - Road Info Sheet

/// Sheet view explaining the selected road type with casino-themed styling.
struct RoadInfoSheet: View {
    let roadType: RoadType
    
    @Environment(\.dismiss) private var dismiss
    
    @ScaledMetric(relativeTo: .title) private var iconSize: CGFloat = Design.BaseFontSize.display
    @ScaledMetric(relativeTo: .title) private var titleSize: CGFloat = Design.BaseFontSize.title
    @ScaledMetric(relativeTo: .body) private var bodySize: CGFloat = Design.BaseFontSize.body
    
    var body: some View {
        NavigationStack {
            ZStack {
                Color.Sheet.background
                    .ignoresSafeArea()
                
                ScrollView {
                    VStack(spacing: Design.Spacing.xLarge) {
                        // Large centered icon (like RulesHelpView)
                        Image(systemName: roadType.icon)
                            .font(.system(size: iconSize))
                            .foregroundStyle(Color.Sheet.accent)
                            .padding(.top, Design.Spacing.xxLarge)
                        
                        // Title
                        Text(roadType.displayName)
                            .font(.system(size: titleSize, weight: .bold))
                            .foregroundStyle(.white)
                        
                        // Subtitle for derived roads
                        if roadType.isDerived {
                            Text(String(localized: "Derived Road"))
                                .font(.subheadline)
                                .foregroundStyle(.white.opacity(Design.Opacity.medium))
                        }
                        
                        // Bullet points (styled like RulesHelpView)
                        VStack(alignment: .leading, spacing: Design.Spacing.medium) {
                            ForEach(explanationPoints, id: \.self) { point in
                                HStack(alignment: .firstTextBaseline, spacing: Design.Spacing.medium) {
                                    Text("•")
                                        .foregroundStyle(Color.Sheet.accent)
                                    
                                    Text(point)
                                        .font(.system(size: bodySize))
                                        .foregroundStyle(.white.opacity(Design.Opacity.heavy))
                                }
                            }
                        }
                        .padding(.horizontal, Design.Spacing.xxLarge)
                        
                        // Color legend for derived roads
                        if roadType.isDerived {
                            colorLegendSection
                        }
                        
                        // Beginner tip for derived roads
                        if roadType.isDerived {
                            beginnerTipSection
                        }
                        
                        Spacer()
                    }
                }
            }
            .navigationTitle(String(localized: "About This Road"))
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button(String(localized: "Done")) {
                        dismiss()
                    }
                    .bold()
                    .foregroundStyle(Color.Sheet.accent)
                }
            }
            .toolbarBackground(Color.Sheet.background, for: .navigationBar)
            .toolbarBackground(.visible, for: .navigationBar)
            .toolbarColorScheme(.dark, for: .navigationBar)
        }
    }
    
    // MARK: - Color Legend Section
    
    private var colorLegendSection: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.small) {
            Text(String(localized: "Color Meaning"))
                .font(.system(size: Design.BaseFontSize.body, weight: .semibold))
                .foregroundStyle(.white)
            
            HStack(spacing: Design.Spacing.large) {
                legendItem(color: .red, text: String(localized: "Pattern repeating"))
                legendItem(color: .blue, text: String(localized: "Pattern breaking"))
            }
        }
        .padding()
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(
            RoundedRectangle(cornerRadius: Design.CornerRadius.large)
                .fill(Color.Sheet.sectionFill)
        )
        .padding(.horizontal, Design.Spacing.large)
    }
    
    // MARK: - Beginner Tip Section
    
    private var beginnerTipSection: some View {
        HStack(alignment: .top, spacing: Design.Spacing.medium) {
            Image(systemName: "lightbulb.fill")
                .font(.system(size: Design.IconSize.medium))
                .foregroundStyle(Color.Sheet.accent)
            
            Text(String(localized: "These are for advanced players. Beginners can ignore them!"))
                .font(.callout)
                .foregroundStyle(.white.opacity(Design.Opacity.strong))
        }
        .padding()
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(
            RoundedRectangle(cornerRadius: Design.CornerRadius.large)
                .fill(Color.Sheet.accent.opacity(Design.Opacity.hint))
        )
        .padding(.horizontal, Design.Spacing.large)
    }
    
    // MARK: - Helper Views
    
    @ViewBuilder
    private func legendItem(color: Color, text: String) -> some View {
        HStack(spacing: Design.Spacing.xSmall) {
            Circle()
                .stroke(color, lineWidth: Design.RoadMap.hollowStrokeWidth)
                .frame(width: Design.RoadMap.cellSize, height: Design.RoadMap.cellSize)
            
            Text(text)
                .font(.caption)
                .foregroundStyle(.white.opacity(Design.Opacity.strong))
        }
    }
    
    // MARK: - Data
    
    private var explanationPoints: [String] {
        switch roadType {
        case .bead:
            return [
                String(localized: "Shows all results in a simple grid."),
                String(localized: "Results fill top to bottom, then left to right."),
                String(localized: "Blue = Player win, Red = Banker win, Green = Tie."),
                String(localized: "The simplest road map to understand.")
            ]
            
        case .big:
            return [
                String(localized: "The most important road map in Baccarat."),
                String(localized: "Results stack vertically when the same side wins."),
                String(localized: "A new column starts when the winner changes."),
                String(localized: "Long columns = hot streak. Short columns = choppy shoe."),
                String(localized: "Ties are shown as a green line across the last circle.")
            ]
            
        case .bigEyeBoy:
            return [
                String(localized: "Analyzes patterns from the Big Road."),
                String(localized: "Compares current streak to the previous column."),
                String(localized: "Helps identify if the shoe is predictable or random."),
                String(localized: "Starts after the first entry in column 2 of the Big Road.")
            ]
            
        case .smallRoad:
            return [
                String(localized: "Similar to Big Eye Boy, but looks further back."),
                String(localized: "Compares current streak to 2 columns back."),
                String(localized: "Identifies medium-term pattern trends."),
                String(localized: "Starts after the first entry in column 3 of the Big Road.")
            ]
            
        case .cockroachPig:
            return [
                String(localized: "The finest pattern detection in Baccarat."),
                String(localized: "Compares current streak to 3 columns back."),
                String(localized: "Shows the most subtle pattern variations."),
                String(localized: "Starts after the first entry in column 4 of the Big Road.")
            ]
        }
    }
}

// MARK: - Previews

#Preview("Road Map Container") {
    struct PreviewWrapper: View {
        @State private var selectedRoad: RoadType = .big
        
        var body: some View {
            ZStack {
                Color.Table.preview
                    .ignoresSafeArea()
                
                RoadMapContainerView(
                    results: [
                        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)
                    ],
                    selectedRoad: $selectedRoad
                )
                .frame(height: 220)
                .padding()
            }
        }
    }
    
    return PreviewWrapper()
}

#Preview("Road Info Sheet") {
    RoadInfoSheet(roadType: .bigEyeBoy)
}
