package com.pixelized.biblib.ui.composable.animation

import androidx.compose.animation.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable

@Composable
fun AnimatedDelayer(
    delay: Int = Delay.DELTA,
    content: @Composable AnimatedDelayerScope.() -> Unit
) {
    val scope = IncreasedDelayerScope(
        delay = Delay(value = delay)
    )
    scope.content()
}

@OptIn(ExperimentalAnimationApi::class)
@Composable
fun <T> AnimatedDelayer(
    targetState: T,
    delay: Int = Delay.DELTA,
    content: @Composable AnimatedDelayerScope.(T) -> Unit
) {
    AnimatedContent(
        targetState = targetState,
        transitionSpec = { EnterTransition.None with ExitTransition.None }
    ) {
        AnimatedDelayer(
            delay = delay,
        ) {
            content(targetState)
        }
    }
}

@Composable
fun AnimatedDelayerScope.SharedDelay(content: @Composable AnimatedDelayerScope.() -> Unit) {
    val localScope = SharedDelayerScope(delay = play())
    localScope.content()
}

@Stable
interface AnimatedDelayerScope {
    val delay: Delay
    fun play(): Delay
}

@Stable
private class IncreasedDelayerScope(
    override var delay: Delay
): AnimatedDelayerScope {
    override fun play(): Delay = delay++
}

@Stable
private class SharedDelayerScope(
    override var delay: Delay
): AnimatedDelayerScope {
    override fun play(): Delay = delay
}

@JvmInline
value class Delay(
    val value: Int = DELTA,
) {
    operator fun inc(): Delay {
        return Delay(value = value + DELTA)
    }

    companion object {
        const val DELTA = 100
    }
}