Pith - timber
package com.vgmlr.timber

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.FiberManualRecord
import androidx.compose.material.icons.filled.HeadsetMic
import androidx.compose.material.icons.filled.MicOff
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PhoneAndroid
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.layout
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import java.util.Locale
import androidx.compose.foundation.BorderStroke
import androidx.compose.ui.graphics.drawscope.DrawScope
import kotlin.math.max
import kotlin.math.pow
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Rect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.unit.IntSize

private val SEARCH_ICON = 26.dp
private val SEARCH_ICON_PAD = 14.dp
private val SEARCH_TEXT_START = 48.dp
private val SEARCH_TEXT_END = 48.dp
private val SEARCH_FS = 18.sp

private const val TAG_SAT = 0.38f
private const val TAG_LIGHT = 0.34f

internal val RAIL_W = 1.dp
internal const val RAIL_ALPHA = 0.4f
private val RAIL_X_BASE = 28.dp
private val RAIL_GAP_BASE = 26.dp
private val RAIL_STEP = 2.dp

private val NUM_FS = 12.sp
private val NUM_PAD = PaddingValues(horizontal = 8.dp, vertical = 2.dp)
private const val NUM_CHIP_ALPHA = 0.3f
private val NUM_EDGE = PAGE_INK.copy(alpha = NUM_CHIP_ALPHA)

private const val PLAY_IN_MS = 320
private const val PLAY_OUT_MS = 320
private val PLAY_END = 8.dp
private val PLAY_INSET_V = 4.dp
private val PLAY_PAD_L = 2.dp
private val PLAY_PAD_R = 12.dp

private val ROW_END = 12.dp
private val ROW_GAP = 10.dp
private const val SIZE_ALPHA = 0.4f
private const val FOCUS_DELAY = 120L

private val CARD_PAD_H = 14.dp
private val CARD_PAD_V = 10.dp
private val CARD_EDGE = BorderStroke(1.dp, MUTED.copy(alpha = 0.50f))
private val CARD_PAD_TOP = 22.dp
private val CLOCK_FS = 32.sp
private val BIG_BTN = 72.dp
private val BIG_ICON = 54.dp
private val BIG_RADIUS = 10.dp
private val BIG_BOX = 100.dp
private val SIDE_GAP = 12.dp
private val CARD_ICON = BTN_ICON + 8.dp

private val SPEC_STEP = 6.dp
private val SPEC_H = 56.dp
private const val SPEC_LO_BIN = 1
private val SPEC_FILL = CARD_BG
private const val MORPH_IN_MS = 350
private const val MORPH_OUT_MS = 700

internal data class Rail(val x: Dp, val gap: Dp)

internal fun railFor(maxId: Int): Rail {
    val steps = (maxId.toString().length - 2).coerceAtLeast(0)
    return Rail(RAIL_X_BASE + RAIL_STEP * steps, RAIL_GAP_BASE + RAIL_STEP * steps)
}

internal fun tagColor(tag: String): Color {
    var h = tag.lowercase().hashCode()
    h = (h xor (h ushr 16)) * 0x45D9F3B // mix
    h = h xor (h ushr 16)
    return Color.hsl(h.mod(360).toFloat(), TAG_SAT, TAG_LIGHT)
}

internal fun clock(ms: Long): String {
    val s = ms.coerceAtLeast(0) / 1000
    return "%02d:%02d:%02d".format(Locale.US, s / 3600, s % 3600 / 60, s % 60)
}

internal fun clockMs(ms: Long): String {
    val t = ms.coerceAtLeast(0)
    val s = t / 1000
    return "%02d:%02d:%02d.%03d".format(Locale.US, s / 3600, s % 3600 / 60, s % 60, t % 1000)
}

internal fun span(sec: Long): String =
    if (sec >= 3600) "%d:%02d:%02d".format(Locale.US, sec / 3600, sec % 3600 / 60, sec % 60)
    else "%d:%02d".format(Locale.US, sec / 60, sec % 60)

internal fun bytes(n: Long): String = when {
    n >= 1L shl 30 -> "%.1f GB".format(Locale.US, n / 1_073_741_824.0)
    n >= 1L shl 20 -> "%.1f MB".format(Locale.US, n / 1_048_576.0)
    else -> "%d KB".format(Locale.US, (n + 1023) / 1024)
}

private fun Modifier.centerOn(x: Dp): Modifier = layout { m, c ->
    val p = m.measure(c.copy(minWidth = 0, minHeight = 0))
    layout(p.width, p.height) { p.place(x.roundToPx() - p.width / 2, 0) }
}

@Composable
internal fun TimberSearch(
    query: String,
    onQueryChange: (String) -> Unit,
    onClear: () -> Unit,
    modifier: Modifier = Modifier
) {
    val focus = LocalFocusManager.current
    val shape = RoundedCornerShape(ROUND_END)
    Box(
        modifier = modifier
            .fillMaxWidth()
            .height(SEARCH_FIELD_H)
            .clip(shape)
            .background(SEARCH_BG)
            .border(EDGE, shape)
    ) {
        Icon(
            Icons.Outlined.Search,
            contentDescription = null,
            tint = Color.White.copy(alpha = 0.6f),
            modifier = Modifier
                .align(Alignment.CenterStart)
                .padding(start = SEARCH_ICON_PAD)
                .size(SEARCH_ICON)
        )
        BasicTextField(
            value = query,
            onValueChange = onQueryChange,
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = SEARCH_TEXT_START, end = SEARCH_TEXT_END)
                .align(Alignment.Center),
            textStyle = TextStyle(fontSize = SEARCH_FS, color = Color.White),
            cursorBrush = SolidColor(Color.White),
            singleLine = true,
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
            keyboardActions = KeyboardActions(onSearch = { focus.clearFocus() }),
            decorationBox = { inner ->
                Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterStart) {
                    if (query.isEmpty()) {
                        Text("Search", color = Color.White.copy(alpha = 0.5f), fontSize = SEARCH_FS)
                    }
                    inner()
                }
            }
        )
        IconButton(
            onClick = onClear,
            modifier = Modifier
                .align(Alignment.CenterEnd)
                .padding(end = 3.dp)
        ) {
            Icon(Icons.Default.Clear, contentDescription = "Clear", tint = Color.White.copy(alpha = 0.6f))
        }
    }
}

@Composable
internal fun ClipItem(
    clip: TimberClip,
    rail: Rail,
    selected: Boolean,
    playing: Boolean,
    seconds: Long,
    edit: TextFieldValue?,
    onEdit: (TextFieldValue) -> Unit,
    onEditDone: () -> Unit,
    onEditLost: () -> Unit,
    onTap: () -> Unit,
    onNum: () -> Unit
) {
    val style = TextStyle(
        color = PAGE_INK,
        fontSize = ROW_FS,
        fontWeight = if (playing) FontWeight.Bold else FontWeight.Normal
    )
    val ext = if (clip.ext.isEmpty()) "" else ".${clip.ext}"
    val grow = animateFloatAsState(
        targetValue = if (playing) 1f else 0f,
        animationSpec = tween(
            if (playing) PLAY_IN_MS else PLAY_OUT_MS,
            easing = FastOutSlowInEasing
        ),
        label = "play"
    )
    var chip by remember { mutableStateOf(IntSize.Zero) }
    val tag = tagColor(clip.id.toString())
    val base = if (selected) NUM_SEL else tag
    val endPad = ROW_END + (PLAY_END + PLAY_PAD_R - ROW_END) * grow.value

    Box(
        Modifier
            .fillMaxWidth()
            .clickable(remember { MutableInteractionSource() }, null, onClick = onTap)
            .drawBehind { drawPlayCard(grow.value, chip, rail.x, base, tag) }
            .padding(vertical = ROW_PAD)
    ) {
        Row(
            Modifier
                .fillMaxWidth()
                .padding(start = rail.x + rail.gap, end = endPad),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {
                if (edit != null) {
                    EditName(edit, style, onEdit, onEditDone, onEditLost, Modifier.weight(1f))
                } else {
                    Text(
                        clip.base,
                        style = style,
                        maxLines = 1,
                        softWrap = false,
                        overflow = TextOverflow.Ellipsis,
                        modifier = Modifier.weight(1f, fill = false)
                    )
                }
                Text(ext, style = style, maxLines = 1, softWrap = false)
            }
            Spacer(Modifier.width(ROW_GAP))
            Text(
                bytes(clip.size),
                style = style.copy(
                    color = PAGE_INK.copy(alpha = SIZE_ALPHA),
                    fontWeight = FontWeight.Normal
                ),
                maxLines = 1,
                softWrap = false
            )
            Spacer(Modifier.width(ROW_GAP))
            Text(
                span(seconds),
                style = style,
                maxLines = 1,
                softWrap = false,
                textAlign = TextAlign.End
            )
        }
        Box(
            modifier = Modifier
                .align(Alignment.CenterStart)
                .centerOn(rail.x)
                .onSizeChanged { chip = it }
                .clickable(remember { MutableInteractionSource() }, null, onClick = onNum)
        ) {
            Text(
                text = clip.id.toString(),
                color = lerp(if (selected) PAGE_BG else NUM_INK, NUM_INK, grow.value),
                fontSize = NUM_FS,
                lineHeight = NUM_FS,
                modifier = Modifier.padding(NUM_PAD)
            )
        }
    }
}

// chip grows into card
private fun DrawScope.drawPlayCard(
    g: Float,
    chip: IntSize,
    railX: Dp,
    base: Color,
    tag: Color
) {
    if (chip.width == 0) return
    val cw = chip.width.toFloat()
    val ch = chip.height.toFloat()
    val chipLeft = railX.toPx() - cw / 2f
    val left = chipLeft - PLAY_PAD_L.toPx() * g
    val t0 = (size.height - ch) / 2f
    val inset = PLAY_INSET_V.toPx()
    val top = mix(t0, inset, g)
    val bottom = mix(t0 + ch, size.height - inset, g)
    val right = mix(chipLeft + cw, size.width - PLAY_END.toPx(), g)
    val rad = CornerRadius(mix(ROUND_LESS.toPx(), ROUND_END.toPx(), g))
    val bw = RAIL_W.toPx()
    drawRoundRect(lerp(base, tag, g), Offset(left, top), Size(right - left, bottom - top), rad)
    drawRoundRect(
        NUM_EDGE,
        Offset(left + bw / 2f, top + bw / 2f),
        Size(right - left - bw, bottom - top - bw),
        rad,
        style = Stroke(bw)
    )
}

private fun mix(a: Float, b: Float, t: Float) = a + (b - a) * t

@Composable
private fun EditName(
    value: TextFieldValue,
    style: TextStyle,
    onChange: (TextFieldValue) -> Unit,
    onDone: () -> Unit,
    onLost: () -> Unit,
    modifier: Modifier
) {
    val fr = remember { FocusRequester() }
    val keyboard = LocalSoftwareKeyboardController.current
    val had = remember { booleanArrayOf(false) }

    LaunchedEffect(Unit) {
        delay(FOCUS_DELAY)
        fr.requestFocus()
        keyboard?.show()
    }

    BasicTextField(
        value = value,
        onValueChange = onChange,
        modifier = modifier
            .focusRequester(fr)
            .onFocusChanged {
                if (it.isFocused) had[0] = true
                else if (had[0]) onLost()
            },
        textStyle = style,
        cursorBrush = SolidColor(PAGE_INK),
        singleLine = true,
        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
        keyboardActions = KeyboardActions(onDone = { onDone() })
    )
}

private fun srcIcon(s: Src): ImageVector = when (s) {
    Src.PHONE -> Icons.Filled.PhoneAndroid
    Src.HEADSET -> Icons.Filled.HeadsetMic
    Src.OFF -> Icons.Filled.MicOff
}

@Composable
internal fun RecordCard(
    time: Long,
    spectrum: () -> FloatArray,
    live: Boolean,
    paused: Boolean,
    source: Src,
    onSource: () -> Unit,
    onMain: () -> Unit,
    onPause: () -> Unit,
    modifier: Modifier = Modifier
) {
    val morph = animateFloatAsState(
        targetValue = if (live) 1f else 0f,
        animationSpec = tween(
            if (live) MORPH_IN_MS else MORPH_OUT_MS,
            easing = FastOutSlowInEasing
        ),
        label = "morph"
    )
    val held = remember { arrayOf(NO_BINS) } // last wave
    val shape = RoundedCornerShape(ROUND_END)

    Column(
        modifier
            .drawWithContent {
                val now = spectrum()
                if (now.isNotEmpty()) held[0] = now
                val m = morph.value
                if (m == 0f && !live) held[0] = NO_BINS
                val stroke = CARD_EDGE.width.toPx()
                val s = stroke / 2f
                val k = (ROUND_END.toPx() - s).coerceAtLeast(0f)
                val topK = k * (1f - m) // corners flatten
                val x0 = s + topK
                val span = size.width - 2 * x0
                val ys = waveYs(held[0], m, span)
                val dx = if (ys != null) span / (ys.size - 1) else 0f
                val edge = cardOutline(size.width, size.height, s, k, topK, ys, x0, dx)
                drawPath(edge, SPEC_FILL)
                drawContent()
                drawPath(edge, CARD_EDGE.brush, style = Stroke(stroke))
            }
            .clip(shape)
            .background(CARD_BG)
            .padding(
                start = CARD_PAD_H,
                end = CARD_PAD_H,
                top = CARD_PAD_TOP,
                bottom = CARD_PAD_V
            ),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(clockMs(time), color = PAGE_INK, fontSize = CLOCK_FS, fontFamily = FontFamily.Monospace)
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(SIDE_GAP)
        ) {
            CardIcon(srcIcon(source), "Source", onClick = onSource)
            Box(
                Modifier.size(BIG_BOX),
                contentAlignment = Alignment.Center
            ) {
                Box(
                    Modifier
                        .size(BIG_BTN)
                        .clip(RoundedCornerShape(BIG_RADIUS))
                        .background(PRIMARY)
                        .clickable(onClick = onMain),
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        if (live) Icons.Filled.Stop else Icons.Filled.FiberManualRecord,
                        contentDescription = if (live) "Stop" else "Record",
                        tint = if (live) PAGE_INK else REC_RED,
                        modifier = Modifier.size(BIG_ICON)
                    )
                }
            }
            CardIcon(
                if (paused) Icons.Filled.PlayArrow else Icons.Filled.Pause,
                "Pause",
                enabled = live,
                onClick = onPause
            )
        }
    }
}

// band offsets, scaled
private fun DrawScope.waveYs(bins: FloatArray, m: Float, span: Float): FloatArray? {
    if (bins.size < 2 || m <= 0f) return null
    val step = SPEC_STEP.toPx()
    val top = SPEC_H.toPx() * m
    val count = (span / step).toInt()
    if (count < 2) return null
    val ratio = bins.size.toFloat() / SPEC_LO_BIN
    val ys = FloatArray(count)
    var peak = 0f
    for (i in 0 until count) {
        val a = (SPEC_LO_BIN * ratio.pow(i.toFloat() / count)).toInt()
        val b = (SPEC_LO_BIN * ratio.pow((i + 1f) / count)).toInt().coerceIn(a + 1, bins.size)
        var v = 0f
        for (k in a until b) v = max(v, bins[k])
        ys[i] = -v * top
        peak = max(peak, v * top)
    }
    return if (peak < 0.5f) null else ys
}

// border, wave top
private fun cardOutline(
    w: Float,
    h: Float,
    s: Float,
    k: Float,
    topK: Float,
    ys: FloatArray?,
    x0: Float,
    dx: Float
): Path = Path().apply {
    val l = s
    val t = s
    val rt = w - s
    val b = h - s
    moveTo(l, t + topK)
    if (topK > 0f) arcTo(Rect(l, t, l + 2 * topK, t + 2 * topK), 180f, 90f, false)
    if (ys != null) wave(ys, x0, dx, t)
    lineTo(rt - topK, t)
    if (topK > 0f) arcTo(Rect(rt - 2 * topK, t, rt, t + 2 * topK), 270f, 90f, false)
    lineTo(rt, b - k)
    if (k > 0f) arcTo(Rect(rt - 2 * k, b - 2 * k, rt, b), 0f, 90f, false)
    lineTo(l + k, b)
    if (k > 0f) arcTo(Rect(l, b - 2 * k, l + 2 * k, b), 90f, 90f, false)
    close()
}

// midpoint quadratics
private fun Path.wave(ys: FloatArray, x0: Float, dx: Float, base: Float) {
    lineTo(x0, base + ys[0])
    for (i in 1 until ys.lastIndex) {
        val x = x0 + i * dx
        quadraticTo(x, base + ys[i], x + dx / 2f, base + (ys[i] + ys[i + 1]) / 2f)
    }
    lineTo(x0 + ys.lastIndex * dx, base + ys.last())
}

@Composable
private fun CardIcon(
    icon: ImageVector,
    desc: String,
    enabled: Boolean = true,
    onClick: () -> Unit
) {
    Box(
        Modifier
            .size(BTN_SIZE)
            .clip(RoundedCornerShape(ROUND_END))
            .clickable(enabled = enabled, onClick = onClick),
        contentAlignment = Alignment.Center
    ) {
        Icon(
            icon,
            contentDescription = desc,
            tint = PAGE_INK.copy(alpha = if (enabled) 1f else DISABLED_ALPHA),
            modifier = Modifier.size(CARD_ICON)
        )
    }
}