package wang.yaojia.webterm.components

import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.SuggestionChipDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import wang.yaojia.webterm.designsystem.Radius
import wang.yaojia.webterm.designsystem.Spacing
import wang.yaojia.webterm.designsystem.WebTermTheme

/**
 * # QuickReply (A25) — the floating quick-reply chip row.
 *
 * A horizontal strip of the editable palette ([QuickReplyStore]). It **floats only
 * while a gate is held** (plan §1 quick-reply row) — the moment Claude is waiting on
 * the user is exactly when a one-tap canned reply is useful — and each chip, on tap,
 * sends its [text][QuickReplyChip.text] VERBATIM via the injected [onSend].
 *
 * ### The load-bearing seam (JVM-tested; layout/float animation are device-QA §7)
 *  - **Visibility:** [shouldShowQuickReply] gates the row on `gateHeld && hasChips`.
 *  - **Send:** a tap calls [sendQuickReply] → `onSend(chip.text)` with NO added byte.
 *    A21 wires `onSend` to `TerminalSessionController.sendInput` (invariant #1 —
 *    input passed through verbatim), and `gateHeld` to the [GateViewModel]
 *    [wang.yaojia.webterm.viewmodels.GateViewModel] held-gate state.
 *
 * The chip label is the user's OWN palette text (not untrusted server data), rendered
 * as a single-line, ellipsised [Text] — no Markdown / autolink.
 *
 * @param chips the palette to show, in display order.
 * @param gateHeld whether a gate is currently held (drives the float).
 * @param onSend receives the tapped chip's exact text.
 */
@Composable
public fun QuickReply(
    chips: List<QuickReplyChip>,
    gateHeld: Boolean,
    onSend: (String) -> Unit,
    modifier: Modifier = Modifier,
) {
    if (!shouldShowQuickReply(gateHeld = gateHeld, hasChips = chips.isNotEmpty())) return

    Surface(
        modifier = modifier.fillMaxWidth(),
        color = MaterialTheme.colorScheme.surface,
        shape = RoundedCornerShape(Radius.pill),
        tonalElevation = Spacing.xs2,
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .horizontalScroll(rememberScrollState())
                .padding(horizontal = Spacing.sm8, vertical = Spacing.xs4),
            horizontalArrangement = Arrangement.spacedBy(Spacing.sm8),
        ) {
            chips.forEach { chip ->
                SuggestionChip(
                    onClick = { sendQuickReply(chip, onSend) },
                    label = {
                        Text(
                            text = chip.text,
                            style = MaterialTheme.typography.labelLarge,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis,
                        )
                    },
                    shape = RoundedCornerShape(Radius.pill),
                    colors = SuggestionChipDefaults.suggestionChipColors(),
                )
            }
        }
    }
}

/**
 * The tap→emit seam (mirrors `KeyBar.emitKey`): send the chip's [text][QuickReplyChip.text]
 * VERBATIM. Kept as a top-level function so the exact-byte contract is JVM-testable
 * without driving Compose.
 */
internal fun sendQuickReply(chip: QuickReplyChip, onSend: (String) -> Unit) {
    onSend(chip.text)
}

/** The row floats only while a gate is held AND the palette is non-empty. */
internal fun shouldShowQuickReply(gateHeld: Boolean, hasChips: Boolean): Boolean =
    gateHeld && hasChips

// ── Preview ─────────────────────────────────────────────────────────────────────

@Preview(name = "QuickReply (gate held)")
@Composable
private fun QuickReplyPreview() {
    WebTermTheme {
        QuickReply(
            chips = QuickReplyDefaults.chips,
            gateHeld = true,
            onSend = {},
        )
    }
}
