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

import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue

/**
 * Counter-based gate that disables user-initiated sheet dismissal (drag,
 * scrim tap) while at least one consumer holds a lock. Programmatic close via
 * [RecipeBottomSheetState.dismiss] always succeeds.
 */
@Stable
class SheetDismissalGate {
    private var lockCount by mutableStateOf(0)

    val isBlocked: Boolean by derivedStateOf { lockCount > 0 }

    internal fun acquire() {
        lockCount++
    }

    internal fun release() {
        if (lockCount > 0) lockCount--
    }
}

internal val LocalSheetDismissalGate = compositionLocalOf<SheetDismissalGate?> { null }

/**
 * Blocks gesture-initiated dismissal of the enclosing [RecipeBottomSheet]
 * while this composable is in composition. Programmatic close via
 * [RecipeBottomSheetState.dismiss] still works.
 */
@Composable
fun BlockSheetDismiss() {
    val gate = LocalSheetDismissalGate.current ?: return
    DisposableEffect(gate) {
        gate.acquire()
        onDispose { gate.release() }
    }
}
