//
//  HomeView.swift
//  lichunWebsocket
//
//  Main home screen displaying character info, messages, and controls
//

import SwiftUI

struct HomeView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @EnvironmentObject var appViewModel: AppViewModel
    // INTEGRATION: Tooltip manager for contextual help
    @EnvironmentObject var tooltipManager: TooltipManager

    var body: some View {
        ScrollView {
            VStack(spacing: AppSpacing.md) {
                // T014: one cohesive identity block (avatar + name + mood + core
                // stats) so the first screen reads as a single character card
                // instead of three competing cards.
                HomeCharacterCard()
                    .environmentObject(webSocketService)

                // T014: "What now?" hub — a single panel of the things waiting
                // for the player (pending event, unread messages, claimable
                // rewards). Only shown when at least one action is available.
                whatNowHub

                // Game controls (moved up for easy access)
                GameControlsCard()
                    .environmentObject(webSocketService)

                // Life timeline
                LifeTimelineCard()
                    .environmentObject(webSocketService)
            }
            .padding(AppSpacing.md)
            .padding(.top, AppSpacing.sm) // Additional top spacing for header visibility
        }
        // Report scroll offset so the collapsing hero header can shrink as the
        // feed scrolls (read by HeaderView via appViewModel). Uses the modern
        // scroll-geometry API where available; older iOS keeps the header in its
        // expanded state on Home (still collapses on other tabs by tab rule).
        .modifier(HomeScrollTracking(offset: $appViewModel.homeScrollOffset))
        .background(
            LinearGradient(
                colors: [AppColors.background, AppColors.surfaceSubtle],
                startPoint: .top,
                endPoint: .bottom
            )
        )
        .onAppear {
            AnalyticsManager.shared.trackScreenView("home", screenClass: "HomeView")

            tooltipManager.showTooltipIfNeeded(
                "home_claim_rewards",
                title: "Claim Rewards!",
                message: "Tap glowing life events to claim your rewards!",
                position: .bottom
            )
        }
    }

    // MARK: - What Now Hub (T014)

    private var unreadMessagesCount: Int {
        webSocketService.player.activeConversations.filter { $0.unread }.count
    }

    private var hasPendingEvent: Bool {
        webSocketService.currentQuestion != nil || webSocketService.currentMessageEvent != nil
    }

    private var unclaimedEventCount: Int {
        webSocketService.unclaimedEventCount
    }

    private var canClaimDailyReward: Bool {
        if let state = webSocketService.dailyRewardState {
            return state.canClaim && !state.todaysClaimed
        }
        return false
    }

    private var claimableQuestCount: Int {
        webSocketService.dailyQuestsState?.quests.filter { $0.canClaim }.count ?? 0
    }

    private var hasAnythingToDo: Bool {
        hasPendingEvent
            || unreadMessagesCount > 0
            || unclaimedEventCount > 0
            || canClaimDailyReward
            || claimableQuestCount > 0
    }

    @ViewBuilder
    private var whatNowHub: some View {
        if hasAnythingToDo {
            BaseCard {
                VStack(alignment: .leading, spacing: AppSpacing.sm) {
                    HStack(spacing: AppSpacing.xs) {
                        Image(systemName: "sparkles")
                            .font(.system(size: 16, weight: .semibold))
                            .foregroundColor(AppColors.primary)
                        Text("What now?")
                            .font(.appBodyBold)
                            .foregroundColor(AppColors.primaryText)
                    }

                    if unclaimedEventCount > 0 {
                        whatNowRow(
                            icon: "gift.fill",
                            tint: AppColors.primary,
                            title: "Claim your rewards",
                            subtitle: "\(unclaimedEventCount) life event\(unclaimedEventCount == 1 ? "" : "s") waiting below"
                        ) {
                            // The claimable events live in the timeline below;
                            // nudge the eye there rather than navigating away.
                            hapticFeedback(style: .light)
                        }
                    }

                    if unreadMessagesCount > 0 {
                        whatNowRow(
                            icon: "message.fill",
                            tint: AppColors.loveInterest,
                            title: "Reply to messages",
                            subtitle: "\(unreadMessagesCount) unread"
                        ) {
                            appViewModel.showMessagesFromHeader = true
                        }
                    }

                    if canClaimDailyReward {
                        whatNowRow(
                            icon: "calendar.badge.plus",
                            tint: AppColors.money,
                            title: "Daily reward ready",
                            subtitle: "Claim today's login bonus"
                        ) {
                            webSocketService.showDailyRewards = true
                        }
                    }

                    if claimableQuestCount > 0 {
                        whatNowRow(
                            icon: "checklist",
                            tint: AppColors.happiness,
                            title: "Finish daily quests",
                            subtitle: "\(claimableQuestCount) reward\(claimableQuestCount == 1 ? "" : "s") to claim"
                        ) {
                            webSocketService.showDailyQuests = true
                        }
                    }
                }
                .frame(maxWidth: .infinity, alignment: .leading)
            }
        }
    }

    private func whatNowRow(
        icon: String,
        tint: Color,
        title: String,
        subtitle: String,
        action: @escaping () -> Void
    ) -> some View {
        Button(action: action) {
            HStack(spacing: AppSpacing.sm) {
                ZStack {
                    Circle()
                        .fill(tint.opacity(0.15))
                        .frame(width: 36, height: 36)
                    Image(systemName: icon)
                        .font(.system(size: 16, weight: .semibold))
                        .foregroundColor(tint)
                }
                VStack(alignment: .leading, spacing: 1) {
                    Text(title)
                        .font(.appBodyBold)
                        .foregroundColor(AppColors.primaryText)
                    Text(subtitle)
                        .font(.appCaption)
                        .foregroundColor(AppColors.secondaryText)
                        .lineLimit(1)
                }
                Spacer()
                Image(systemName: "chevron.right")
                    .font(.system(size: 12, weight: .semibold))
                    .foregroundColor(AppColors.secondaryText.opacity(0.6))
            }
            .padding(.vertical, AppSpacing.xxs)
            .contentShape(Rectangle())
        }
        .buttonStyle(PlainButtonStyle())
    }
}

// MARK: - Scroll offset plumbing

/// Feeds the Home ScrollView's vertical content offset into `offset` (0 at the
/// top, negative as the feed scrolls up). Uses `onScrollGeometryChange` on
/// iOS 18+, which is reliable inside the tab container; on older systems it is a
/// no-op (the header simply stays expanded on Home and the tab rule still drives
/// the compact state on other tabs).
struct HomeScrollTracking: ViewModifier {
    @Binding var offset: CGFloat

    func body(content: Content) -> some View {
        if #available(iOS 18.0, *) {
            content.onScrollGeometryChange(for: CGFloat.self) { geo in
                -geo.contentOffset.y
            } action: { _, newValue in
                offset = newValue
            }
        } else {
            content
        }
    }
}

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