package com.keylightpiano.pianotimeline.ui

import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp

/**
 * Draws a thin, auto-fading scrollbar on the trailing edge of a scrollable list,
 * the way most Android apps show one: invisible at rest, fades in while scrolling.
 *
 * This is an approximation that works well for lists where items are roughly
 * uniform height (ours are): the thumb size/position is estimated from the
 * visible item indices rather than exact pixel offsets.
 */
fun Modifier.fadingScrollbar(
    state: LazyListState,
    width: Dp = 4.dp,
    color: Color = Color.Gray
): Modifier = composed {
    // Scrollbar is visible while actively scrolling, then fades out.
    val targetAlpha = if (state.isScrollInProgress) 0.5f else 0f
    val alpha by animateFloatAsState(
        targetValue = targetAlpha,
        animationSpec = tween(durationMillis = if (state.isScrollInProgress) 150 else 500),
        label = "scrollbarAlpha"
    )

    drawWithContent {
        drawContent()

        val layoutInfo = state.layoutInfo
        val totalItems = layoutInfo.totalItemsCount
        val visibleItems = layoutInfo.visibleItemsInfo

        if (totalItems > 0 && visibleItems.isNotEmpty() && alpha > 0f) {
            val firstVisible = visibleItems.first().index
            val visibleCount = visibleItems.size

            // Fraction of the list that's on screen → thumb height.
            val viewportHeight = size.height
            val proportionVisible = (visibleCount.toFloat() / totalItems).coerceIn(0.05f, 1f)
            val thumbHeight = viewportHeight * proportionVisible

            // Scroll progress → thumb vertical position.
            val scrollableItems = (totalItems - visibleCount).coerceAtLeast(1)
            val scrollProgress = (firstVisible.toFloat() / scrollableItems).coerceIn(0f, 1f)
            val thumbTop = (viewportHeight - thumbHeight) * scrollProgress

            val widthPx = width.toPx()
            drawRoundRect(
                color = color.copy(alpha = alpha),
                topLeft = Offset(size.width - widthPx, thumbTop),
                size = Size(widthPx, thumbHeight),
                cornerRadius = androidx.compose.ui.geometry.CornerRadius(widthPx / 2, widthPx / 2)
            )
        }
    }
}
