import SwiftUI
import ComponentLibrary

struct IncomingMessageLoading: View {
    @State private var currentStage: Int = 0

    private let stages: [(message: String, type: LoadingAnimationType)] = [
        ("Crafting melodies...", .keys),
        ("Drumming up...", .drums),
        ("Writing lyrics...", .lyrics),
        ("Harmonizing...", .harmonize)
    ]

    var body: some View {
        HStack(spacing: 5) {
            LoadingIndicator(
                message: stages[currentStage].message,
                animationType: stages[currentStage].type
            )

            Spacer()
        }
        .onAppear {
            startCycling()
        }
    }

    private func startCycling() {
        // Cycle through first 3 stages (keys, drums, lyrics) at 1.25s each
        // Then stay on harmonize until dismissed
        Timer.scheduledTimer(withTimeInterval: 1.25, repeats: true) { timer in
            if currentStage < 3 {
                withAnimation(.easeInOut(duration: 0.3)) {
                    currentStage += 1
                }
            } else {
                // Stop cycling once we reach harmonize (stage 3)
                timer.invalidate()
            }
        }
    }
}

#Preview {
    VStack(alignment: .leading, spacing: 20) {
        IncomingMessageLoading()
        
        Spacer()
    }
    .padding(.horizontal, 16)
    .background(ChatConstants.Colors.Background.primary)
    .frame(maxWidth: .infinity, maxHeight: .infinity)
}
