//
//  OnboardingStep4_GuidedActionsView.swift
//  lichunWebsocket
//
//  Guided actions checklist for onboarding
//

import SwiftUI

struct OnboardingStep4_GuidedActionsView: View {
    @EnvironmentObject var appViewModel: AppViewModel
    @EnvironmentObject var webSocketService: WebSocketService
    let onComplete: () -> Void

    let tasks = [
        OnboardingTask(
            id: "talkToCharacter",
            icon: "message.fill",
            title: "Talk to a Character",
            description: "Start a conversation in the Social tab",
            // Social tab (Messages / dating surface)
            destination: .tab(2)
        ),
        OnboardingTask(
            id: "startActivity",
            icon: "figure.run",
            title: "Start an Activity",
            description: "Choose an activity from the Activities tab",
            // Activities tab
            destination: .tab(1)
        ),
        OnboardingTask(
            id: "visitStore",
            icon: "cart.fill",
            title: "Visit the Store",
            description: "Check out items in the Store",
            // Store is a sheet, not a tab
            destination: .store
        )
    ]

    var allTasksComplete: Bool {
        tasks.allSatisfy { appViewModel.isTaskComplete($0.id) }
    }

    @State private var showHeader = false
    @State private var showTasks = false

    /// The task whose destination the user just navigated to. We mark it complete
    /// only once the shared app state actually reaches that destination (real signal),
    /// rather than on a blind timer.
    @State private var pendingTask: OnboardingTask?

    var body: some View {
        ZStack {
            // Warm gradient background
            LinearGradient(
                gradient: Gradient(colors: [
                    Color(hex: 0xFFFAF0),  // Warm ivory
                    Color(hex: 0xFFEFE6),  // Soft peach cream
                    Color(hex: 0xFFE8E8)   // Gentle blush
                ]),
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .edgesIgnoringSafeArea(.all)

            VStack(spacing: AppSpacing.xl) {
                // Friendly header with animation
                VStack(spacing: AppSpacing.sm) {
                    ZStack {
                        // Warm glow
                        Circle()
                            .fill(
                                LinearGradient(
                                    gradient: Gradient(colors: [
                                        Color(hex: 0xFFB88C).opacity(0.3),
                                        Color(hex: 0xFF8C94).opacity(0.3)
                                    ]),
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                            )
                            .frame(width: 80, height: 80)
                            .blur(radius: 10)

                        Image(systemName: "hand.wave.fill")
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(width: 60, height: 60)
                            .foregroundStyle(
                                LinearGradient(
                                    gradient: Gradient(colors: [
                                        Color(hex: 0xFFB88C),
                                        Color(hex: 0xFF8C94)
                                    ]),
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                            )
                    }
                    .scaleEffect(showHeader ? 1.0 : 0.5)
                    .opacity(showHeader ? 1.0 : 0)

                    Text("Let's Get Started!")
                        .font(.appLargeTitle)
                        .fontWeight(.bold)
                        .foregroundColor(AppColors.primaryText)
                        .opacity(showHeader ? 1.0 : 0)
                        .offset(y: showHeader ? 0 : 20)

                    Text("Try these fun activities when you're ready")
                        .font(.appBody)
                        .foregroundColor(AppColors.secondaryText)
                        .multilineTextAlignment(.center)
                        .padding(.horizontal, AppSpacing.xl)
                        .opacity(showHeader ? 1.0 : 0)
                        .offset(y: showHeader ? 0 : 20)
                }
                .padding(.top, AppSpacing.xxl)

                // Task checklist with staggered animation
                VStack(spacing: AppSpacing.md) {
                    ForEach(Array(tasks.enumerated()), id: \.element.id) { index, task in
                        OnboardingTaskCard(
                            task: task,
                            isComplete: appViewModel.isTaskComplete(task.id)
                        ) {
                            // Remember which task the user is acting on, then trigger
                            // the real navigation. Completion is marked via .onChange
                            // below once the shared app state actually lands on the
                            // destination (a real signal, not a blind timer).
                            pendingTask = task
                            switch task.destination {
                            case .tab(let index):
                                appViewModel.selectedTab = index
                            case .store:
                                appViewModel.showStore = true
                            }
                        }
                        .opacity(showTasks ? 1.0 : 0)
                        .offset(x: showTasks ? 0 : -20)
                        .animation(
                            .spring(response: 0.5, dampingFraction: 0.8)
                                .delay(Double(index) * 0.1),
                            value: showTasks
                        )
                    }
                }
                .padding(.horizontal, AppSpacing.xl)

                Spacer()

                // Continue button (only shown when all tasks complete)
                if allTasksComplete {
                    Button(action: {
                        withAnimation(.spring(response: 0.5, dampingFraction: 0.8)) {
                            onComplete()
                        }
                    }) {
                        Text("Continue")
                            .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)
                    .transition(.move(edge: .bottom).combined(with: .opacity))
                } else {
                    // Skip button with warm styling
                    Button(action: {
                        withAnimation(.spring(response: 0.5, dampingFraction: 0.8)) {
                            onComplete()
                        }
                    }) {
                        Text("I'll explore on my own")
                            .font(.appBody)
                            .foregroundColor(Color(hex: 0xFF8C94))
                            .padding(.horizontal, AppSpacing.lg)
                            .padding(.vertical, AppSpacing.sm)
                            .background(
                                Capsule()
                                    .fill(Color(hex: 0xFF8C94).opacity(0.15))
                            )
                    }
                    .padding(.bottom, AppSpacing.sm)
                }

                Spacer()
                    .frame(height: AppSpacing.xl)
            }
        }
        .onAppear {
            // Staggered animations
            withAnimation(.spring(response: 0.5, dampingFraction: 0.7)) {
                showHeader = true
            }

            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                showTasks = true
            }
        }
        // Real completion signal: a tab-navigation task is done once the shared
        // selectedTab actually becomes its target tab.
        .onChange(of: appViewModel.selectedTab) { newTab in
            guard let task = pendingTask, case .tab(let target) = task.destination, newTab == target else { return }
            complete(task)
        }
        // Real completion signal: the store task is done once the Store sheet
        // actually opens (showStore becomes true).
        .onChange(of: appViewModel.showStore) { isPresented in
            guard isPresented, let task = pendingTask, case .store = task.destination else { return }
            complete(task)
        }
    }

    /// Marks a guided action complete and notifies the backend. Driven by real
    /// navigation state changes rather than a fixed timer.
    private func complete(_ task: OnboardingTask) {
        pendingTask = nil
        guard !appViewModel.isTaskComplete(task.id) else { return }
        appViewModel.markTaskComplete(task.id)
        webSocketService.sendMessage(message: WebSocketCommands.tooltipSeen(tooltipId: task.id))
    }
}

// MARK: - Onboarding Task Model

/// Where a guided action should take the user. The live tab bar only has
/// tabs 0 (Home), 1 (Activities), and 2 (Social); the Store is a sheet, not a tab.
enum OnboardingDestination {
    case tab(Int)
    case store
}

struct OnboardingTask {
    let id: String
    let icon: String
    let title: String
    let description: String
    let destination: OnboardingDestination
}

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