//
//  SocialView.swift
//  lichunWebsocket
//
//  Combined view for Dating and Messages
//

import SwiftUI

struct SocialView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @EnvironmentObject var appViewModel: AppViewModel
    @State private var playerAge: Int = 0

    /// Dating unlocks at age 16
    private var isDatingUnlocked: Bool {
        playerAge >= 16
    }

    var body: some View {
        VStack(spacing: 0) {
            // Segment picker - using Text only (HStack doesn't work in segmented style)
            Picker("Social", selection: $appViewModel.selectedSocialSegment) {
                Text("Dating")
                    .tag(0)

                Text(unreadMessagesCount > 0 ? "Messages (\(unreadMessagesCount))" : "Messages")
                    .tag(1)
            }
            .pickerStyle(.segmented)
            .padding()
            .background(AppColors.background)

            // Content - using conditional view instead of TabView to avoid gesture conflicts
            Group {
                if appViewModel.selectedSocialSegment == 0 {
                    if isDatingUnlocked {
                        DatingView()
                    } else {
                        DatingLockedView(currentAge: playerAge)
                    }
                } else {
                    MessagesView()
                }
            }
            .animation(.easeInOut(duration: 0.2), value: appViewModel.selectedSocialSegment)
        }
        .background(AppColors.background)
        .onAppear {
            playerAge = webSocketService.person.ageYears
        }
        .onChange(of: webSocketService.person.id) { _ in
            playerAge = webSocketService.person.ageYears
        }
        .onChange(of: webSocketService.person.ageYears) { newAge in
            playerAge = newAge
        }
    }

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

// MARK: - Preview

#if DEBUG
struct SocialView_Previews: PreviewProvider {
    static var previews: some View {
        SocialView()
            .environmentObject(WebSocketService(urlSession: URLSession.shared, delegateQueue: OperationQueue()))
            .environmentObject(AppViewModel())
    }
}
#endif
