package dev.ulfrx.recipe.ui.screens.search

import androidx.lifecycle.ViewModel
import dev.ulfrx.recipe.ui.screens.shell.search.SearchState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update

/**
 * Single shell-wide search VM. Replaces the per-tab `…SearchViewModel`s — search
 * is now a global affordance, not feature-scoped.
 *
 * Drives the three-state Apple-Music-style flow described in [SearchState]:
 *  - `open()`  A → B  (clicked the floating search button)
 *  - `focus()` B → C  (tapped the search pill — text field gained focus)
 *  - `unfocus()` C → B  (tapped the X dismiss button — clears query AND focus)
 *  - `close()` B/C → A (tapped the collapsed dock icon — returns to the
 *    originating tab; clears focus and query so a fresh open starts blank)
 *  - `onQueryChange(q)` — pure echo this phase; per-feature SearchSource
 *    plumbing arrives in Phase 5/6/8/9.
 */
class ShellSearchViewModel : ViewModel() {
    private val _state = MutableStateFlow(SearchState())
    val state: StateFlow<SearchState> = _state.asStateFlow()

    fun open() {
        _state.update { it.copy(isOpen = true, isFocused = false) }
    }

    fun close() {
        _state.value = SearchState()
    }

    fun focus() {
        _state.update { if (it.isOpen) it.copy(isFocused = true) else it }
    }

    fun unfocus() {
        _state.update { it.copy(isFocused = false, query = "") }
    }

    fun onQueryChange(q: String) {
        _state.update { it.copy(query = q) }
    }

    fun clear() {
        _state.update { it.copy(query = "") }
    }
}
