package app.closer.ui.messages.components

import android.Manifest
import android.content.pm.PackageManager
import android.media.MediaPlayer
import android.media.MediaRecorder
import android.net.Uri
import android.os.Build
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
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.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
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.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Image
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.PhotoCamera
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import app.closer.core.media.MediaCompressor
import app.closer.domain.model.QuestionMessage
import coil.ImageLoader
import coil.compose.AsyncImage
import coil.decode.GifDecoder
import coil.decode.ImageDecoderDecoder
import coil.request.ImageRequest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.nio.ByteBuffer

/**
 * One chat row — Messenger style: only the partner's avatar shows (on the left); our own messages
 * are bubbles on the right with no avatar. Handles text, encrypted image/GIF, and voice messages.
 */
val REACTION_EMOJIS = listOf("❤️", "😂", "👍", "😮", "😢", "🔥")

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ChatMessageRow(
    message: QuestionMessage,
    isCurrentUser: Boolean,
    partnerAvatarUrl: String?,
    showAvatar: Boolean,
    showTimestamp: Boolean,
    showSeen: Boolean = false,
    canReact: Boolean = true,
    onReact: (String) -> Unit = {},
    onReactBlocked: () -> Unit = {},
    onDelete: () -> Unit = {},
    loadDecryptedMedia: suspend (String) -> ByteArray?
) {
    val bubbleShape = if (isCurrentUser) {
        RoundedCornerShape(topStart = 16.dp, topEnd = 4.dp, bottomStart = 16.dp, bottomEnd = 16.dp)
    } else {
        RoundedCornerShape(topStart = 4.dp, topEnd = 16.dp, bottomStart = 16.dp, bottomEnd = 16.dp)
    }
    var menuOpen by remember { mutableStateOf(false) }
    val clipboard = LocalClipboardManager.current

    Column(modifier = Modifier.fillMaxWidth()) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = if (isCurrentUser) Arrangement.End else Arrangement.Start,
            verticalAlignment = Alignment.Bottom
        ) {
            if (!isCurrentUser) {
                ChatAvatar(partnerAvatarUrl, visible = showAvatar)
                Spacer(modifier = Modifier.width(6.dp))
            }

            Box(
                modifier = if (message.deleted) Modifier
                else Modifier.combinedClickable(onClick = {}, onLongClick = { menuOpen = true })
            ) {
                when {
                    message.deleted -> DeletedBubble(bubbleShape, isCurrentUser)
                    message.isImage -> EncryptedChatImage(message.mediaUrl, bubbleShape, loadDecryptedMedia)
                    message.isVoice -> EncryptedVoiceMessage(message.mediaUrl, message.durationMs, isCurrentUser, bubbleShape, loadDecryptedMedia)
                    else -> Surface(
                        shape = bubbleShape,
                        color = if (isCurrentUser) MaterialTheme.colorScheme.primary
                        else MaterialTheme.colorScheme.surfaceVariant,
                        modifier = Modifier.widthIn(max = 264.dp)
                    ) {
                        Text(
                            text = message.text,
                            style = MaterialTheme.typography.bodyMedium,
                            color = if (isCurrentUser) MaterialTheme.colorScheme.onPrimary
                            else MaterialTheme.colorScheme.onSurfaceVariant,
                            modifier = Modifier.padding(horizontal = 14.dp, vertical = 9.dp)
                        )
                    }
                }

                MessageActionMenu(
                    expanded = menuOpen,
                    onDismiss = { menuOpen = false },
                    canCopy = message.type == "text",
                    canDelete = isCurrentUser,
                    onReact = { emoji ->
                        menuOpen = false
                        if (canReact) onReact(emoji) else onReactBlocked()
                    },
                    onCopy = {
                        menuOpen = false
                        clipboard.setText(AnnotatedString(message.text))
                    },
                    onDelete = { menuOpen = false; onDelete() }
                )
            }
        }

        if (message.reactions.isNotEmpty() && !message.deleted) {
            ReactionChip(
                emojis = message.reactions.values.toList(),
                modifier = Modifier
                    .align(if (isCurrentUser) Alignment.End else Alignment.Start)
                    .padding(start = if (isCurrentUser) 0.dp else 40.dp, end = if (isCurrentUser) 6.dp else 0.dp, top = 2.dp)
            )
        }

        if (showTimestamp) {
            val time = formatClockTime(message.createdAt)
            Text(
                text = if (showSeen) "Seen · $time" else time,
                style = MaterialTheme.typography.labelSmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.55f),
                modifier = Modifier
                    .align(if (isCurrentUser) Alignment.End else Alignment.Start)
                    .padding(start = if (isCurrentUser) 0.dp else 40.dp, end = if (isCurrentUser) 6.dp else 0.dp, top = 2.dp)
            )
        }
    }
}

@Composable
private fun DeletedBubble(shape: Shape, isCurrentUser: Boolean) {
    Surface(
        shape = shape,
        color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f),
        modifier = Modifier.widthIn(max = 264.dp)
    ) {
        Text(
            text = "This message was deleted",
            style = MaterialTheme.typography.bodyMedium,
            fontStyle = androidx.compose.ui.text.font.FontStyle.Italic,
            color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
            modifier = Modifier.padding(horizontal = 14.dp, vertical = 9.dp)
        )
    }
}

@Composable
private fun ReactionChip(emojis: List<String>, modifier: Modifier = Modifier) {
    Surface(
        shape = RoundedCornerShape(12.dp),
        color = MaterialTheme.colorScheme.surfaceVariant,
        modifier = modifier
    ) {
        Text(
            text = emojis.distinct().joinToString("") + if (emojis.size > 1) " ${emojis.size}" else "",
            style = MaterialTheme.typography.bodySmall,
            modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp)
        )
    }
}

@Composable
private fun MessageActionMenu(
    expanded: Boolean,
    onDismiss: () -> Unit,
    canCopy: Boolean,
    canDelete: Boolean,
    onReact: (String) -> Unit,
    onCopy: () -> Unit,
    onDelete: () -> Unit
) {
    DropdownMenu(expanded = expanded, onDismissRequest = onDismiss) {
        Row(
            modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
            horizontalArrangement = Arrangement.spacedBy(2.dp)
        ) {
            REACTION_EMOJIS.forEach { emoji ->
                Text(
                    text = emoji,
                    style = MaterialTheme.typography.titleLarge,
                    modifier = Modifier
                        .clip(CircleShape)
                        .clickable { onReact(emoji) }
                        .padding(6.dp)
                )
            }
        }
        if (canCopy) {
            DropdownMenuItem(
                text = { Text("Copy") },
                onClick = onCopy,
                leadingIcon = { Icon(Icons.Filled.ContentCopy, contentDescription = null) }
            )
        }
        if (canDelete) {
            DropdownMenuItem(
                text = { Text("Delete") },
                onClick = onDelete,
                leadingIcon = { Icon(Icons.Filled.Delete, contentDescription = null) }
            )
        }
    }
}

/** A centered date pill shown between messages from different days. */
@Composable
fun ChatDaySeparator(epochMillis: Long) {
    Box(modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp), contentAlignment = Alignment.Center) {
        Surface(
            shape = RoundedCornerShape(12.dp),
            color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.7f)
        ) {
            Text(
                text = chatDayLabel(epochMillis),
                style = MaterialTheme.typography.labelSmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.padding(horizontal = 12.dp, vertical = 3.dp)
            )
        }
    }
}

@Composable
private fun rememberMediaImageLoader(): ImageLoader {
    val context = LocalContext.current
    return remember {
        ImageLoader.Builder(context)
            .components {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) add(ImageDecoderDecoder.Factory())
                else add(GifDecoder.Factory())
            }
            .build()
    }
}

@Composable
private fun EncryptedChatImage(
    mediaUrl: String,
    shape: Shape,
    loadDecryptedMedia: suspend (String) -> ByteArray?
) {
    val bytes by produceState<ByteArray?>(initialValue = null, mediaUrl) {
        value = loadDecryptedMedia(mediaUrl)
    }
    val loader = rememberMediaImageLoader()
    val context = LocalContext.current
    var showFull by remember { mutableStateOf(false) }

    val b = bytes
    if (b == null) {
        Box(
            modifier = Modifier.size(200.dp).clip(shape).background(MaterialTheme.colorScheme.surfaceVariant),
            contentAlignment = Alignment.Center
        ) {
            CircularProgressIndicator(
                strokeWidth = 2.dp,
                modifier = Modifier.size(22.dp),
                color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
            )
        }
        return
    }

    val aspect = remember(b) { imageAspectRatio(b) }
    val model = remember(b) { ImageRequest.Builder(context).data(ByteBuffer.wrap(b)).build() }
    AsyncImage(
        model = model,
        imageLoader = loader,
        contentDescription = "Photo — tap to enlarge",
        contentScale = ContentScale.Fit,
        modifier = Modifier
            .clip(shape)
            .background(MaterialTheme.colorScheme.surfaceVariant)
            .chatMediaSize(aspect)
            .clickable { showFull = true }
    )

    if (showFull) {
        FullScreenImageViewer(bytes = b, imageLoader = loader, onDismiss = { showFull = false })
    }
}

/** Fits the media inside a ~240×320dp bubble at its true aspect ratio (scales small GIFs up to a
 *  consistent chat size, never squished). */
private fun Modifier.chatMediaSize(aspect: Float): Modifier {
    val maxW = 240f
    val maxH = 320f
    return if (aspect >= maxW / maxH) this.width(maxW.dp).aspectRatio(aspect)
    else this.height(maxH.dp).aspectRatio(aspect)
}

private fun imageAspectRatio(bytes: ByteArray): Float {
    val opts = android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds = true }
    runCatching { android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts) }
    val w = opts.outWidth
    val h = opts.outHeight
    return if (w > 0 && h > 0) w.toFloat() / h else 1f
}

/** Tap-to-enlarge: a full-screen view of the decrypted image (works for photos, GIFs, stickers). */
@Composable
private fun FullScreenImageViewer(
    bytes: ByteArray,
    imageLoader: ImageLoader,
    onDismiss: () -> Unit
) {
    val context = LocalContext.current
    Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) {
        val model = remember(bytes) { ImageRequest.Builder(context).data(ByteBuffer.wrap(bytes)).build() }
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Black.copy(alpha = 0.96f))
                .clickable(onClick = onDismiss),
            contentAlignment = Alignment.Center
        ) {
            AsyncImage(
                model = model,
                imageLoader = imageLoader,
                contentDescription = null,
                contentScale = ContentScale.Fit,
                modifier = Modifier.fillMaxWidth()
            )
            IconButton(
                onClick = onDismiss,
                modifier = Modifier.align(Alignment.TopEnd).padding(12.dp)
            ) {
                Icon(Icons.Filled.Close, contentDescription = "Close", tint = Color.White)
            }
        }
    }
}

@Composable
private fun EncryptedVoiceMessage(
    mediaUrl: String,
    durationMs: Long,
    isCurrentUser: Boolean,
    shape: Shape,
    loadDecryptedMedia: suspend (String) -> ByteArray?
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    var player by remember { mutableStateOf<MediaPlayer?>(null) }
    var tempFile by remember { mutableStateOf<File?>(null) }
    var playing by remember { mutableStateOf(false) }
    var loading by remember { mutableStateOf(false) }
    var positionMs by remember { mutableLongStateOf(0L) }
    val totalMs = durationMs.coerceAtLeast(1L)

    DisposableEffect(Unit) {
        onDispose {
            runCatching { player?.release() }
            tempFile?.delete()
        }
    }

    // Poll the player position so the progress bar advances during playback.
    LaunchedEffect(playing) {
        while (playing) {
            positionMs = player?.currentPosition?.toLong() ?: positionMs
            delay(100)
        }
    }

    fun toggle() {
        val p = player
        if (p != null) {
            if (p.isPlaying) { p.pause(); playing = false } else { p.start(); playing = true }
            return
        }
        if (loading) return
        loading = true
        scope.launch {
            val data = loadDecryptedMedia(mediaUrl)
            if (data == null) { loading = false; return@launch }
            val f = withContext(Dispatchers.IO) {
                File.createTempFile("voice_play", ".m4a", context.cacheDir).apply { writeBytes(data) }
            }
            tempFile = f
            val mp = MediaPlayer()
            runCatching {
                mp.setDataSource(f.absolutePath)
                mp.setOnCompletionListener { playing = false; positionMs = 0L; runCatching { mp.seekTo(0) } }
                mp.prepare()
                mp.start()
            }.onSuccess { player = mp; playing = true }.onFailure { mp.release() }
            loading = false
        }
    }

    Surface(
        shape = shape,
        color = if (isCurrentUser) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceVariant,
        modifier = Modifier.widthIn(max = 230.dp)
    ) {
        val tint = if (isCurrentUser) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant
        Row(
            modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            IconButton(onClick = { toggle() }, modifier = Modifier.size(36.dp)) {
                if (loading) {
                    CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(20.dp), color = tint)
                } else {
                    Icon(
                        imageVector = if (playing) Icons.Filled.Pause else Icons.Filled.PlayArrow,
                        contentDescription = if (playing) "Pause" else "Play",
                        tint = tint
                    )
                }
            }
            LinearProgressIndicator(
                progress = { if (totalMs > 0) (positionMs.toFloat() / totalMs).coerceIn(0f, 1f) else 0f },
                modifier = Modifier.width(92.dp),
                color = tint,
                trackColor = tint.copy(alpha = 0.25f)
            )
            Text(
                text = formatDuration(if (playing || positionMs > 0) positionMs else durationMs),
                style = MaterialTheme.typography.bodyMedium,
                color = tint
            )
        }
    }
}

@Composable
private fun ChatAvatar(url: String?, visible: Boolean) {
    val size = 28.dp
    if (!visible) {
        Spacer(modifier = Modifier.size(size))
        return
    }
    if (!url.isNullOrBlank()) {
        AsyncImage(
            model = url,
            contentDescription = null,
            contentScale = ContentScale.Crop,
            modifier = Modifier.size(size).clip(CircleShape)
        )
    } else {
        Box(
            modifier = Modifier.size(size).clip(CircleShape).background(MaterialTheme.colorScheme.surfaceVariant),
            contentAlignment = Alignment.Center
        ) {
            Icon(Icons.Filled.Person, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(16.dp))
        }
    }
}

/**
 * Composer: text + gallery + camera (images only), GIFs/stickers/Bitmoji inserted from the
 * keyboard (rich content), and hold-free voice notes. All media is E2E-encrypted before sending.
 */
@Composable
fun ChatComposer(
    value: String,
    onValueChange: (String) -> Unit,
    onSend: () -> Unit,
    onSendImage: (ByteArray) -> Unit,
    onSendVoice: (ByteArray, Long) -> Unit,
    canSendMedia: Boolean = true,
    onUpgrade: () -> Unit = {},
    modifier: Modifier = Modifier
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()

    // compress = true for real photos (gallery/camera); false for keyboard GIFs/stickers/Bitmoji
    // (compressing those would kill animation/transparency).
    fun readAndSend(uri: Uri, compress: Boolean) {
        scope.launch {
            val bytes = withContext(Dispatchers.IO) {
                val raw = runCatching { context.contentResolver.openInputStream(uri)?.use { it.readBytes() } }.getOrNull()
                raw?.let { if (compress) MediaCompressor.compressPhoto(it) else it }
            }
            bytes?.takeIf { it.isNotEmpty() }?.let(onSendImage)
        }
    }

    val galleryLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.PickVisualMedia()
    ) { uri: Uri? -> uri?.let { readAndSend(it, compress = true) } }

    var pendingCameraUri by remember { mutableStateOf<Uri?>(null) }
    val cameraLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.TakePicture()
    ) { success: Boolean -> if (success) pendingCameraUri?.let { readAndSend(it, compress = true) } }

    fun launchCamera() {
        val file = File(context.cacheDir, "chat_capture_${System.currentTimeMillis()}.jpg")
        val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
        pendingCameraUri = uri
        cameraLauncher.launch(uri)
    }
    val cameraPermissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission()
    ) { granted: Boolean -> if (granted) launchCamera() }

    // ── Voice recording ──────────────────────────────────────────────────────────
    var isRecording by remember { mutableStateOf(false) }
    var recordStart by remember { mutableLongStateOf(0L) }
    var elapsedMs by remember { mutableLongStateOf(0L) }
    val recorder = remember { mutableStateOf<MediaRecorder?>(null) }
    val recordFile = remember { mutableStateOf<File?>(null) }

    fun startRecording() {
        val f = File(context.cacheDir, "voice_${System.currentTimeMillis()}.m4a")
        val rec = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) MediaRecorder(context) else @Suppress("DEPRECATION") MediaRecorder()
        rec.setAudioSource(MediaRecorder.AudioSource.MIC)
        rec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
        rec.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
        rec.setOutputFile(f.absolutePath)
        runCatching { rec.prepare(); rec.start() }
            .onSuccess {
                recorder.value = rec; recordFile.value = f
                recordStart = System.currentTimeMillis(); elapsedMs = 0L; isRecording = true
            }
            .onFailure { runCatching { rec.release() }; f.delete() }
    }

    fun finishRecording(send: Boolean) {
        val rec = recorder.value
        val f = recordFile.value
        val dur = System.currentTimeMillis() - recordStart
        runCatching { rec?.stop() }
        runCatching { rec?.release() }
        recorder.value = null
        recordFile.value = null
        isRecording = false
        if (send && f != null && dur > 800) {
            scope.launch {
                val bytes = withContext(Dispatchers.IO) { runCatching { f.readBytes() }.getOrNull() }
                f.delete()
                bytes?.takeIf { it.isNotEmpty() }?.let { onSendVoice(it, dur) }
            }
        } else {
            f?.delete()
        }
    }

    val micPermissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission()
    ) { granted: Boolean -> if (granted) startRecording() }

    LaunchedEffect(isRecording) {
        while (isRecording) {
            elapsedMs = System.currentTimeMillis() - recordStart
            if (elapsedMs >= MAX_RECORDING_MS) { finishRecording(send = true); break } // auto-send at the cap
            delay(200)
        }
    }
    DisposableEffect(Unit) {
        onDispose { runCatching { recorder.value?.release() }; recordFile.value?.delete() }
    }

    if (isRecording) {
        Row(
            modifier = modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            IconButton(onClick = { finishRecording(send = false) }, modifier = Modifier.size(44.dp)) {
                Icon(Icons.Filled.Close, contentDescription = "Cancel", tint = MaterialTheme.colorScheme.error)
            }
            Box(modifier = Modifier.size(10.dp).clip(CircleShape).background(MaterialTheme.colorScheme.error))
            Text(
                text = "Recording… ${formatDuration(elapsedMs)}",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurface,
                modifier = Modifier.weight(1f)
            )
            IconButton(onClick = { finishRecording(send = true) }, modifier = Modifier.size(48.dp)) {
                Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send", tint = MaterialTheme.colorScheme.primary)
            }
        }
        return
    }

    Row(
        modifier = modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(2.dp)
    ) {
        ComposerMediaButton(
            icon = Icons.Filled.Image,
            description = "Send a photo",
            locked = !canSendMedia,
            onClick = { galleryLauncher.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) },
            onUpgrade = onUpgrade
        )
        ComposerMediaButton(
            icon = Icons.Filled.PhotoCamera,
            description = "Take a photo",
            locked = !canSendMedia,
            onClick = {
                if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
                    launchCamera() else cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
            },
            onUpgrade = onUpgrade
        )

        // Field that accepts GIFs / stickers / Bitmoji inserted from the keyboard (rich content).
        Surface(
            modifier = Modifier.weight(1f),
            shape = RoundedCornerShape(24.dp),
            color = MaterialTheme.colorScheme.surface,
            border = BorderStroke(1.dp, MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.2f))
        ) {
            RichContentTextField(
                value = value,
                onValueChange = onValueChange,
                // Keyboard GIF/sticker/Bitmoji: gated → route to paywall instead of sending.
                onImageReceived = { uri -> if (canSendMedia) readAndSend(uri, compress = false) else onUpgrade() },
                modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp),
                hint = "Message…"
            )
        }

        if (value.isBlank()) {
            // Mic when there's nothing typed (tap to record a voice note) — gated behind premium.
            ComposerMediaButton(
                icon = Icons.Filled.Mic,
                description = "Record a voice note",
                locked = !canSendMedia,
                size = 48.dp,
                onClick = {
                    if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)
                        startRecording() else micPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
                },
                onUpgrade = onUpgrade
            )
        } else {
            IconButton(onClick = onSend, modifier = Modifier.size(48.dp)) {
                Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send", tint = MaterialTheme.colorScheme.primary)
            }
        }
    }
}

/** Cap voice notes at 2 minutes; recording auto-stops and sends at this length. */
private const val MAX_RECORDING_MS = 120_000L

/** A composer media button with a lock badge + paywall routing when the couple isn't premium. */
@Composable
private fun ComposerMediaButton(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    description: String,
    locked: Boolean,
    onClick: () -> Unit,
    onUpgrade: () -> Unit,
    size: androidx.compose.ui.unit.Dp = 40.dp
) {
    Box {
        IconButton(onClick = { if (locked) onUpgrade() else onClick() }, modifier = Modifier.size(size)) {
            Icon(
                imageVector = icon,
                contentDescription = description,
                tint = if (locked) MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.45f)
                else MaterialTheme.colorScheme.primary
            )
        }
        if (locked) {
            Icon(
                imageVector = Icons.Filled.Lock,
                contentDescription = null,
                tint = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.size(12.dp).align(Alignment.BottomEnd)
            )
        }
    }
}

private fun formatDuration(ms: Long): String {
    val totalSec = (ms / 1000).toInt()
    val m = totalSec / 60
    val s = totalSec % 60
    return "%d:%02d".format(m, s)
}

/** "3:45 PM" — falls back to now for a just-sent message whose server timestamp hasn't resolved. */
private fun formatClockTime(ms: Long): String {
    val t = if (ms > 0) ms else System.currentTimeMillis()
    return java.text.SimpleDateFormat("h:mm a", java.util.Locale.getDefault()).format(java.util.Date(t))
}

/** "Today" / "Yesterday" / "March 4" for day separators. */
fun chatDayLabel(ms: Long): String {
    val t = if (ms > 0) ms else System.currentTimeMillis()
    val cal = java.util.Calendar.getInstance().apply { timeInMillis = t }
    val today = java.util.Calendar.getInstance()
    val yesterday = (today.clone() as java.util.Calendar).apply { add(java.util.Calendar.DAY_OF_YEAR, -1) }
    return when {
        isSameCalendarDay(cal, today) -> "Today"
        isSameCalendarDay(cal, yesterday) -> "Yesterday"
        else -> java.text.SimpleDateFormat("MMMM d", java.util.Locale.getDefault()).format(java.util.Date(t))
    }
}

/** True when two epoch millis fall on the same calendar day (0 is treated as now). */
fun isSameChatDay(a: Long, b: Long): Boolean {
    val ca = java.util.Calendar.getInstance().apply { timeInMillis = if (a > 0) a else System.currentTimeMillis() }
    val cb = java.util.Calendar.getInstance().apply { timeInMillis = if (b > 0) b else System.currentTimeMillis() }
    return isSameCalendarDay(ca, cb)
}

private fun isSameCalendarDay(a: java.util.Calendar, b: java.util.Calendar): Boolean =
    a.get(java.util.Calendar.YEAR) == b.get(java.util.Calendar.YEAR) &&
        a.get(java.util.Calendar.DAY_OF_YEAR) == b.get(java.util.Calendar.DAY_OF_YEAR)
