package ru.forbion.f7cloud.core.designsystem

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay

private val BottomBarFloatOffset = 6.dp

/**
 * Bottom bar visibility — mirrors forbion [mobileBottomBarAutoHide] (4s idle hide).
 */
@Composable
fun F7AutoHideBottomBar(
    enabled: Boolean,
    pinned: Boolean,
    activityNonce: Int,
    modifier: Modifier = Modifier,
    hideDelayMs: Long = 4000L,
    content: @Composable () -> Unit,
) {
    if (!enabled) return

    var visible by remember { mutableStateOf(true) }

    LaunchedEffect(enabled, pinned, activityNonce) {
        if (pinned) {
            visible = true
            return@LaunchedEffect
        }
        visible = true
        delay(hideDelayMs)
        if (!pinned) {
            visible = false
        }
    }

    Box(
        modifier = modifier
            .fillMaxWidth()
            .navigationBarsPadding()
            .padding(bottom = BottomBarFloatOffset),
        contentAlignment = Alignment.BottomCenter,
    ) {
        AnimatedVisibility(
            visible = visible,
            enter = fadeIn() + slideInVertically(initialOffsetY = { it / 2 }),
            exit = fadeOut() + slideOutVertically(targetOffsetY = { it / 2 }),
            modifier = Modifier.wrapContentWidth(),
        ) {
            Box(contentAlignment = Alignment.BottomCenter) {
                content()
            }
        }
    }
}
