//
//  LoadingSpinner.swift
//  SportsTime
//
//  Apple-style indeterminate spinner with theme-aware colors.
//

import SwiftUI

struct LoadingSpinner: View {
    enum Size {
        case small, medium, large

        var diameter: CGFloat {
            switch self {
            case .small: return 16
            case .medium: return 24
            case .large: return 40
            }
        }

        var strokeWidth: CGFloat {
            switch self {
            case .small: return 2
            case .medium: return 3
            case .large: return 4
            }
        }

        var labelFont: Font {
            switch self {
            case .small, .medium: return .subheadline
            case .large: return .body
            }
        }
    }

    let size: Size
    let label: String?

    @State private var rotation: Double = 0
    @Environment(\.colorScheme) private var colorScheme

    init(size: Size = .medium, label: String? = nil) {
        self.size = size
        self.label = label
    }

    var body: some View {
        HStack(spacing: Theme.Spacing.sm) {
            spinnerView

            if let label {
                Text(label)
                    .font(size.labelFont)
                    .foregroundStyle(Theme.textSecondary(colorScheme))
            }
        }
    }

    private var spinnerView: some View {
        ZStack {
            // Background track - subtle gray like Apple's native spinner
            Circle()
                .stroke(Color.secondary.opacity(0.2), lineWidth: size.strokeWidth)

            // Rotating arc (270 degrees) - gray like Apple's ProgressView
            Circle()
                .trim(from: 0, to: 0.75)
                .stroke(Color.secondary, style: StrokeStyle(lineWidth: size.strokeWidth, lineCap: .round))
                .rotationEffect(.degrees(rotation))
        }
        .frame(width: size.diameter, height: size.diameter)
        .onAppear {
            withAnimation(.linear(duration: 1).repeatForever(autoreverses: false)) {
                rotation = 360
            }
        }
    }
}

// MARK: - Preview

#Preview("Loading Spinner Sizes") {
    VStack(spacing: 40) {
        LoadingSpinner(size: .small, label: "Loading...")
        LoadingSpinner(size: .medium, label: "Loading games...")
        LoadingSpinner(size: .large, label: "Planning trip")
        LoadingSpinner(size: .medium)
    }
    .padding(40)
    .themedBackground()
}
