package dev.adriankuta.visualizer.components

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import kotlin.math.hypot
import kotlin.math.min

/**
 * Renders FFT magnitude as vertical bars.
 *
 * The input is the raw FFT byte array from Visualizer where values are interleaved
 * real and imaginary parts: [re0, im0, re1, im1, ...]. This composable computes the
 * magnitude per bin and draws a limited number of bars for readability.
 *
 * @param data Interleaved real/imag FFT bytes; null shows a baseline.
 * @param modifier Compose modifier for sizing and padding.
 */
@Composable
fun FftBarsView(
    data: ByteArray?,
    modifier: Modifier = Modifier,
) {
    Text("FFT (magnitude bars)", style = MaterialTheme.typography.titleMedium)
    Canvas(
        modifier = modifier
            .fillMaxWidth()
            .height(160.dp)
            .padding(vertical = 4.dp)
    ) {
        val w = size.width
        val h = size.height
        if (data != null && data.size >= 2) {
            val n = data.size / 2 // real/imag pairs count
            val barCount = min(64, n) // limit bars for readability
            val barWidth = w / barCount
            for (i in 0 until barCount) {
                val re = data[2 * i].toInt()
                val im = data[2 * i + 1].toInt()
                val mag = hypot(re.toDouble(), im.toDouble()).toFloat()
                val scaled = (mag / 128f).coerceIn(0f, 1.5f)
                val barHeight = h * (scaled.coerceAtMost(1f))
                val left = i * barWidth
                drawRect(
                    color = Color(0xFF8BC34A),
                    topLeft = androidx.compose.ui.geometry.Offset(left, h - barHeight),
                    size = androidx.compose.ui.geometry.Size(barWidth * 0.9f, barHeight)
                )
            }
        } else {
            drawLine(
                color = Color.Gray,
                start = androidx.compose.ui.geometry.Offset(0f, h - 1f),
                end = androidx.compose.ui.geometry.Offset(w, h - 1f),
                strokeWidth = 1f
            )
        }
    }
}
