package dev.privacyllc.period.navigation

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import dev.privacyllc.period.core.datastore.UserPreferencesRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

enum class RootState { Loading, Onboarding, Ready }

@HiltViewModel
class RootViewModel @Inject constructor(
    preferences: UserPreferencesRepository,
) : ViewModel() {

    // Notification actions used to be applied here. They moved to
    // AppLockViewModel, which is the only place that knows whether the session
    // has been unlocked — the write they perform must not happen for somebody
    // who tapped a reminder button and never proved who they were. The
    // repository call itself is unchanged and still shared with the in-app
    // button, which is what keeps the two meaning the same thing.

    /**
     * Set when onboarding finishes, so the switch happens immediately rather
     * than waiting for the preference write to travel back through DataStore —
     * which is fast, but not instant, and a visible flicker on the last tap of
     * onboarding is a poor first impression.
     */
    private val finishedThisSession = MutableStateFlow(false)

    val state: StateFlow<RootState> =
        combine(
            preferences.preferences.map { it.onboardingCompleted },
            finishedThisSession,
        ) { completed, finished ->
            if (completed || finished) RootState.Ready else RootState.Onboarding
        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), RootState.Loading)

    fun onboardingFinished() { finishedThisSession.value = true }
}
