//
//  DeathView.swift
//  lichunWebsocket
//
//  Memorial / end-of-life recap shown when the character dies. Renders the
//  server-built LifeSummary (score, net worth, peak career, relationships,
//  children, notable events, achievements) and offers a New Life chooser:
//  "Continue as <heir>" (heir mode, when an heir + inheritance is present) or
//  "Start Fresh" (fresh mode, always).
//

import SwiftUI

struct DeathView: View {
    @EnvironmentObject var webSocketService: WebSocketService

    @State private var isLoaded = false
    @State private var candleFlicker = false
    @State private var starsOpacity = 0.3
    @State private var showLegacyTree = false

    private var summary: LifeSummary? { webSocketService.player.lifeSummary }
    private var legacy: LegacyData? { webSocketService.player.lifeSummary?.legacy }
    private var heir: HeirInfo? { legacy?.heir }

    var body: some View {
        ZStack {
            // Peaceful gradient background - deep twilight colors
            LinearGradient(
                colors: [
                    Color(red: 0.15, green: 0.12, blue: 0.25),  // Deep purple
                    Color(red: 0.1, green: 0.08, blue: 0.2),    // Darker purple
                    Color(red: 0.05, green: 0.05, blue: 0.15)   // Almost black purple
                ],
                startPoint: .top,
                endPoint: .bottom
            )
            .edgesIgnoringSafeArea(.all)

            // Soft twinkling stars. Constrained to a non-interactive overlay so
            // the absolute .position() coordinates can never inflate the parent
            // layout or steal taps from the scroll/footer content below.
            GeometryReader { geo in
                ForEach(0..<20) { index in
                    Circle()
                        .fill(Color.white.opacity(starsOpacity))
                        .frame(width: CGFloat.random(in: 2...4), height: CGFloat.random(in: 2...4))
                        .position(
                            x: CGFloat.random(in: 0...geo.size.width),
                            y: CGFloat.random(in: 0...geo.size.height * 0.6)
                        )
                        .animation(
                            .easeInOut(duration: Double.random(in: 2...4))
                            .repeatForever(autoreverses: true)
                            .delay(Double(index) * 0.2),
                            value: starsOpacity
                        )
                }
            }
            .allowsHitTesting(false)

            // Scrollable life-summary recap. The New Life CTAs live in a pinned
            // bottom footer (safeAreaInset) so they stay visible + tappable above
            // the home indicator on every device size.
            ScrollView {
                VStack(spacing: AppSpacing.xl) {
                    Spacer()
                        .frame(height: AppSpacing.xl)

                    candle

                    memorialHeader

                    scoreCard

                    statsGrid

                    notableEventsCard

                    legacyTeaser

                    Spacer()
                        .frame(height: AppSpacing.lg)
                }
                .padding(.horizontal, AppSpacing.xl)
            }
            .safeAreaInset(edge: .bottom) {
                newLifeChooser
                    .padding(.horizontal, AppSpacing.xl)
                    .padding(.top, AppSpacing.md)
                    .padding(.bottom, AppSpacing.sm)
                    .background(.ultraThinMaterial)
            }
        }
        .sheet(isPresented: $showLegacyTree) {
            LegacyTreeView()
                .environmentObject(webSocketService)
        }
        .onAppear {
            withAnimation(.spring(response: 1.0, dampingFraction: 0.75)) {
                isLoaded = true
            }
            withAnimation(.easeInOut(duration: 1.5).repeatForever(autoreverses: true)) {
                candleFlicker = true
            }
            withAnimation(.easeInOut(duration: 3.0).repeatForever(autoreverses: true)) {
                starsOpacity = 0.7
            }
        }
    }

    // MARK: - Candle

    private var candle: some View {
        ZStack {
            Circle()
                .fill(
                    RadialGradient(
                        colors: [
                            Color.orange.opacity(candleFlicker ? 0.4 : 0.3),
                            Color.orange.opacity(0.1),
                            Color.clear
                        ],
                        center: .center,
                        startRadius: 20,
                        endRadius: 80
                    )
                )
                .frame(width: 160, height: 160)
                .blur(radius: 20)

            Image(systemName: "flame.fill")
                .font(.system(size: 60))
                .foregroundStyle(
                    LinearGradient(
                        colors: [Color.yellow.opacity(0.9), Color.orange.opacity(0.9)],
                        startPoint: .top,
                        endPoint: .bottom
                    )
                )
                .shadow(color: Color.orange.opacity(0.8), radius: candleFlicker ? 20 : 15, x: 0, y: 0)
                .scaleEffect(candleFlicker ? 1.05 : 1.0)
                .offset(y: candleFlicker ? -2 : 0)
        }
        .opacity(isLoaded ? 1 : 0)
        .scaleEffect(isLoaded ? 1 : 0.5)
    }

    // MARK: - Header

    private var memorialHeader: some View {
        VStack(spacing: AppSpacing.md) {
            Text("In Loving Memory")
                .font(.system(size: 24, weight: .semibold, design: .serif))
                .foregroundColor(.white.opacity(0.95))
                .tracking(2)
                .opacity(isLoaded ? 1 : 0)
                .offset(y: isLoaded ? 0 : -20)

            Text(webSocketService.person.firstname + " " + webSocketService.person.lastname)
                .font(.system(size: 34, weight: .bold, design: .serif))
                .minimumScaleFactor(0.6)
                .lineLimit(2)
                .multilineTextAlignment(.center)
                .foregroundStyle(
                    LinearGradient(
                        colors: [Color.white, Color.white.opacity(0.8)],
                        startPoint: .top,
                        endPoint: .bottom
                    )
                )
                .opacity(isLoaded ? 1 : 0)
                .scaleEffect(isLoaded ? 1 : 0.9)

            if let finalAge = summary?.finalAge, finalAge > 0 {
                Text("\(finalAge) years lived")
                    .font(.appCaption)
                    .foregroundColor(.white.opacity(0.6))
            } else if webSocketService.person.ageYears > 0 {
                Text("\(webSocketService.person.ageYears) years lived")
                    .font(.appCaption)
                    .foregroundColor(.white.opacity(0.6))
            }
        }
    }

    // MARK: - Score (prominent)

    private var scoreCard: some View {
        BaseCard(
            backgroundColor: Color.white.opacity(0.1),
            borderColor: Color.white.opacity(0.2),
            showShadow: false
        ) {
            VStack(spacing: AppSpacing.xs) {
                Text("LIFE SCORE")
                    .font(.system(size: 12, weight: .bold))
                    .tracking(3)
                    .foregroundColor(.white.opacity(0.6))

                Text("\(summary?.score ?? 0)")
                    .font(.system(size: 56, weight: .heavy, design: .rounded))
                    .foregroundStyle(
                        LinearGradient(
                            colors: [Color.yellow, Color.orange],
                            startPoint: .top,
                            endPoint: .bottom
                        )
                    )
                    .minimumScaleFactor(0.5)
                    .lineLimit(1)
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, AppSpacing.sm)
        }
        .opacity(isLoaded ? 1 : 0)
        .offset(y: isLoaded ? 0 : 20)
        .animation(.spring(response: 0.6, dampingFraction: 0.75).delay(0.3), value: isLoaded)
    }

    // MARK: - Stats grid

    private var statsGrid: some View {
        BaseCard(
            backgroundColor: Color.white.opacity(0.08),
            borderColor: Color.white.opacity(0.15),
            showShadow: false
        ) {
            VStack(spacing: AppSpacing.sm) {
                statRow(icon: "dollarsign.circle.fill",
                        label: "Net Worth",
                        value: formatMoney(summary?.netWorth ?? webSocketService.person.money))

                if let career = summary?.peakCareer, !career.title.isEmpty {
                    statRow(icon: "briefcase.fill",
                            label: "Peak Career",
                            value: career.title)
                    if career.bestIncome > 0 {
                        statRow(icon: "chart.line.uptrend.xyaxis",
                                label: "Best Income",
                                value: formatMoney(career.bestIncome))
                    }
                }

                statRow(icon: "person.2.fill",
                        label: "Relationships",
                        value: "\(summary?.relationshipsCount ?? 0)")

                statRow(icon: "figure.2.and.child.holdinghands",
                        label: "Children",
                        value: "\(summary?.childrenCount ?? 0)")

                if let achievements = summary?.achievementsEarned, achievements > 0 {
                    statRow(icon: "trophy.fill",
                            label: "Achievements",
                            value: "\(achievements)")
                }

                if let earnings = summary?.lifetimeEarnings, earnings > 0 {
                    statRow(icon: "banknote.fill",
                            label: "Lifetime Earnings",
                            value: formatMoney(earnings))
                }
            }
        }
        .opacity(isLoaded ? 1 : 0)
        .offset(y: isLoaded ? 0 : 20)
        .animation(.spring(response: 0.6, dampingFraction: 0.75).delay(0.35), value: isLoaded)
    }

    private func statRow(icon: String, label: String, value: String) -> some View {
        HStack {
            Image(systemName: icon)
                .font(.system(size: 16))
                .foregroundColor(.white.opacity(0.7))
                .frame(width: 24)
            Text(label)
                .font(.appBody)
                .foregroundColor(.white.opacity(0.7))
            Spacer()
            Text(value)
                .font(.appHeadline)
                .foregroundColor(.white.opacity(0.95))
                .minimumScaleFactor(0.6)
                .lineLimit(1)
        }
    }

    // MARK: - Notable events

    @ViewBuilder
    private var notableEventsCard: some View {
        if let events = summary?.notableEvents, !events.isEmpty {
            BaseCard(
                backgroundColor: Color.white.opacity(0.05),
                borderColor: Color.white.opacity(0.1),
                showShadow: false
            ) {
                VStack(alignment: .leading, spacing: AppSpacing.sm) {
                    Text("Notable Moments")
                        .font(.system(size: 15, weight: .semibold, design: .serif))
                        .foregroundColor(.white.opacity(0.8))

                    ForEach(Array(events.enumerated()), id: \.offset) { _, event in
                        HStack(alignment: .top, spacing: AppSpacing.sm) {
                            Image(systemName: "sparkle")
                                .font(.system(size: 12))
                                .foregroundColor(Color.yellow.opacity(0.7))
                                .padding(.top, 3)
                            Text(event)
                                .font(.appBody)
                                .foregroundColor(.white.opacity(0.7))
                                .fixedSize(horizontal: false, vertical: true)
                        }
                    }
                }
                .frame(maxWidth: .infinity, alignment: .leading)
            }
            .opacity(isLoaded ? 1 : 0)
            .offset(y: isLoaded ? 0 : 20)
            .animation(.spring(response: 0.6, dampingFraction: 0.75).delay(0.4), value: isLoaded)
        }
    }

    // MARK: - Legacy teaser

    @ViewBuilder
    private var legacyTeaser: some View {
        if !webSocketService.player.familyTree.isEmpty || webSocketService.player.familyPrestige > 0 {
            Button {
                hapticFeedback(style: .light)
                showLegacyTree = true
            } label: {
                HStack(spacing: AppSpacing.sm) {
                    Image(systemName: "tree.fill")
                        .font(.system(size: 16))
                        .foregroundColor(Color.green.opacity(0.8))
                    VStack(alignment: .leading, spacing: 2) {
                        Text("View Family Legacy")
                            .font(.appHeadline)
                            .foregroundColor(.white.opacity(0.9))
                        Text("Family Prestige \(webSocketService.player.familyPrestige) - \(webSocketService.player.familyTree.count) generation\(webSocketService.player.familyTree.count == 1 ? "" : "s")")
                            .font(.appCaption)
                            .foregroundColor(.white.opacity(0.55))
                    }
                    Spacer()
                    Image(systemName: "chevron.right")
                        .font(.system(size: 14))
                        .foregroundColor(.white.opacity(0.5))
                }
                .padding(AppSpacing.md)
                .background(Color.white.opacity(0.06))
                .cornerRadius(AppSpacing.pillCornerRadius)
                .overlay(
                    RoundedRectangle(cornerRadius: AppSpacing.pillCornerRadius)
                        .strokeBorder(Color.white.opacity(0.15), lineWidth: 1)
                )
            }
            .buttonStyle(SquishButtonStyle())
            .opacity(isLoaded ? 1 : 0)
            .animation(.spring(response: 0.6, dampingFraction: 0.75).delay(0.45), value: isLoaded)
        }
    }

    // MARK: - New Life chooser

    private var newLifeChooser: some View {
        VStack(spacing: AppSpacing.md) {
            // Continue as heir — only when a living heir exists.
            if let heir = heir {
                Button {
                    hapticFeedback(style: .medium)
                    webSocketService.startNewLife(mode: "heir")
                } label: {
                    VStack(spacing: AppSpacing.xs) {
                        HStack(spacing: AppSpacing.sm) {
                            Image(systemName: "figure.child")
                                .font(.system(size: 20))
                            Text("Continue as \(heir.name)")
                                .font(.appHeadline)
                                .minimumScaleFactor(0.7)
                                .lineLimit(1)
                        }
                        if let inheritance = legacy?.inheritance, inheritance > 0 {
                            Text("Inherits \(formatMoney(inheritance)) - Prestige \(legacy?.familyPrestige ?? webSocketService.player.familyPrestige)")
                                .font(.appCaption)
                                .opacity(0.85)
                        } else {
                            Text("Carry on the family legacy - Prestige \(legacy?.familyPrestige ?? webSocketService.player.familyPrestige)")
                                .font(.appCaption)
                                .opacity(0.85)
                        }
                    }
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, AppSpacing.md)
                    .background(
                        LinearGradient(
                            colors: [Color.purple.opacity(0.55), Color.indigo.opacity(0.5)],
                            startPoint: .top,
                            endPoint: .bottom
                        )
                    )
                    .cornerRadius(AppSpacing.pillCornerRadius)
                    .overlay(
                        RoundedRectangle(cornerRadius: AppSpacing.pillCornerRadius)
                            .strokeBorder(Color.white.opacity(0.3), lineWidth: 1)
                    )
                    .shadow(color: Color.purple.opacity(0.3), radius: 10, x: 0, y: 4)
                }
                .buttonStyle(SquishButtonStyle())
            }

            // Start fresh — always available.
            Button {
                hapticFeedback(style: .medium)
                webSocketService.startNewLife(mode: "fresh")
            } label: {
                HStack(spacing: AppSpacing.sm) {
                    Image(systemName: "arrow.counterclockwise.circle.fill")
                        .font(.system(size: 20))
                    Text(heir == nil ? "Begin a New Journey" : "Start Fresh")
                        .font(.appHeadline)
                }
                .foregroundColor(.white)
                .frame(maxWidth: .infinity)
                .frame(height: AppSpacing.buttonHeight)
                .background(
                    LinearGradient(
                        colors: [Color.white.opacity(0.2), Color.white.opacity(0.15)],
                        startPoint: .top,
                        endPoint: .bottom
                    )
                )
                .cornerRadius(AppSpacing.pillCornerRadius)
                .overlay(
                    RoundedRectangle(cornerRadius: AppSpacing.pillCornerRadius)
                        .strokeBorder(Color.white.opacity(0.3), lineWidth: 1)
                )
                .shadow(color: Color.white.opacity(0.1), radius: 10, x: 0, y: 4)
            }
            .buttonStyle(SquishButtonStyle())
        }
        .opacity(isLoaded ? 1 : 0)
        .scaleEffect(isLoaded ? 1 : 0.9)
        .animation(.spring(response: 0.6, dampingFraction: 0.75).delay(0.5), value: isLoaded)
    }

    // MARK: - Helpers

    private func formatMoney(_ amount: Int) -> String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.maximumFractionDigits = 0
        let str = formatter.string(from: NSNumber(value: amount)) ?? "\(amount)"
        return "$\(str)"
    }
}

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