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

import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.SaverScope
import androidx.compose.runtime.saveable.rememberSaveable

@Composable
inline fun <reified T> rememberSavableMutableTransitionState(
    initialState: T,
    targetState: T,
): MutableTransitionState<T> {
    return rememberSaveable(saver = mutableTransitionStateSaver()) {
        MutableTransitionState(initialState).apply { this.targetState = targetState }
    }
}

inline fun <reified T> mutableTransitionStateSaver() =
    object : Saver<MutableTransitionState<T>, Pair<T, T>> {
        override fun restore(value: Pair<T, T>): MutableTransitionState<T> {
            return MutableTransitionState(value.first).apply { targetState = value.second }
        }

        override fun SaverScope.save(value: MutableTransitionState<T>): Pair<T, T> {
            return value.currentState to value.targetState
        }
    }