//
//  AuthenticatedRootView.swift
//  vibes
//
//  Created on 11/20/25.
//

import SwiftUI
import Combine
import ConvexMobile
import Auth0

struct AuthenticatedRootView: View {
    @State private var authState: AuthState<Credentials> = .loading
    @State private var cancellable: AnyCancellable?
    
    var body: some View {
        Group {
            switch authState {
            case .loading:
                LoadingView()
            case .unauthenticated:
                LoginView(onLogin: handleLogin)
            case .authenticated:
                IndexView()
            }
        }
        .onAppear {
            setupAuthStateListener()
            // Try to login from cache on app launch
            Task {
                _ = await convex.loginFromCache()
            }
        }
    }
    
    private func setupAuthStateListener() {
        cancellable = convex.authState.sink { newState in
            DispatchQueue.main.async {
                authState = newState
                
                // When user becomes authenticated, upsert their profile
                if case .authenticated(let credentials) = newState {
                    Task {
                        await upsertUserProfile(credentials: credentials)
                    }
                }
            }
        }
    }
    
    private func upsertUserProfile(credentials: Credentials) async {
        do {
            // Call upsert - backend extracts user info from the auth token
            try await convex.mutation("users:upsertUser")
        } catch {
            print("Failed to upsert user profile: \(error)")
        }
    }
    
    private func handleLogin() {
        Task {
            _ = await convex.login()
        }
    }
}

struct LoadingView: View {
    var body: some View {
        ZStack {
            Color.black
                .ignoresSafeArea()
            
            VStack(spacing: 16) {
                ProgressView()
                    .progressViewStyle(CircularProgressViewStyle(tint: Constants.ForegroundPrimary))
                    .scaleEffect(1.5)
                
                Text("Loading...")
                    .font(Constants.Typography.mediumRegular)
                    .foregroundColor(Constants.ForegroundSecondary)
            }
        }
    }
}

#Preview("Loading") {
    LoadingView()
}

#Preview("Authenticated Root") {
    AuthenticatedRootView()
}

