//
//  LifeTimelineCard.swift
//  lichunWebsocket
//
//  Timeline of life events with filtering
//

import SwiftUI

struct LifeTimelineCard: View {
    @EnvironmentObject var webSocketService: WebSocketService
    // T014: gentle one-time idle nudge under the empty state.
    @EnvironmentObject var tooltipManager: TooltipManager
    @State private var selectedFilter: EventFilter = .all
    @State private var appearedEvents: Set<String> = []

    enum EventFilter: String, CaseIterable {
        case all = "All"
        case career = "Career"
        case social = "Social"
        case achievements = "Achievements"
    }

    var filteredEvents: [MessageEvent] {
        let events = webSocketService.lifeEvents

        switch selectedFilter {
        case .all:
            return events
        case .career:
            return events.filter { $0.category == .career }
        case .social:
            return events.filter { $0.category == .social }
        case .achievements:
            return events.filter { $0.category == .achievement }
        }
    }

    var sortedEvents: [MessageEvent] {
        // Unclaimed first, then by date
        filteredEvents.sorted { event1, event2 in
            if !event1.claimed && event2.claimed {
                return true
            } else if event1.claimed && !event2.claimed {
                return false
            } else {
                // Both same claim status, sort by date (newest first)
                return (event1.claimedAt ?? Date.distantPast) > (event2.claimedAt ?? Date.distantPast)
            }
        }
    }

    var body: some View {
        BaseCard {
            VStack(spacing: AppSpacing.md) {
                // Header
                HStack {
                    Text("Life Timeline")
                        .font(.appBodyBold)
                        .foregroundColor(AppColors.primaryText)

                    Spacer()

                    // Unclaimed count badge
                    if webSocketService.unclaimedEventCount > 0 {
                        HStack(spacing: AppSpacing.xxs) {
                            Text("\(webSocketService.unclaimedEventCount)")
                                .font(.appSmallBold)
                            Image(systemName: "gift.fill")
                                .font(.appMicro)
                        }
                        .foregroundColor(.white)
                        .padding(.horizontal, AppSpacing.sm)
                        .padding(.vertical, AppSpacing.xxs)
                        .background(AppColors.primary)
                        .cornerRadius(AppSpacing.smallCornerRadius)
                        .shadow(color: AppColors.primary.opacity(0.3), radius: AppSpacing.Shadow.offsetY, x: 0, y: 2)
                    }

                    // Filter picker
                    Menu {
                        ForEach(EventFilter.allCases, id: \.self) { filter in
                            Button(filter.rawValue) {
                                withAnimation {
                                    selectedFilter = filter
                                    appearedEvents.removeAll() // Reset for new animation
                                }
                            }
                        }
                    } label: {
                        HStack(spacing: AppSpacing.xxs) {
                            Text(selectedFilter.rawValue)
                                .font(.appCaption)
                            Image(systemName: "chevron.down")
                                .font(.system(size: 9))
                        }
                        .foregroundColor(AppColors.secondaryText)
                        .padding(.horizontal, AppSpacing.sm)
                        .padding(.vertical, AppSpacing.xxs)
                        .background(AppColors.surfaceSubtle)
                        .cornerRadius(AppSpacing.smallCornerRadius)
                    }
                }

                Divider()
                    .background(AppColors.disabledText.opacity(0.3))

                // Events list
                if sortedEvents.isEmpty {
                    // Empty state — tell the player how to make life happen.
                    VStack(spacing: AppSpacing.xs) {
                        Image(systemName: "calendar.badge.clock")
                            .font(.system(size: 32))
                            .foregroundColor(AppColors.disabledText)

                        Text("No events yet")
                            .font(.appBody)
                            .foregroundColor(AppColors.secondaryText)

                        Text("Tap + on the Speed of Time control to fast-forward and let life happen.")
                            .font(.appCaption)
                            .foregroundColor(AppColors.disabledText)
                            .multilineTextAlignment(.center)
                            .fixedSize(horizontal: false, vertical: true)
                    }
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, AppSpacing.md)
                    .onAppear {
                        // Gentle, one-time nudge for brand-new players who are
                        // staring at an empty timeline.
                        tooltipManager.showTooltipIfNeeded(
                            "home_idle_speed_nudge",
                            title: "Make life happen",
                            message: "Tap the + on Speed of Time to fast-forward. Events, choices, and rewards arrive as time passes.",
                            position: .top
                        )
                    }
                } else {
                    ScrollView {
                        LazyVStack(spacing: AppSpacing.sm) {
                            let limitedEvents = sortedEvents.prefix(AppSpacing.timelineEventLimit)
                            // Calculate unclaimed indices for pulse optimization
                            let unclaimedEvents = Array(limitedEvents).filter { !$0.claimed && $0.isClaimable }
                            ForEach(0..<limitedEvents.count, id: \.self) { index in
                                let event = limitedEvents[limitedEvents.startIndex + index]
                                let unclaimedIndex = unclaimedEvents.firstIndex(where: { $0.id == event.id })
                                LifeEventCard(event: event, unclaimedIndex: unclaimedIndex)
                                    .environmentObject(webSocketService)
                                    .opacity(appearedEvents.contains(event.id) ? 1 : 0)
                                    .offset(x: appearedEvents.contains(event.id) ? 0 : -10)
                                    .onAppear {
                                        withAnimation(.easeOut(duration: 0.12).delay(Double(index) * 0.02)) {
                                            _ = appearedEvents.insert(event.id)
                                        }
                                    }
                            }
                        }
                        .padding(.top, AppSpacing.xxs)
                    }
                    .frame(maxHeight: AppSpacing.timelineMaxHeight)
                }
            }
        }
    }
}

// MARK: - Preview
#Preview {
    let service = WebSocketService(urlSession: URLSession.shared, delegateQueue: OperationQueue())
    LifeTimelineCard()
        .environmentObject(service)
        .padding()
        .background(AppColors.background)
}
