package com.jishisongfu.duobibi.ui.discover

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jishisongfu.duobibi.ui.arena.ArenaCategory
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject

/**
 * "发现"页 ViewModel — 静态种子按 [品类 × 关键词] 两维度过滤。
 *
 * 不依赖网络/数据库,纯内存运算,占审稳定。
 *
 * 过滤策略:
 *  - **selectedCategory**:null=不限,其它=只显该品类
 *  - **query**:trim 后非空时,匹配 title 或 category.title 任一(忽略大小写) —
 *     这样用户输"数码"能命中整个数码家电品类,输"iPhone"能命中具体商品
 *  - 两维度 AND
 */
@HiltViewModel
class DiscoverViewModel @Inject constructor() : ViewModel() {

    private val _selectedCategory = MutableStateFlow<ArenaCategory?>(null)
    val selectedCategory: StateFlow<ArenaCategory?> = _selectedCategory.asStateFlow()

    private val _query = MutableStateFlow("")
    val query: StateFlow<String> = _query.asStateFlow()

    val items: StateFlow<List<DiscoverItem>> = combine(
        _selectedCategory,
        _query,
    ) { cat, q ->
        val byCategory = if (cat == null) DISCOVER_SEED else DISCOVER_SEED.filter { it.category == cat }
        val needle = q.trim()
        if (needle.isEmpty()) {
            byCategory
        } else {
            byCategory.filter { item ->
                item.title.contains(needle, ignoreCase = true) ||
                    item.category.title.contains(needle, ignoreCase = true)
            }
        }
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), DISCOVER_SEED)

    fun selectCategory(c: ArenaCategory?) {
        _selectedCategory.value = c
    }

    fun setQuery(q: String) {
        _query.value = q
    }
}
