//
//  QuestDepthSection.swift
//  lichunWebsocket
//
//  Wave 2: extends the daily-quests surface with the deeper quest loop:
//   - the full-clear streak (consecutive days all daily quests were cleared) and
//     the N-day bonus it works toward,
//   - the rolled weekly challenge with its larger diamond payoff,
//   - a short explainer of quest chains (completing a quest unlocks a follow-up).
//
//  Sourced from the cached questEngagement snapshot (rides in playerObject).
//  Streak / weekly / chain rewards are auto-awarded server-side, so this surface
//  is read-only status (no claim buttons).
//

import SwiftUI

struct QuestDepthSection: View {
    let engagement: QuestEngagementSnapshot?

    private var streak: Int { engagement?.fullClearStreak ?? 0 }
    private var weekly: WeeklyChallenge? { engagement?.weekly }

    var body: some View {
        VStack(alignment: .leading, spacing: AppSpacing.sm) {
            FullClearStreakCard(
                streak: streak,
                daysToBonus: engagement?.daysToNextBonus ?? QuestEngagementSnapshot.streakBonusThreshold
            )

            if let weekly = weekly {
                WeeklyChallengeCard(challenge: weekly)
            }

            QuestChainsExplainer()
        }
    }
}

// MARK: - Full-Clear Streak

private struct FullClearStreakCard: View {
    let streak: Int
    let daysToBonus: Int

    var body: some View {
        BaseCard(backgroundColor: AppColors.surfaceElevated, showShadow: true) {
            HStack(spacing: AppSpacing.md) {
                ZStack {
                    Circle()
                        .fill(AppColors.warning.opacity(0.15))
                        .frame(width: 48, height: 48)
                    Image(systemName: "flame.fill")
                        .font(.system(size: 24))
                        .foregroundColor(AppColors.warning)
                }

                VStack(alignment: .leading, spacing: 2) {
                    Text("Full-Clear Streak")
                        .font(.appBodyBold)
                        .foregroundColor(AppColors.primaryText)
                    Text(subtitle)
                        .font(.appCaption)
                        .foregroundColor(AppColors.secondaryText)
                }

                Spacer()

                VStack(spacing: 0) {
                    Text("\(streak)")
                        .font(.system(size: 26, weight: .bold, design: .rounded))
                        .foregroundColor(AppColors.warning)
                    Text(streak == 1 ? "day" : "days")
                        .font(.appCaption)
                        .foregroundColor(AppColors.secondaryText)
                }
            }
        }
    }

    private var subtitle: String {
        let reward = QuestEngagementSnapshot.streakBonusReward
        if streak == 0 {
            return "Clear all daily quests to start a streak. Reward at \(QuestEngagementSnapshot.streakBonusThreshold) days."
        }
        if daysToBonus <= 1 {
            return "1 more full-clear day for a \(reward) diamond bonus!"
        }
        return "\(daysToBonus) more full-clear days for a \(reward) diamond bonus."
    }
}

// MARK: - Weekly Challenge

private struct WeeklyChallengeCard: View {
    let challenge: WeeklyChallenge

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

                    VStack(alignment: .leading, spacing: 2) {
                        Text("Weekly Challenge")
                            .font(.appBodyBold)
                            .foregroundColor(AppColors.primaryText)
                        Text(challenge.description)
                            .font(.appCaption)
                            .foregroundColor(AppColors.secondaryText)
                            .lineLimit(2)
                    }

                    Spacer()

                    statusBadge
                }

                if !challenge.claimed {
                    HStack {
                        Text(challenge.progressText)
                            .font(.appCaptionBold)
                            .foregroundColor(AppColors.primaryText)
                        Spacer()
                        Text("\(Int(challenge.progressFraction * 100))%")
                            .font(.appCaption)
                            .foregroundColor(AppColors.secondaryText)
                    }
                    ProgressBar(value: challenge.progressFraction, foregroundColor: AppColors.intelligence)
                }

                HStack(spacing: 4) {
                    Image(systemName: "gem.fill")
                        .font(.system(size: 12))
                        .foregroundColor(AppColors.diamond)
                    Text("\(challenge.diamondReward) diamonds")
                        .font(.appCaptionBold)
                        .foregroundColor(AppColors.primaryText)
                    Text("• bigger weekly payoff")
                        .font(.appCaption)
                        .foregroundColor(AppColors.secondaryText)
                }
            }
        }
    }

    private var statusBadge: some View {
        Group {
            if challenge.claimed {
                badge(text: "Earned", icon: "checkmark.seal.fill", color: AppColors.success)
            } else if challenge.completed {
                badge(text: "Complete", icon: "star.fill", color: AppColors.accent)
            } else {
                badge(text: "Active", icon: "clock.fill", color: AppColors.info)
            }
        }
    }

    private func badge(text: String, icon: String, color: Color) -> some View {
        HStack(spacing: 4) {
            Image(systemName: icon).font(.caption2)
            Text(text).font(.appCaption)
        }
        .foregroundColor(color)
        .padding(.horizontal, AppSpacing.sm)
        .padding(.vertical, 4)
        .background(color.opacity(0.15))
        .cornerRadius(AppSpacing.smallCornerRadius)
    }
}

// MARK: - Quest Chains Explainer

private struct QuestChainsExplainer: View {
    var body: some View {
        HStack(spacing: AppSpacing.sm) {
            Image(systemName: "link")
                .font(.system(size: 16))
                .foregroundColor(AppColors.primary)
            Text("Complete a daily quest to unlock a bonus follow-up quest in the same category.")
                .font(.appCaption)
                .foregroundColor(AppColors.secondaryText)
            Spacer(minLength: 0)
        }
        .padding(AppSpacing.sm)
        .background(AppColors.primary.opacity(0.08))
        .cornerRadius(AppSpacing.smallCornerRadius)
    }
}
