// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later

package space.rcmd.android.sizzle.ui.toolbox

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import space.rcmd.android.sizzle.model.ToolboxSlot
import space.rcmd.android.sizzle.ui.AppViewModel
import space.rcmd.android.sizzle.ui.theme.LocalRetro
import kotlin.math.roundToInt

/**
 * Editor for the [space.rcmd.android.sizzle.model.ToolboxType.MIX_TIGHTENER]
 * effect. The preset bar above (rendered by [ToolboxScreen]) chooses a genre/
 * instrument voicing; this screen exposes four faders:
 *  - **Strength** — the master amount for the whole EQ → compressor → limiter chain.
 *  - **EQ / Comp / Limit** — per-stage trims. Each stage's effective amount is
 *    master Strength × that stage's fader, so you can (say) keep the tone shaping
 *    but back off the compression, or push the limiter for more loudness.
 * At the bottom every fader is transparent; at the top it's the full preset.
 */
@Composable
fun MixTightenerEditor(vm: AppViewModel, slot: ToolboxSlot) {
    val c = LocalRetro.current
    @Suppress("UNUSED_VARIABLE") val rev = vm.revision // subscribe so the faders refresh
    val mono = FontFamily.Monospace

    Column(
        Modifier.fillMaxWidth().padding(top = 4.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(10.dp),
    ) {
        Text(
            "Preset-driven EQ → 3-band compressor → limiter. Pick a preset, then set the " +
                "master Strength and trim each stage:",
            color = c.textDim, fontFamily = mono, fontSize = 11.sp,
            textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth(),
        )
        Row(
            Modifier.fillMaxWidth().height(268.dp),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
        ) {
            Fader(vm, slot, "strength", "STRENGTH", 1f, Modifier.weight(1f))
            Fader(vm, slot, "eqAmt", "EQ", 1f, Modifier.weight(1f))
            Fader(vm, slot, "compAmt", "COMP", 1f, Modifier.weight(1f))
            Fader(vm, slot, "limAmt", "LIMIT", 1f, Modifier.weight(1f))
        }
        Text(
            "Bottom = off · Top = full. Each stage = Strength × its fader.",
            color = c.textDim, fontFamily = mono, fontSize = 10.sp,
            textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth(),
        )
    }
}

/** One labelled vertical fader writing [key] on the slot. */
@Composable
private fun RowScope.Fader(
    vm: AppViewModel,
    slot: ToolboxSlot,
    key: String,
    label: String,
    default: Float,
    modifier: Modifier,
) {
    val c = LocalRetro.current
    @Suppress("UNUSED_VARIABLE") val rev = vm.revision // subscribe so this fader refreshes on write
    val mono = FontFamily.Monospace
    val value = slot.float(key, default).coerceIn(0f, 1f)
    Column(
        modifier,
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(4.dp),
    ) {
        Text(label, color = c.accent, fontFamily = mono, fontSize = 11.sp, maxLines = 1)
        Text("${(value * 100).roundToInt()}%", color = c.text, fontFamily = mono, fontSize = 12.sp)
        Box(
            Modifier
                .fillMaxWidth()
                .weight(1f)
                .border(1.dp, c.grid, RectangleShape)
                .background(c.background)
                .pointerInput(slot.index, key) {
                    detectTapGestures { off -> setAmt(vm, slot, key, 1f - off.y / size.height) }
                }
                .pointerInput(slot.index, key) {
                    detectDragGestures { change, _ ->
                        change.consume()
                        setAmt(vm, slot, key, 1f - change.position.y / size.height)
                    }
                },
            contentAlignment = Alignment.BottomCenter,
        ) {
            FaderFill(value)
        }
    }
}

@Composable
private fun FaderFill(value: Float) {
    val c = LocalRetro.current
    Box(
        Modifier
            .fillMaxWidth()
            .fillMaxHeight(value.coerceIn(0.001f, 1f))
            .background(c.accent.copy(alpha = 0.30f)),
        contentAlignment = Alignment.TopCenter,
    ) {
        Box(Modifier.fillMaxWidth().height(3.dp).background(c.accent)) // thumb
    }
}

private fun setAmt(vm: AppViewModel, slot: ToolboxSlot, key: String, fraction: Float) {
    slot.set(key, fraction.coerceIn(0f, 1f))
    vm.bumpForToolbar()
}
