//
//  CozyConnectingView.swift
//  lichunWebsocket
//
//  Cute and cozy loading screen for connecting to the player's character
//

import SwiftUI

struct CozyConnectingView: View {
    @State private var currentMessageIndex = 0
    @State private var isPulsing = false
    @State private var rotation: Double = 0
    @State private var floatingOffset: CGFloat = 0
    @State private var particleAnimations: [Bool] = Array(repeating: false, count: 8)

    // Cute messages about connecting to their character
    private let messages = [
        "Waking up your character...",
        "Checking in on their life...",
        "Opening the door to their world...",
        "Connecting to your story...",
        "Your character has been waiting...",
        "Loading their adventures..."
    ]

    var body: some View {
        ZStack {
            // Warm gradient background
            LinearGradient(
                colors: [
                    AppColors.background,
                    AppColors.surfaceElevated,
                    Color(hex: 0xFFE5F0) // Soft pink tint
                ],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .ignoresSafeArea()

            // Floating particles
            ForEach(0..<8, id: \.self) { index in
                FloatingParticle(
                    color: particleColor(for: index),
                    size: particleSize(for: index),
                    position: particlePosition(for: index),
                    isAnimating: particleAnimations[index]
                )
            }

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

                // Main character connection visual
                ZStack {
                    // Outer glow ring
                    Circle()
                        .fill(
                            RadialGradient(
                                colors: [
                                    AppColors.primary.opacity(0.3),
                                    AppColors.primary.opacity(0.1),
                                    Color.clear
                                ],
                                center: .center,
                                startRadius: 40,
                                endRadius: 100
                            )
                        )
                        .frame(width: 200, height: 200)
                        .scaleEffect(isPulsing ? 1.1 : 0.95)
                        .opacity(isPulsing ? 0.6 : 0.3)

                    // Middle rotating ring
                    Circle()
                        .stroke(
                            LinearGradient(
                                colors: [
                                    AppColors.primary,
                                    AppColors.accent,
                                    AppColors.secondary,
                                    AppColors.primary
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            ),
                            lineWidth: 4
                        )
                        .frame(width: 140, height: 140)
                        .rotationEffect(.degrees(rotation))

                    // Inner floating heart (representing their character's life)
                    ZStack {
                        // Heart background
                        Circle()
                            .fill(
                                LinearGradient(
                                    colors: [AppColors.primary, AppColors.accent],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                            )
                            .frame(width: 100, height: 100)

                        // Heart icon
                        Image(systemName: "heart.fill")
                            .font(.system(size: 44))
                            .foregroundColor(.white)
                            .shadow(color: AppColors.primary.opacity(0.5), radius: 8, x: 0, y: 4)
                    }
                    .offset(y: floatingOffset)
                    .scaleEffect(isPulsing ? 1.05 : 0.98)
                }
                .frame(height: 220)

                // Message text
                VStack(spacing: AppSpacing.sm) {
                    Text(messages[currentMessageIndex])
                        .font(.appHeadline)
                        .foregroundColor(AppColors.primaryText)
                        .multilineTextAlignment(.center)
                        .id("message-\(currentMessageIndex)") // For transition
                        .transition(.asymmetric(
                            insertion: .opacity.combined(with: .scale(scale: 0.8, anchor: .center)),
                            removal: .opacity.combined(with: .scale(scale: 1.2, anchor: .center))
                        ))

                    // Animated dots
                    HStack(spacing: 6) {
                        ForEach(0..<3) { index in
                            Circle()
                                .fill(AppColors.secondary)
                                .frame(width: 8, height: 8)
                                .opacity(dotOpacity(for: index))
                        }
                    }
                    .padding(.top, AppSpacing.xs)
                }
                .padding(.horizontal, AppSpacing.xl)

                Spacer()

                // Cozy footer message
                Text("✨ Your character has been living their life")
                    .font(.appCaption)
                    .foregroundColor(AppColors.secondaryText)
                    .multilineTextAlignment(.center)
                    .padding(.horizontal, AppSpacing.xl)
                    .padding(.bottom, AppSpacing.xxl)
                    .opacity(isPulsing ? 0.8 : 0.5)
            }
        }
        .onAppear {
            startAnimations()
        }
    }

    // MARK: - Particle Helpers

    private func particleColor(for index: Int) -> Color {
        let colors = [AppColors.primary, AppColors.accent, AppColors.secondary, AppColors.happiness]
        return colors[index % colors.count]
    }

    private func particleSize(for index: Int) -> CGFloat {
        return CGFloat([6, 8, 10, 7, 9, 6, 11, 8][index])
    }

    private func particlePosition(for index: Int) -> CGPoint {
        let positions: [(CGFloat, CGFloat)] = [
            (0.2, 0.15), (0.8, 0.2), (0.15, 0.45), (0.85, 0.5),
            (0.1, 0.75), (0.9, 0.7), (0.3, 0.85), (0.7, 0.9)
        ]
        return CGPoint(x: positions[index].0, y: positions[index].1)
    }

    private func dotOpacity(for index: Int) -> Double {
        let delay = Double(index) * 0.2
        return isPulsing ? (sin(Date().timeIntervalSinceReferenceDate * 2 + delay) + 1) / 2 : 0.3
    }

    // MARK: - Animation Control

    private func startAnimations() {
        // Pulsing animation
        withAnimation(.easeInOut(duration: 1.5).repeatForever(autoreverses: true)) {
            isPulsing = true
        }

        // Rotation animation
        withAnimation(.linear(duration: 4.0).repeatForever(autoreverses: false)) {
            rotation = 360
        }

        // Floating animation
        withAnimation(.easeInOut(duration: 2.0).repeatForever(autoreverses: true)) {
            floatingOffset = -8
        }

        // Particle animations with staggered delays
        for index in 0..<8 {
            DispatchQueue.main.asyncAfter(deadline: .now() + Double(index) * 0.15) {
                withAnimation(.easeInOut(duration: 2.5).repeatForever(autoreverses: true)) {
                    particleAnimations[index] = true
                }
            }
        }

        // Rotate messages every 2.5 seconds
        Timer.scheduledTimer(withTimeInterval: 2.5, repeats: true) { _ in
            withAnimation(.easeInOut(duration: 0.5)) {
                currentMessageIndex = (currentMessageIndex + 1) % messages.count
            }
        }
    }
}

// MARK: - Floating Particle Component

struct FloatingParticle: View {
    let color: Color
    let size: CGFloat
    let position: CGPoint
    let isAnimating: Bool

    @State private var offset: CGSize = .zero
    @State private var opacity: Double = 0.0

    var body: some View {
        Circle()
            .fill(color)
            .frame(width: size, height: size)
            .opacity(opacity)
            .offset(offset)
            .position(
                x: UIScreen.main.bounds.width * position.x,
                y: UIScreen.main.bounds.height * position.y
            )
            .blur(radius: 1)
            .onChange(of: isAnimating) { animating in
                if animating {
                    startFloating()
                }
            }
    }

    private func startFloating() {
        // Fade in
        withAnimation(.easeIn(duration: 0.5)) {
            opacity = Double.random(in: 0.3...0.7)
        }

        // Random floating motion
        let randomX = CGFloat.random(in: -30...30)
        let randomY = CGFloat.random(in: -40...40)

        withAnimation(
            .easeInOut(duration: Double.random(in: 3...5))
            .repeatForever(autoreverses: true)
        ) {
            offset = CGSize(width: randomX, height: randomY)
        }
    }
}

// MARK: - Preview
#if DEBUG
struct CozyConnectingView_Previews: PreviewProvider {
    static var previews: some View {
        CozyConnectingView()
    }
}
#endif
