package net.sergeych.toread

import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberUpdatedState
import kotlin.js.ExperimentalWasmJsInterop
import kotlinx.browser.window
import org.w3c.dom.events.Event

private var currentBrowserNavigationDepth = 0

@Composable
@OptIn(ExperimentalWasmJsInterop::class)
internal actual fun PlatformBackHandler(
    enabled: Boolean,
    navigationDepth: Int,
    onBack: () -> Unit,
) {
    val currentOnBack = rememberUpdatedState(onBack)

    LaunchedEffect(navigationDepth) {
        if (navigationDepth > currentBrowserNavigationDepth) {
            repeat(navigationDepth - currentBrowserNavigationDepth) {
                window.history.pushState(null, "", window.location.href)
            }
        }
        currentBrowserNavigationDepth = navigationDepth
    }

    DisposableEffect(enabled) {
        if (!enabled) {
            onDispose { }
        } else {
            val listener: (Event) -> Unit = {
                currentOnBack.value()
            }
            window.addEventListener("popstate", listener)
            onDispose {
                window.removeEventListener("popstate", listener)
            }
        }
    }
}
