package app.dudu.ime.ui

import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.StartOffset
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
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

/**
 * 波形（设计规范 3.2）：条宽 3 / 间距 3 / 圆角 2，固定 12 值高度序列，
 * active 时 scaleY 0.35→1 交替 0.9s ease-in-out、逐条延迟 (i%6)*0.07s。
 * 这是全产品唯一循环动画，仅录音中出现。
 */
private val PATTERN = floatArrayOf(0.3f, 0.55f, 0.85f, 0.45f, 0.7f, 1f, 0.4f, 0.6f, 0.25f, 0.8f, 0.5f, 0.35f)
private val EaseInOut = CubicBezierEasing(0.42f, 0f, 0.58f, 1f)

@Composable
fun Waveform(
    bars: Int,
    height: Dp,
    color: Color,
    modifier: Modifier = Modifier,
    active: Boolean = true,
) {
    val n = bars.coerceIn(1, PATTERN.size)
    val transition = rememberInfiniteTransition(label = "waveform")
    val scales: List<State<Float>> = (0 until n).map { i ->
        if (active) {
            transition.animateFloat(
                initialValue = 0.35f,
                targetValue = 1f,
                animationSpec = infiniteRepeatable(
                    animation = tween(durationMillis = 900, easing = EaseInOut),
                    repeatMode = RepeatMode.Reverse,
                    initialStartOffset = StartOffset((i % 6) * 70),
                ),
                label = "bar$i",
            )
        } else {
            remember { mutableFloatStateOf(1f) }
        }
    }

    val barW = 3.dp
    val gap = 3.dp
    val totalW = barW * n + gap * (n - 1)

    Canvas(modifier.size(totalW, height)) {
        val bw = barW.toPx()
        val g = gap.toPx()
        val h = size.height
        for (i in 0 until n) {
            val base = (PATTERN[i] * h).coerceAtLeast(4.dp.toPx())
            val bh = base * scales[i].value
            drawRoundRect(
                color = color,
                topLeft = Offset(i * (bw + g), (h - bh) / 2f),
                size = Size(bw, bh),
                cornerRadius = CornerRadius(2.dp.toPx()),
            )
        }
    }
}
