package com.anypreta.bountyboard.ui.nav

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.anypreta.bountyboard.data.AppContainer
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

class ShellViewModel(private val container: AppContainer) : ViewModel() {

    private val _unread = MutableStateFlow(0L)
    val unread: StateFlow<Long> = _unread.asStateFlow()

    init {
        viewModelScope.launch {
            while (isActive) {
                refreshUnread()
                delay(30_000)
            }
        }
    }

    fun refreshUnread() {
        viewModelScope.launch {
            try {
                val r = container.repo.call { notifications(unread = true, limit = 1) }
                _unread.value = r.unread
            } catch (_: Exception) {
            }
        }
    }

    fun toggleTheme() {
        viewModelScope.launch {
            val current = container.settings.theme.first()
            container.settings.setTheme(if (current == "dark") "light" else "dark")
        }
    }

    fun logout(onDone: () -> Unit) {
        viewModelScope.launch {
            try {
                container.repo.action { logout() }
            } catch (_: Exception) {
            }
            container.stopLiveService()
            container.live.disconnect()
            container.cancelPush()
            container.clearPushState()
            container.cookieJar.clear()
            container.session.clear()
            onDone()
        }
    }
}
