//
//  LegacyTreeView.swift
//  lichunWebsocket
//
//  Renders the persistent generational family tree (player.familyTree) and the
//  compounding family prestige (player.familyPrestige). Reachable from the
//  death screen and intended to be reachable from a profile entry as well.
//

import SwiftUI

struct LegacyTreeView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @Environment(\.dismiss) private var dismiss

    private var familyTree: [FamilyTreeEntry] {
        // Show founder → most recent (highest generation last).
        webSocketService.player.familyTree.sorted { $0.generation < $1.generation }
    }
    private var familyPrestige: Int { webSocketService.player.familyPrestige }

    var body: some View {
        NavigationView {
            ZStack {
                AppColors.primaryBackground
                    .edgesIgnoringSafeArea(.all)

                ScrollView {
                    VStack(spacing: AppSpacing.lg) {
                        prestigeBanner

                        if familyTree.isEmpty {
                            emptyState
                        } else {
                            ForEach(Array(familyTree.enumerated()), id: \.element.id) { index, entry in
                                ancestorCard(entry, isLast: index == familyTree.count - 1)
                            }
                        }
                    }
                    .padding(AppSpacing.lg)
                }
            }
            .navigationTitle("Family Legacy")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("Done") { dismiss() }
                }
            }
        }
        .navigationViewStyle(.stack)
    }

    // MARK: - Prestige banner

    private var prestigeBanner: some View {
        BaseCard {
            VStack(spacing: AppSpacing.xs) {
                Image(systemName: "crown.fill")
                    .font(.system(size: 28))
                    .foregroundColor(AppColors.diamond)

                Text("Family Prestige")
                    .font(.appCaption)
                    .foregroundColor(AppColors.secondaryText)

                Text("\(familyPrestige)")
                    .font(.system(size: 44, weight: .heavy, design: .rounded))
                    .foregroundColor(AppColors.primaryText)

                Text("\(familyTree.count) generation\(familyTree.count == 1 ? "" : "s") recorded")
                    .font(.appCaption)
                    .foregroundColor(AppColors.secondaryText)
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, AppSpacing.sm)
        }
    }

    // MARK: - Ancestor card

    private func ancestorCard(_ entry: FamilyTreeEntry, isLast: Bool) -> some View {
        HStack(alignment: .top, spacing: AppSpacing.md) {
            // Generation rail
            VStack(spacing: 0) {
                ZStack {
                    Circle()
                        .fill(AppColors.primary.opacity(0.2))
                        .frame(width: 36, height: 36)
                    Text("\(entry.generation)")
                        .font(.appHeadline)
                        .foregroundColor(AppColors.primary)
                }
                if !isLast {
                    Rectangle()
                        .fill(AppColors.primary.opacity(0.25))
                        .frame(width: 2)
                        .frame(maxHeight: .infinity)
                }
            }

            BaseCard {
                VStack(alignment: .leading, spacing: AppSpacing.xs) {
                    HStack {
                        Text(entry.name.isEmpty ? "Unknown" : entry.name)
                            .font(.appHeadline)
                            .foregroundColor(AppColors.primaryText)
                        Spacer()
                        Text("Score \(entry.score)")
                            .font(.appCaption)
                            .foregroundColor(AppColors.diamond)
                    }

                    if entry.finalAge > 0 {
                        legacyRow(icon: "hourglass", text: "Lived \(entry.finalAge) years")
                    }
                    if let career = entry.peakCareer, !career.isEmpty {
                        legacyRow(icon: "briefcase.fill", text: career)
                    }
                    legacyRow(icon: "dollarsign.circle.fill", text: formatMoney(entry.netWorth))
                }
                .frame(maxWidth: .infinity, alignment: .leading)
            }
        }
    }

    private func legacyRow(icon: String, text: String) -> some View {
        HStack(spacing: AppSpacing.sm) {
            Image(systemName: icon)
                .font(.system(size: 13))
                .foregroundColor(AppColors.secondaryText)
                .frame(width: 18)
            Text(text)
                .font(.appBody)
                .foregroundColor(AppColors.secondaryText)
        }
    }

    // MARK: - Empty state

    private var emptyState: some View {
        BaseCard {
            VStack(spacing: AppSpacing.sm) {
                Image(systemName: "tree")
                    .font(.system(size: 32))
                    .foregroundColor(AppColors.secondaryText)
                Text("No ancestors yet")
                    .font(.appHeadline)
                    .foregroundColor(AppColors.primaryText)
                Text("Your lineage history will grow as generations pass.")
                    .font(.appBody)
                    .foregroundColor(AppColors.secondaryText)
                    .multilineTextAlignment(.center)
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, AppSpacing.md)
        }
    }

    // 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
