//
//  AchievementCollectionView.swift
//  lichunWebsocket
//
//  Wave 2: a collection / trophy-case screen driven by the per-category
//  achievement summary (`achievementsList.summary`). Each category section lists
//  locked + unlocked achievements with progress + hint. Secret achievements show
//  a teaser (??? / "Secret achievement") until discovered, and each category
//  shows its completion %.
//

import SwiftUI

struct AchievementCollectionView: View {
    @EnvironmentObject var webSocketService: WebSocketService

    private var summary: AchievementSummary? { webSocketService.achievementSummary }

    var body: some View {
        ScrollView {
            VStack(spacing: AppSpacing.lg) {
                if let summary = summary {
                    CollectionOverallHeader(summary: summary)

                    ForEach(summary.orderedCategories, id: \.key) { item in
                        CategorySection(categoryKey: item.key, summary: item.summary)
                    }
                } else {
                    CollectionLoadingState()
                }

                Spacer(minLength: AppSpacing.xl)
            }
            .padding(.bottom, AppSpacing.xl)
        }
        .background(AppColors.background)
        .navigationTitle("Collection")
        .navigationBarTitleDisplayMode(.inline)
        .onAppear {
            // Reuse the existing getAchievements command; the server includes the
            // collection summary alongside the flat list.
            webSocketService.fetchAchievements()
            AnalyticsManager.shared.trackScreenView("achievement_collection", screenClass: "AchievementCollectionView")
        }
    }
}

// MARK: - Overall Header

private struct CollectionOverallHeader: View {
    let summary: AchievementSummary

    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: "trophy.fill")
                    .font(.system(size: 34))
                    .foregroundColor(AppColors.prestige)
            }

            Text("\(summary.unlocked) / \(summary.total)")
                .font(.system(size: 30, weight: .bold, design: .rounded))
                .foregroundColor(AppColors.primaryText)

            Text("\(summary.progressPercent)% collected")
                .font(.appBody)
                .foregroundColor(AppColors.secondaryText)

            ProgressBar(
                value: Double(min(max(summary.progressPercent, 0), 100)) / 100.0,
                foregroundColor: AppColors.prestige
            )
            .padding(.horizontal, AppSpacing.xl)
        }
        .padding(.top, AppSpacing.md)
    }
}

// MARK: - Category Section

private struct CategorySection: View {
    let categoryKey: String
    let summary: CategorySummary

    var body: some View {
        VStack(alignment: .leading, spacing: AppSpacing.sm) {
            HStack(spacing: AppSpacing.sm) {
                Image(systemName: AchievementCategoryDisplay.icon(for: categoryKey))
                    .font(.system(size: 16))
                    .foregroundColor(AppColors.prestige)
                Text(AchievementCategoryDisplay.title(for: categoryKey))
                    .font(.appHeadline)
                    .foregroundColor(AppColors.primaryText)
                Spacer()
                Text("\(summary.unlocked)/\(summary.total)  •  \(summary.progressPercent)%")
                    .font(.appCaptionBold)
                    .foregroundColor(AppColors.secondaryText)
            }

            ProgressBar(value: summary.progressFraction, foregroundColor: AppColors.prestige)

            ForEach(summary.entries) { entry in
                CollectionEntryRow(entry: entry)
            }
        }
        .padding(.horizontal, AppSpacing.md)
    }
}

// MARK: - Entry Row

private struct CollectionEntryRow: View {
    let entry: CollectionEntry

    var body: some View {
        BaseCard(backgroundColor: AppColors.surfaceElevated, showShadow: true) {
            HStack(spacing: AppSpacing.md) {
                ZStack {
                    Circle()
                        .fill((entry.unlocked ? AppColors.success : AppColors.disabledText).opacity(0.15))
                        .frame(width: 44, height: 44)
                    Image(systemName: entry.resolvedIcon)
                        .font(.system(size: 20))
                        .foregroundColor(entry.unlocked ? AppColors.success : AppColors.disabledText.opacity(0.6))
                }

                VStack(alignment: .leading, spacing: 2) {
                    HStack(spacing: 6) {
                        Text(entry.displayName)
                            .font(.appBodyBold)
                            .foregroundColor(AppColors.primaryText)
                        if entry.hidden && !entry.unlocked {
                            Image(systemName: "lock.fill")
                                .font(.system(size: 10))
                                .foregroundColor(AppColors.secondaryText)
                        }
                    }
                    Text(entry.displaySubtitle)
                        .font(.appCaption)
                        .foregroundColor(AppColors.secondaryText)
                        .lineLimit(2)
                }

                Spacer()

                if entry.reward > 0 {
                    HStack(spacing: 4) {
                        Image(systemName: "gem.fill")
                            .font(.system(size: 11))
                        Text("\(entry.reward)")
                            .font(.appCaptionBold)
                    }
                    .foregroundColor(entry.unlocked ? AppColors.diamond : AppColors.disabledText.opacity(0.6))
                }
            }
        }
        .opacity(entry.unlocked ? 1.0 : 0.85)
    }
}

// MARK: - Loading State

private struct CollectionLoadingState: View {
    var body: some View {
        VStack(spacing: AppSpacing.md) {
            ProgressView()
            Text("Loading your collection...")
                .font(.appBody)
                .foregroundColor(AppColors.secondaryText)
        }
        .padding(.top, AppSpacing.xxl)
    }
}

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