//
//  MatchFormatGuideView.swift
//  PadelClub
//
//  Created by razmig on 20/02/2025.
//

import SwiftUI

struct MatchFormatGuideView: View {
    let matchCounts = Array(2...7)
    let formats: [MatchFormat] = [
        .twoSets, .twoSetsDecisivePoint,
        .twoSetsSuperTie, .twoSetsDecisivePointSuperTie,
        .twoSetsOfFourGames, .twoSetsOfFourGamesDecisivePoint,
        .nineGames, .nineGamesDecisivePoint,
        .superTie
    ]
    
    func getFormatDescription(for matchCount: Int) -> String {
        var description = ""
        
        // Group formats by their behavior
        let formatGroups = Dictionary(grouping: formats) { format in
            format.maximumMatchPerDay(for: matchCount)
        }
        
        // Sort by maximum matches allowed (descending)
        let sortedMaxMatches = formatGroups.keys.sorted(by: >)
        
        for maxMatches in sortedMaxMatches {
            if let formatsForMax = formatGroups[maxMatches] {
                let formatStrings = formatsForMax.map { $0.format }.joined(separator: "/")
                if maxMatches > 0 && maxMatches <= matchCount {
                    description += "Maximum \(maxMatches) matchs en format \(formatStrings)\n"
                } else if maxMatches == 0 {
                    description += "Aucun match au format \(formatStrings)\n"
                }
            }
        }
        
        if matchCount >= 7 {
            description += "Format \(MatchFormat.superTie.format) principalement"
        }
        
        return description.isEmpty ? "Aucun match possible" : description
    }

    var body: some View {
        List {
            Section {
                ForEach(matchCounts, id: \.self) { count in
                    VStack {
                        Text("\(count) matchs par jour")
                            .font(.headline)
                        Text(getFormatDescription(for: count))
                    }
                }
                
                // Special case for 7+ matches
                VStack {
                    Text("7+ matchs par jour")
                        .font(.headline)
                    Text("Tournois P 25 uniquement (soirée/demi-journée/journée)")
                }
            }
        }
        .navigationTitle("Guide des Formats de Match")
        .navigationBarTitleDisplayMode(.inline)
        .toolbarBackground(.visible, for: .navigationBar)
    }
}
