//
//  MatchCelebrationView.swift
//  lichunWebsocket
//
//  Full-screen celebratory moment shown right after a swipe match.
//  Replaces the old top-anchored MatchExplanationToast (which floated awkwardly
//  inside a full-screen sheet, hid who you matched with, and offered no way to
//  start the conversation). This makes the post-match moment feel intentional:
//  it shows the matched person and gives clear next steps.
//

import SwiftUI

struct MatchCelebrationView: View {
    let partner: Person
    let explanation: MatchExplanation
    /// Open the chat with the new match.
    let onSendMessage: () -> Void
    /// Dismiss and continue swiping.
    let onKeepSwiping: () -> Void

    @State private var cardAppeared = false
    @State private var heartPulse = false

    var body: some View {
        ZStack {
            // Soft romantic backdrop so the card reads as a celebratory overlay.
            LinearGradient(
                colors: [
                    AppColors.primary.opacity(0.35),
                    Color(hex: 0xD4A5F5).opacity(0.25),
                    AppColors.primaryBackground
                ],
                startPoint: .top,
                endPoint: .bottom
            )
            .ignoresSafeArea()

            ScrollView {
                VStack(spacing: AppSpacing.lg) {
                    Spacer(minLength: AppSpacing.xl)

                    matchHeader

                    partnerCard

                    if !explanation.reasons.isEmpty {
                        reasonsSection
                    }

                    actionButtons

                    Spacer(minLength: AppSpacing.lg)
                }
                .padding(.horizontal, AppSpacing.lg)
                .frame(maxWidth: .infinity)
            }
        }
        .onAppear {
            withAnimation(.spring(response: 0.55, dampingFraction: 0.7)) {
                cardAppeared = true
            }
            withAnimation(.easeInOut(duration: 1.1).repeatForever(autoreverses: true)) {
                heartPulse = true
            }
        }
    }

    // MARK: - Header

    private var matchHeader: some View {
        VStack(spacing: AppSpacing.sm) {
            ZStack {
                Circle()
                    .fill(
                        RadialGradient(
                            colors: [
                                AppColors.primary.opacity(0.35),
                                AppColors.primary.opacity(0.0)
                            ],
                            center: .center,
                            startRadius: 10,
                            endRadius: 55
                        )
                    )
                    .frame(width: 96, height: 96)
                    .scaleEffect(heartPulse ? 1.08 : 0.92)

                Image(systemName: "heart.fill")
                    .font(.system(size: 56))
                    .foregroundStyle(
                        LinearGradient(
                            colors: [AppColors.primary, AppColors.primaryDark],
                            startPoint: .top,
                            endPoint: .bottom
                        )
                    )
                    .shadow(color: AppColors.primary.opacity(0.5), radius: 14, x: 0, y: 6)
                    .scaleEffect(heartPulse ? 1.06 : 0.96)
            }

            Text("It's a Match!")
                .font(.appLargeTitle)
                .foregroundColor(AppColors.primaryText)
                .multilineTextAlignment(.center)

            Text("You and \(partner.firstname) liked each other")
                .font(.appBody)
                .foregroundColor(AppColors.secondaryText)
                .multilineTextAlignment(.center)
        }
        .scaleEffect(cardAppeared ? 1 : 0.85)
        .opacity(cardAppeared ? 1 : 0)
    }

    // MARK: - Partner Card

    private var partnerCard: some View {
        BaseCard {
            VStack(spacing: AppSpacing.md) {
                CharacterAvatar(
                    person: partner,
                    size: 110,
                    showBorder: true,
                    borderGradient: [AppColors.primary, AppColors.primaryDark],
                    showGlow: true
                )

                VStack(spacing: AppSpacing.xs) {
                    Text("\(partner.firstname) \(partner.lastname)")
                        .font(.appTitle)
                        .foregroundColor(AppColors.primaryText)
                        .multilineTextAlignment(.center)

                    HStack(spacing: AppSpacing.xs) {
                        Text("\(partner.ageYears)")
                            .font(.appBody)
                            .foregroundColor(AppColors.secondaryText)

                        if !partner.occupation.isEmpty {
                            Text("•")
                                .foregroundColor(AppColors.secondaryText)
                            Text(partner.occupation)
                                .font(.appBody)
                                .foregroundColor(AppColors.secondaryText)
                                .lineLimit(1)
                        }
                    }
                }

                if explanation.compatibilityScore > 0 {
                    HStack(spacing: AppSpacing.xs) {
                        Image(systemName: "sparkles")
                            .font(.system(size: 13))
                        Text("\(explanation.compatibilityScore)% compatible")
                            .font(.appCaption)
                    }
                    .foregroundColor(AppColors.primary)
                    .padding(.horizontal, AppSpacing.sm)
                    .padding(.vertical, 5)
                    .background(AppColors.primary.opacity(0.15))
                    .cornerRadius(12)
                }
            }
            .frame(maxWidth: .infinity)
            .padding(AppSpacing.sm)
        }
        .scaleEffect(cardAppeared ? 1 : 0.9)
        .opacity(cardAppeared ? 1 : 0)
    }

    // MARK: - Reasons

    private var reasonsSection: some View {
        VStack(alignment: .leading, spacing: AppSpacing.xs) {
            Text("Why you matched")
                .font(.appHeadline)
                .foregroundColor(AppColors.primaryText)

            ForEach(explanation.reasons, id: \.self) { reason in
                HStack(spacing: AppSpacing.sm) {
                    Image(systemName: "checkmark.circle.fill")
                        .font(.system(size: 14))
                        .foregroundColor(AppColors.primary)
                    Text(reason)
                        .font(.appBody)
                        .foregroundColor(AppColors.secondaryText)
                    Spacer()
                }
            }
        }
        .frame(maxWidth: .infinity, alignment: .leading)
        .padding(AppSpacing.md)
        .background(AppColors.surfaceElevated.opacity(0.6))
        .cornerRadius(AppSpacing.cornerRadius)
        .opacity(cardAppeared ? 1 : 0)
    }

    // MARK: - Actions

    private var actionButtons: some View {
        VStack(spacing: AppSpacing.sm) {
            PrimaryButton(title: "Send a Message") {
                onSendMessage()
            }

            SecondaryButton(title: "Keep Swiping") {
                onKeepSwiping()
            }
        }
        .padding(.top, AppSpacing.xs)
        .opacity(cardAppeared ? 1 : 0)
    }
}

// MARK: - Preview

#if DEBUG
struct MatchCelebrationView_Previews: PreviewProvider {
    static var previews: some View {
        MatchCelebrationView(
            partner: previewPerson(),
            explanation: MatchExplanation(
                matchedPersonName: "Stella",
                compatibilityScore: 87,
                reasons: ["87% compatible", "3 shared interests", "Similar age and life stage"]
            ),
            onSendMessage: {},
            onKeepSwiping: {}
        )
    }

    static func previewPerson() -> Person {
        let p = Person()
        p.firstname = "Stella"
        p.lastname = "Thompson"
        p.ageYears = 27
        p.occupation = "Architect"
        p.image = "https://api.dicebear.com/7.x/avataaars/svg?seed=Stella"
        return p
    }
}
#endif
