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.graphics.Path
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.unit.dp

/**
 * Displays the most recent audio waveform as a continuous path.
 *
 * @param data Waveform bytes where each value is 0..255 (unsigned), as provided by Visualizer.
 *             Pass null to render an idle baseline.
 * @param modifier Compose modifier for sizing and padding.
 */
@Composable
fun WaveformView(
    data: ByteArray?,
    modifier: Modifier = Modifier,
) {
    Text("Waveform", style = MaterialTheme.typography.titleMedium)
    Canvas(
        modifier = modifier
            .fillMaxWidth()
            .height(120.dp)
            .padding(vertical = 4.dp)
    ) {
        val w = size.width
        val h = size.height
        if (data == null || data.isEmpty()) {
            drawLine(
                color = Color.Gray,
                start = androidx.compose.ui.geometry.Offset(0f, h / 2),
                end = androidx.compose.ui.geometry.Offset(w, h / 2),
                strokeWidth = 1f
            )
        } else {
            val path = Path()
            val stepX = w / (data.size - 1).coerceAtLeast(1)
            for (i in data.indices) {
                val x = i * stepX
                val normalized = (data[i].toInt() and 0xFF) / 255f
                val y = h * (1f - normalized)
                if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)
            }
            drawPath(path = path, color = Color.Cyan, style = Stroke(width = 2f))
            drawLine(
                color = Color.Gray,
                start = androidx.compose.ui.geometry.Offset(0f, h / 2),
                end = androidx.compose.ui.geometry.Offset(w, h / 2),
                strokeWidth = 1f
            )
        }
    }
}
