package dev.ulfrx.recipe.ui.components.sheet

import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.navigation3.runtime.NavKey

@Stable
class RecipeBottomSheetState<T : NavKey> {
    val backStack: SnapshotStateList<T> = mutableStateListOf()

    val isOpen by derivedStateOf { backStack.isNotEmpty() }

    fun push(entry: T) {
        backStack.add(entry)
    }

    fun pop() {
        if (backStack.isNotEmpty()) {
            backStack.removeAt(backStack.lastIndex)
        }
    }

    fun open(entry: T) {
        backStack.clear()
        backStack.add(entry)
    }

    fun dismiss() {
        backStack.clear()
    }
}

@Composable
fun <T : NavKey> rememberRecipeBottomSheetState(): RecipeBottomSheetState<T> =
    remember { RecipeBottomSheetState() }
