//
//  OnboardingStep5_CompletionView.swift
//  lichunWebsocket
//
//  Completion celebration view for onboarding
//

import SwiftUI

struct OnboardingStep5_CompletionView: View {
    @EnvironmentObject var appViewModel: AppViewModel
    @EnvironmentObject var webSocketService: WebSocketService
    @State private var animateIcon = false
    @State private var showContent = false
    let onComplete: () -> Void

    var body: some View {
        ZStack {
            // Warm celebratory gradient background
            LinearGradient(
                gradient: Gradient(colors: [
                    Color(hex: 0xFFD89B),  // Golden peach
                    Color(hex: 0xFFB88C),  // Warm peach
                    Color(hex: 0xFF8C94),  // Soft coral
                    Color(hex: 0xFFA8B8)   // Gentle pink
                ]),
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .edgesIgnoringSafeArea(.all)

            VStack(spacing: AppSpacing.xl) {
                Spacer()

                // Animated celebration icon with sparkles
                ZStack {
                    // Outer glow with warm colors
                    Circle()
                        .fill(Color.white.opacity(0.4))
                        .frame(width: animateIcon ? 160 : 140, height: animateIcon ? 160 : 140)
                        .blur(radius: 30)

                    // Multiple glow layers for depth
                    Circle()
                        .fill(Color.white.opacity(0.35))
                        .frame(width: 120, height: 120)
                        .blur(radius: 15)

                    Circle()
                        .fill(Color.white.opacity(0.3))
                        .frame(width: 100, height: 100)

                    // Star icon with rotation
                    Image(systemName: "star.fill")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 60, height: 60)
                        .foregroundColor(.white)
                        .rotationEffect(.degrees(animateIcon ? 360 : 0))

                    // Floating sparkles
                    ForEach(0..<3) { index in
                        Image(systemName: "sparkle")
                            .foregroundColor(.white.opacity(0.8))
                            .font(.system(size: 20))
                            .offset(
                                x: animateIcon ? CGFloat([-40, 40, 0][index]) : 0,
                                y: animateIcon ? CGFloat([-40, -40, -60][index]) : 0
                            )
                            .opacity(animateIcon ? 1.0 : 0.0)
                            .scaleEffect(animateIcon ? 1.0 : 0.5)
                            .animation(
                                .spring(response: 0.8, dampingFraction: 0.6)
                                    .delay(Double(index) * 0.1),
                                value: animateIcon
                            )
                    }
                }
                .shadow(color: .white.opacity(0.3), radius: 30, y: 10)
                .scaleEffect(animateIcon ? 1.0 : 0.8)

                // Warm, encouraging title
                VStack(spacing: AppSpacing.xs) {
                    Text("You're All Set!")
                        .font(.appTitle)
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                        .shadow(color: .black.opacity(0.1), radius: 4, y: 2)
                        .opacity(showContent ? 1 : 0)
                        .offset(y: showContent ? 0 : 20)

                    Text("Your journey begins now")
                        .font(.appHeadline)
                        .foregroundColor(.white.opacity(0.95))
                        .opacity(showContent ? 1 : 0)
                        .offset(y: showContent ? 0 : 20)
                }

                // Achievement unlock with cozy card
                VStack(spacing: AppSpacing.md) {
                    HStack(spacing: AppSpacing.sm) {
                        Image(systemName: "trophy.fill")
                            .foregroundColor(.white)
                            .font(.title3)
                        Text("Achievement Unlocked")
                            .font(.appBodyBold)
                            .foregroundColor(.white.opacity(0.95))
                    }
                    .padding(.horizontal, AppSpacing.lg)
                    .padding(.vertical, AppSpacing.xs)
                    .background(
                        Capsule()
                            .fill(Color.white.opacity(0.2))
                    )

                    HStack(spacing: AppSpacing.md) {
                        // Icon with warm glow
                        ZStack {
                            Circle()
                                .fill(Color.white.opacity(0.3))
                                .frame(width: 56, height: 56)
                                .blur(radius: 8)

                            Circle()
                                .fill(Color.white.opacity(0.25))
                                .frame(width: 50, height: 50)

                            Image(systemName: "sparkles")
                                .resizable()
                                .aspectRatio(contentMode: .fit)
                                .frame(width: 28, height: 28)
                                .foregroundColor(.white)
                        }

                        VStack(alignment: .leading, spacing: AppSpacing.xs) {
                            Text("First Steps")
                                .font(.appHeadline)
                                .fontWeight(.semibold)
                                .foregroundColor(.white)

                            Text("You've completed the tutorial!")
                                .font(.appBody)
                                .foregroundColor(.white.opacity(0.95))
                        }

                        Spacer()

                        // Diamond reward with sparkle
                        VStack(spacing: AppSpacing.xxs) {
                            Image(systemName: "diamond.fill")
                                .foregroundColor(AppColors.diamond)
                                .font(.title2)
                                .shadow(color: AppColors.diamond.opacity(0.5), radius: 8)

                            Text("+25")
                                .font(.appHeadline)
                                .fontWeight(.bold)
                                .foregroundColor(.white)
                        }
                    }
                    .padding(AppSpacing.md)
                    .background(
                        RoundedRectangle(cornerRadius: 20)
                            .fill(Color.white.opacity(0.25))
                            .shadow(color: .black.opacity(0.1), radius: 20, y: 10)
                    )
                }
                .padding(.horizontal, AppSpacing.xl)
                .opacity(showContent ? 1 : 0)
                .offset(y: showContent ? 0 : 30)
                .scaleEffect(showContent ? 1.0 : 0.9)

                Spacer()

                // Start playing button with warm gradient
                Button(action: {
                    // INTEGRATION: Play success sound
                    SoundManager.shared.playSound(.success)

                    // Haptic feedback
                    let notification = UINotificationFeedbackGenerator()
                    notification.notificationOccurred(.success)

                    withAnimation(.spring(response: 0.5, dampingFraction: 0.8)) {
                        // Track onboarding completion
                        AnalyticsManager.shared.track(.onboardingComplete)

                        // Mark onboarding as complete
                        appViewModel.completeOnboarding()

                        // Send completion message to server
                        webSocketService.sendMessage(message: [
                            "type": "completeOnboarding"
                        ])

                        onComplete()
                    }
                }) {
                    HStack(spacing: AppSpacing.sm) {
                        Image(systemName: "play.circle.fill")
                            .font(.title3)

                        Text("Start Your Life")
                            .font(.appHeadline)
                            .fontWeight(.bold)
                    }
                    .foregroundColor(Color(hex: 0xFF8C94))
                    .frame(maxWidth: .infinity)
                    .frame(height: AppSpacing.buttonHeight + 8)
                    .background(Color.white)
                    .cornerRadius(AppSpacing.cornerRadius + 4)
                    .shadow(color: .black.opacity(0.2), radius: 25, y: 12)
                }
                .padding(.horizontal, AppSpacing.xl)
                .padding(.bottom, AppSpacing.xl)
                .opacity(showContent ? 1 : 0)
                .offset(y: showContent ? 0 : 40)
                .scaleEffect(showContent ? 1.0 : 0.9)
            }
        }
        .onAppear {
            // Initial scale and sparkle animation
            withAnimation(.spring(response: 0.6, dampingFraction: 0.6)) {
                animateIcon = true
            }

            // Content reveal
            withAnimation(.easeOut(duration: 0.8).delay(0.4)) {
                showContent = true
            }

            // Continuous gentle rotation animation for star
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) {
                withAnimation(.linear(duration: 4).repeatForever(autoreverses: false)) {
                    animateIcon = true
                }
            }
        }
    }
}

// MARK: - Preview
#if DEBUG
struct OnboardingStep5_CompletionView_Previews: PreviewProvider {
    static var previews: some View {
        OnboardingStep5_CompletionView(onComplete: {})
            .environmentObject(AppViewModel())
            .environmentObject(WebSocketService(
                urlSession: URLSession.shared,
                delegateQueue: OperationQueue()
            ))
    }
}
#endif
