//
//  LifeGoalsView.swift
//  lichunWebsocket
//
//  Wave 2: surfaces the player's forward-looking life goals (aspirations).
//  Shows active goals with progress bars + rewards, the overall life score, and
//  completed goals. Just-completed goals are surfaced as a celebratory toast by
//  GameStateStore.handleLifeGoalsUpdate; this screen reads the cached snapshot.
//

import SwiftUI

struct LifeGoalsView: View {
    @EnvironmentObject var webSocketService: WebSocketService

    private var snapshot: LifeGoalsSnapshot? { webSocketService.player.lifeGoals }
    private var activeGoals: [LifeGoal] { snapshot?.active ?? [] }
    private var completedGoals: [LifeGoal] { snapshot?.completed ?? [] }
    private var lifeScore: Int { snapshot?.lifeScore ?? 0 }

    var body: some View {
        ScrollView {
            VStack(spacing: AppSpacing.lg) {
                LifeScoreHeader(score: lifeScore,
                                activeCount: activeGoals.count,
                                completedCount: completedGoals.count)

                if activeGoals.isEmpty && completedGoals.isEmpty {
                    LifeGoalsEmptyState()
                } else {
                    if !activeGoals.isEmpty {
                        VStack(alignment: .leading, spacing: AppSpacing.sm) {
                            SectionHeader(title: "Active Goals")
                            ForEach(activeGoals) { goal in
                                LifeGoalCard(goal: goal, isCompleted: false)
                            }
                        }
                        .padding(.horizontal, AppSpacing.md)
                    }

                    if !completedGoals.isEmpty {
                        VStack(alignment: .leading, spacing: AppSpacing.sm) {
                            SectionHeader(title: "Completed")
                            ForEach(completedGoals) { goal in
                                LifeGoalCard(goal: goal, isCompleted: true)
                            }
                        }
                        .padding(.horizontal, AppSpacing.md)
                    }
                }

                Spacer(minLength: AppSpacing.xl)
            }
            .padding(.bottom, AppSpacing.xl)
        }
        .background(AppColors.background)
        .navigationTitle("Life Goals")
        .navigationBarTitleDisplayMode(.inline)
        .onAppear {
            AnalyticsManager.shared.trackScreenView("life_goals", screenClass: "LifeGoalsView")
        }
    }
}

// MARK: - Life Score Header

private struct LifeScoreHeader: View {
    let score: Int
    let activeCount: Int
    let completedCount: Int

    var body: some View {
        VStack(spacing: AppSpacing.sm) {
            ZStack {
                Circle()
                    .fill(AppColors.prestige.opacity(0.25))
                    .frame(width: 90, height: 90)
                    .blur(radius: 8)
                Circle()
                    .fill(AppColors.prestige.opacity(0.18))
                    .frame(width: 76, height: 76)
                Image(systemName: "target")
                    .font(.system(size: 36))
                    .foregroundColor(AppColors.prestige)
            }

            Text("\(score)")
                .font(.system(size: 34, weight: .bold, design: .rounded))
                .foregroundColor(AppColors.primaryText)

            Text("Life Score")
                .font(.appBody)
                .foregroundColor(AppColors.secondaryText)

            HStack(spacing: AppSpacing.lg) {
                statPill(value: activeCount, label: "Active", color: AppColors.intelligence)
                statPill(value: completedCount, label: "Completed", color: AppColors.success)
            }
            .padding(.top, AppSpacing.xs)
        }
        .padding(.top, AppSpacing.md)
    }

    private func statPill(value: Int, label: String, color: Color) -> some View {
        VStack(spacing: 2) {
            Text("\(value)")
                .font(.appHeadline)
                .foregroundColor(color)
            Text(label)
                .font(.appCaption)
                .foregroundColor(AppColors.secondaryText)
        }
    }
}

// MARK: - Life Goal Card

private struct LifeGoalCard: View {
    let goal: LifeGoal
    let isCompleted: Bool

    private var fraction: Double {
        if isCompleted { return 1.0 }
        return Double(min(max(goal.progressPercent, 0), 100)) / 100.0
    }

    var body: some View {
        BaseCard(backgroundColor: AppColors.surfaceElevated, showShadow: true) {
            VStack(alignment: .leading, spacing: AppSpacing.sm) {
                HStack(spacing: AppSpacing.sm) {
                    ZStack {
                        Circle()
                            .fill((isCompleted ? AppColors.success : AppColors.prestige).opacity(0.15))
                            .frame(width: 44, height: 44)
                        Image(systemName: resolvedIcon)
                            .font(.system(size: 20))
                            .foregroundColor(isCompleted ? AppColors.success : AppColors.prestige)
                    }

                    VStack(alignment: .leading, spacing: 2) {
                        Text(goal.title)
                            .font(.appBodyBold)
                            .foregroundColor(AppColors.primaryText)
                        if !goal.description.isEmpty {
                            Text(goal.description)
                                .font(.appCaption)
                                .foregroundColor(AppColors.secondaryText)
                                .lineLimit(2)
                        }
                    }

                    Spacer()

                    if isCompleted {
                        Image(systemName: "checkmark.seal.fill")
                            .font(.system(size: 22))
                            .foregroundColor(AppColors.success)
                    }
                }

                if !isCompleted {
                    ProgressBar(
                        value: fraction,
                        foregroundColor: AppColors.prestige,
                        showLabel: true
                    )
                    if goal.target > 0 {
                        Text("\(goal.current)/\(goal.target)")
                            .font(.appCaption)
                            .foregroundColor(AppColors.secondaryText)
                    }
                }

                HStack(spacing: AppSpacing.md) {
                    if goal.reward > 0 {
                        rewardBadge(icon: "dollarsign.circle.fill",
                                    text: "$\(goal.reward)",
                                    color: AppColors.money)
                    }
                    if goal.lifeScore > 0 {
                        rewardBadge(icon: "star.fill",
                                    text: "+\(goal.lifeScore) score",
                                    color: AppColors.prestige)
                    }
                    Spacer()
                }
            }
        }
        .opacity(isCompleted ? 0.85 : 1.0)
    }

    private var resolvedIcon: String { goal.icon.isEmpty ? "flag.fill" : goal.icon }

    private func rewardBadge(icon: String, text: String, color: Color) -> some View {
        HStack(spacing: 4) {
            Image(systemName: icon)
                .font(.system(size: 11))
            Text(text)
                .font(.appCaptionBold)
        }
        .foregroundColor(color)
        .padding(.horizontal, AppSpacing.sm)
        .padding(.vertical, 4)
        .background(color.opacity(0.12))
        .cornerRadius(AppSpacing.smallCornerRadius)
    }
}

// MARK: - Empty State

private struct LifeGoalsEmptyState: View {
    var body: some View {
        VStack(spacing: AppSpacing.md) {
            Image(systemName: "target")
                .font(.system(size: 48))
                .foregroundColor(AppColors.secondaryText.opacity(0.5))
            Text("No life goals yet")
                .font(.appHeadline)
                .foregroundColor(AppColors.primaryText)
            Text("Keep living and your aspirations will appear here as you grow through each life stage.")
                .font(.appBody)
                .foregroundColor(AppColors.secondaryText)
                .multilineTextAlignment(.center)
                .padding(.horizontal, AppSpacing.lg)
        }
        .padding(.top, AppSpacing.xl)
    }
}

// MARK: - Preview
// Preview removed - requires backend connection
