//
//  OnboardingStep3_UITourView.swift
//  lichunWebsocket
//
//  UI tour for onboarding flow - shows key features of the app
//

import SwiftUI

struct OnboardingStep3_UITourView: View {
    @EnvironmentObject var appViewModel: AppViewModel
    @State private var currentTourStep = 0
    @State private var showCard = false
    @State private var spotlightPulse = false
    let onComplete: () -> Void

    // Mirror of the live tab bar so the spotlight matches what players will see.
    private let mockTabs: [(icon: String, label: String)] = [
        ("house.fill", "Home"),
        ("calendar", "Activities"),
        ("heart.circle.fill", "Social"),
        ("line.3.horizontal.circle.fill", "More"),
    ]

    // T014: each tour step points at a REAL on-screen control. `spotlight`
    // tells the mock chrome below the card which element to highlight so the
    // player leaves onboarding knowing exactly where to tap.
    let tourSteps = [
        TourStep(
            icon: "speedometer",
            title: "Speed Up Time",
            description: "Tap + on the Speed of Time control (top of Home) to fast-forward. Events and choices arrive as time passes."
        ),
        TourStep(
            icon: "calendar",
            title: "The Activities Tab",
            description: "The second tab is Activities. Study, work, join clubs, and pick up hobbies to shape who your character becomes."
        ),
        TourStep(
            icon: "heart.circle.fill",
            title: "The Social Tab",
            description: "The heart tab is Social. Reply to messages, build friendships, and find romance. The badge shows unread chats."
        ),
        TourStep(
            icon: "line.3.horizontal.circle.fill",
            title: "The More Menu",
            description: "The last tab opens More: achievements, the store, your relationships, and settings all live here."
        )
    ]

    /// Which tab index the mock tab bar should highlight for the current step.
    /// Step 0 (speed) highlights Home, where the speed control lives.
    private var spotlightTab: Int {
        switch currentTourStep {
        case 0: return 0   // Home (speed control)
        case 1: return 1   // Activities
        case 2: return 2   // Social
        default: return 3  // More
        }
    }

    /// Whether the current step is about the header speed control rather than a tab.
    private var spotlightHeader: Bool { currentTourStep == 0 }

    var body: some View {
        ZStack {
            // Warm gradient background
            LinearGradient(
                gradient: Gradient(colors: [
                    Color(hex: 0xFFF5E6),  // Soft cream
                    Color(hex: 0xFFE6E6),  // Warm pink tint
                    Color(hex: 0xFFF0E6)   // Peachy cream
                ]),
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .edgesIgnoringSafeArea(.all)

            VStack(spacing: 0) {
                // Friendly header
                VStack(spacing: AppSpacing.xs) {
                    Text("Quick Tour")
                        .font(.appLargeTitle)
                        .fontWeight(.bold)
                        .foregroundColor(AppColors.primaryText)

                    Text("Let's show you around")
                        .font(.appBody)
                        .foregroundColor(AppColors.secondaryText)
                }
                .padding(.top, AppSpacing.xl)

                // Progress indicator with warm colors
                HStack(spacing: AppSpacing.sm) {
                    ForEach(0..<tourSteps.count, id: \.self) { index in
                        Capsule()
                            .fill(index == currentTourStep
                                ? Color(hex: 0xFF8C94)
                                : Color(hex: 0xFFB88C).opacity(0.3))
                            .frame(width: index == currentTourStep ? 24 : 8, height: 8)
                            .animation(.spring(response: 0.3, dampingFraction: 0.7), value: currentTourStep)
                    }
                }
                .padding(.top, AppSpacing.md)

                Spacer()

                // Tour card with cozy animation
                TourCard(
                    step: tourSteps[currentTourStep],
                    currentStep: currentTourStep + 1,
                    totalSteps: tourSteps.count
                )
                .padding(.horizontal, AppSpacing.xl)
                .scaleEffect(showCard ? 1.0 : 0.9)
                .opacity(showCard ? 1.0 : 0)
                .transition(.asymmetric(
                    insertion: .scale.combined(with: .opacity),
                    removal: .scale.combined(with: .opacity)
                ))
                .id(currentTourStep)

                // T014: real-control spotlight. A mock of the actual header
                // speed control + tab bar, with the element this step describes
                // pulsing, so the tour maps onto the live UI.
                spotlightChrome
                    .padding(.horizontal, AppSpacing.xl)
                    .padding(.top, AppSpacing.lg)

                Spacer()

                // Navigation buttons with friendly styling
                HStack(spacing: AppSpacing.md) {
                    // Skip button with soft styling
                    Button(action: {
                        withAnimation(.spring(response: 0.5, dampingFraction: 0.8)) {
                            onComplete()
                        }
                    }) {
                        Text("Skip")
                            .font(.appHeadline)
                            .foregroundColor(Color(hex: 0xFF8C94))
                            .frame(maxWidth: .infinity)
                            .frame(height: AppSpacing.buttonHeight)
                            .background(
                                RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                                    .fill(Color(hex: 0xFF8C94).opacity(0.15))
                            )
                    }

                    // Next/Done button with warm gradient
                    Button(action: {
                        showCard = false
                        withAnimation(.spring(response: 0.5, dampingFraction: 0.8)) {
                            if currentTourStep < tourSteps.count - 1 {
                                currentTourStep += 1
                                // Re-animate card
                                DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                                    withAnimation(.spring(response: 0.4, dampingFraction: 0.7)) {
                                        showCard = true
                                    }
                                }
                            } else {
                                onComplete()
                            }
                        }
                    }) {
                        Text(currentTourStep < tourSteps.count - 1 ? "Next" : "Let's Go!")
                            .font(.appHeadline)
                            .fontWeight(.semibold)
                            .foregroundColor(.white)
                            .frame(maxWidth: .infinity)
                            .frame(height: AppSpacing.buttonHeight)
                            .background(
                                LinearGradient(
                                    gradient: Gradient(colors: [
                                        Color(hex: 0xFFB88C),
                                        Color(hex: 0xFF8C94)
                                    ]),
                                    startPoint: .leading,
                                    endPoint: .trailing
                                )
                            )
                            .cornerRadius(AppSpacing.cornerRadius)
                            .shadow(color: Color(hex: 0xFF8C94).opacity(0.3), radius: 12, y: 6)
                    }
                }
                .padding(.horizontal, AppSpacing.xl)
                .padding(.bottom, AppSpacing.xl)
            }
        }
        .onAppear {
            withAnimation(.spring(response: 0.4, dampingFraction: 0.7).delay(0.2)) {
                showCard = true
            }
            withAnimation(.easeInOut(duration: 0.9).repeatForever(autoreverses: true)) {
                spotlightPulse = true
            }
        }
    }

    // MARK: - Spotlight Chrome (T014)

    private var spotlightChrome: some View {
        VStack(spacing: AppSpacing.sm) {
            // Mock header strip: Speed control + Messages icon (highlighted on
            // the speed step).
            HStack(spacing: AppSpacing.sm) {
                HStack(spacing: 4) {
                    Image(systemName: "speedometer")
                        .font(.system(size: 12, weight: .semibold))
                    Text("Speed of Time")
                        .font(.appCaption)
                    Image(systemName: "plus.circle.fill")
                        .font(.system(size: 14))
                }
                .foregroundColor(AppColors.primaryText)
                .padding(.horizontal, AppSpacing.sm)
                .padding(.vertical, 6)
                .background(
                    Capsule().fill(AppColors.surfaceElevated)
                )
                .overlay(spotlightHeader ? spotlightRing(cornerRadius: 20) : nil)
                .scaleEffect(spotlightHeader && spotlightPulse ? 1.04 : 1.0)

                Spacer()

                Image(systemName: "message.circle.fill")
                    .font(.system(size: 22))
                    .foregroundColor(AppColors.secondaryText)
            }
            .padding(.horizontal, AppSpacing.sm)

            // Mock tab bar with the active step highlighted.
            HStack(spacing: 0) {
                ForEach(Array(mockTabs.enumerated()), id: \.offset) { index, tab in
                    let isActive = !spotlightHeader && index == spotlightTab
                    VStack(spacing: 3) {
                        Image(systemName: tab.icon)
                            .font(.system(size: 18, weight: isActive ? .semibold : .regular))
                        Text(tab.label)
                            .font(.system(size: 10, weight: isActive ? .semibold : .regular))
                    }
                    .foregroundColor(isActive ? AppColors.primary : AppColors.secondaryText.opacity(0.7))
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, AppSpacing.xs)
                    .background(
                        isActive
                            ? RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                                .fill(AppColors.primary.opacity(0.12))
                            : nil
                    )
                    .overlay(isActive ? spotlightRing(cornerRadius: AppSpacing.cornerRadius) : nil)
                    .scaleEffect(isActive && spotlightPulse ? 1.06 : 1.0)
                }
            }
            .padding(AppSpacing.xxs)
            .background(
                RoundedRectangle(cornerRadius: AppSpacing.cornerRadius + 4)
                    .fill(AppColors.surfaceElevated)
                    .shadow(color: Color(hex: 0xFF8C94).opacity(0.12), radius: 12, y: 4)
            )
        }
        .animation(.spring(response: 0.35, dampingFraction: 0.7), value: currentTourStep)
        .accessibilityHidden(true)
    }

    private func spotlightRing(cornerRadius: CGFloat) -> some View {
        RoundedRectangle(cornerRadius: cornerRadius)
            .stroke(AppColors.primary.opacity(spotlightPulse ? 0.8 : 0.4), lineWidth: 2)
    }
}

// MARK: - Tour Step Model
struct TourStep {
    let icon: String
    let title: String
    let description: String
}

// MARK: - Preview
#if DEBUG
struct OnboardingStep3_UITourView_Previews: PreviewProvider {
    static var previews: some View {
        OnboardingStep3_UITourView(onComplete: {})
            .environmentObject(AppViewModel())
    }
}
#endif
