package dev.ulfrx.recipe.ui.components.overlay

import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.staticCompositionLocalOf

@Stable
class OverlayDismisser {
    private val handlers = mutableListOf<() -> Unit>()

    fun register(onDismiss: () -> Unit): () -> Unit {
        handlers += onDismiss
        return { handlers -= onDismiss }
    }

    fun dismissAll() {
        handlers.toList().forEach { it() }
    }
}

val LocalOverlayDismisser =
    staticCompositionLocalOf<OverlayDismisser> {
        error("OverlayDismisser not provided — wrap your composable in AppShell or supply one explicitly.")
    }

@Composable
fun RegisterDismissibleOverlay(
    active: Boolean,
    onDismiss: () -> Unit,
) {
    val dismisser = LocalOverlayDismisser.current
    val latestOnDismiss by rememberUpdatedState(onDismiss)
    DisposableEffect(dismisser, active) {
        val unregister = if (active) dismisser.register { latestOnDismiss() } else null
        onDispose { unregister?.invoke() }
    }
}
