package com.cottondb.android.ui.day.thoughts import androidx.compose.foundation.background import androidx.compose.foundation.clickable 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.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf 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.shadow import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp import com.cottondb.android.day.thoughts.RoutedRecord import com.cottondb.android.day.thoughts.Thought import com.cottondb.android.day.thoughts.ThoughtMutation import com.cottondb.android.day.thoughts.ThoughtRead import com.cottondb.android.day.thoughts.ThoughtRepository import com.cottondb.android.design.CottonFonts import com.cottondb.android.design.CottonMetrics import com.cottondb.android.design.CottonTextStyles import com.cottondb.android.generated.CottonPalette import kotlinx.coroutines.CancellationException import kotlinx.coroutines.launch import kotlinx.serialization.json.JsonElement import java.time.Clock import java.time.Duration import java.time.Instant /** * One capture's ledger page. * * `audioUrl` is an object key, never a host path. A future Android playback * seam must first ask `read.mediaPath`, pass an existing local path to the * platform player, and only call `media.ensure` from that explicit detail * seam. This renderer neither fetches bytes nor draws a pretend audio player. * * Swift replaces a settled one-record capture with that record's screen. The * Android record destinations are not all hosted yet, so this bounded port * keeps the ledger page visible; root navigation can add that typed handover * when those destinations exist. */ @Composable fun ThoughtDetailScreen(id: String, repository: ThoughtRepository, clock: Clock, dataRevision: Long, onBack: () -> Unit, onNavigate: (String) -> Unit) { val scope = rememberCoroutineScope() var read by remember(id, repository) { mutableStateOf(null) } var loading by remember(id, repository) { mutableStateOf(true) } var failure by remember(id, repository) { mutableStateOf(null) } var writing by remember { mutableStateOf(false) } var menu by remember { mutableStateOf(false) } var notice by remember { mutableStateOf(null) } suspend fun reload() { loading = read == null try { read = repository.read(); failure = null } catch (cancelled: CancellationException) { throw cancelled } catch (error: Throwable) { failure = error.message ?: "Couldn't read this capture." } finally { loading = false } } LaunchedEffect(id, repository, dataRevision) { reload() } val thought = read?.thoughts?.firstOrNull { it.id == id } Box(Modifier.fillMaxSize().background(CottonPalette.groundMuted).safeDrawingPadding().imePadding()) { Column(Modifier.fillMaxSize().padding(horizontal = CottonMetrics.contentMargin)) { Row(Modifier.fillMaxWidth().padding(vertical = 14.dp), verticalAlignment = Alignment.CenterVertically) { Text("Back", Modifier.clickable(role = Role.Button, onClick = onBack).padding(8.dp), style = CottonTextStyles.preview, color = CottonPalette.inkSecondary) Text("Capture", Modifier.weight(1f), style = CottonTextStyles.screenTitle.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink) if (thought != null) Text("More", Modifier.clickable(role = Role.Button, onClick = { menu = true }).padding(8.dp), style = CottonTextStyles.preview, color = CottonPalette.ink) } when { loading -> ThoughtSkeleton() thought != null -> ThoughtPage(thought, read!!, clock, onNavigate) failure != null -> ThoughtUnreadable(failure!!) { scope.launch { reload() } } else -> ThoughtMissing() } } } if (menu && thought != null) AlertDialog( onDismissRequest = { menu = false }, title = { Text("Capture actions", fontFamily = CottonFonts.display) }, text = { if (thought.routeStatus == "pending") Text("Dismiss this capture", Modifier.fillMaxWidth().clickable(enabled = !writing, role = Role.Button) { if (!writing) { writing = true; menu = false scope.launch { try { when (val result = repository.dismiss(thought.id)) { ThoughtMutation.Success -> reload(); is ThoughtMutation.Failure -> notice = result.message } } finally { writing = false } } } }.padding(vertical = 12.dp), style = CottonTextStyles.body, color = CottonPalette.statusError) else Text("This capture has no further actions.", style = CottonTextStyles.body, color = CottonPalette.inkSecondary) }, confirmButton = { TextButton(onClick = { menu = false }) { Text("Done") } }, ) notice?.let { message -> AlertDialog(onDismissRequest = { notice = null }, title = { Text("Couldn’t change capture", fontFamily = CottonFonts.display) }, text = { Text(message) }, confirmButton = { TextButton(onClick = { notice = null }) { Text("OK") } }) } } @Composable private fun ThoughtPage(thought: Thought, read: ThoughtRead, clock: Clock, onNavigate: (String) -> Unit) = Column(verticalArrangement = Arrangement.spacedBy(18.dp)) { Column( Modifier.fillMaxWidth().shadow(3.dp, RoundedCornerShape(CottonMetrics.cardRadius)).background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius)).padding(22.dp), verticalArrangement = Arrangement.spacedBy(14.dp), ) { Text(if (thought.audioUrl.isNullOrBlank()) "THOUGHT" else "THOUGHT · SPOKEN", style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.type), color = CottonPalette.inkSecondary) Text(thought.rawText.orEmpty(), style = CottonTextStyles.body, color = CottonPalette.inkBody) Text("captured ${recordAge(thought.capturedAt, clock)}", style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.type), color = CottonPalette.inkSecondary) if (thought.routeStatus == "dismissed") Text("DROPPED", style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.type), color = CottonPalette.statusError) } ThoughtStoryLine(thought, read) val records = recordsOf(thought) if (records.size > 1) ThoughtBecame(records, read, onNavigate) } @Composable private fun ThoughtStoryLine(thought: Thought, read: ThoughtRead) = Column(Modifier.padding(start = 12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { Text(standing(thought, recordsOf(thought).size), style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand), color = if (thought.routeStatus == "pending") CottonPalette.statusError else CottonPalette.inkSecondary) proposalLine(thought)?.let { Text(it, style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand), color = CottonPalette.inkSecondary) } thought.sweepNote?.takeIf(String::isNotBlank)?.let { Text(it, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } } @Composable private fun ThoughtBecame(records: List, read: ThoughtRead, onNavigate: (String) -> Unit) = Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { Text("What it became · ${records.size}", style = CottonTextStyles.sectionLabel.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink) Column(Modifier.fillMaxWidth().background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius)).padding(horizontal = 18.dp)) { records.forEachIndexed { index, record -> if (index > 0) androidx.compose.material3.HorizontalDivider(color = CottonPalette.hairline) val fact = read.routedFacts[record.id] val personName = fact?.personId?.let { person -> read.people.firstOrNull { it.id == person }?.fullName } val title = if (record.kind == "person_note" && personName != null) "Note on $personName" else kindName(record.kind) Row(Modifier.fillMaxWidth().clickable(role = Role.Button, onClick = { recordPath(record, fact?.personId)?.let(onNavigate) }).semantics { contentDescription = "Open $title" }.padding(vertical = 12.dp), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text(title, style = CottonTextStyles.body, color = CottonPalette.ink); fact?.dateIso?.let { Text(dateFact(record.kind, it), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } } Text("Open", style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand), color = CottonPalette.inkSecondary) } } } } @Composable private fun ThoughtSkeleton() = Box(Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) { Box(Modifier.fillMaxWidth().padding(top = 36.dp).background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius)).padding(vertical = 110.dp)) } @Composable private fun ThoughtUnreadable(message: String, retry: () -> Unit) = Column(Modifier.padding(top = 40.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { Text("Couldn't read this capture.", style = CottonTextStyles.screenTitle, color = CottonPalette.ink); Text("It is on your database; this device could not read it just now.", style = CottonTextStyles.body, color = CottonPalette.inkBody); Text("Try again", Modifier.clickable(role = Role.Button, onClick = retry).padding(vertical = 8.dp), style = CottonTextStyles.body, color = CottonPalette.accent); Text(message, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } @Composable private fun ThoughtMissing() = Column(Modifier.padding(top = 40.dp)) { Text("This capture isn't here any more.", style = CottonTextStyles.screenTitle, color = CottonPalette.ink) } private fun recordsOf(thought: Thought): List { if (thought.routedRecords.isNotEmpty()) return thought.routedRecords val routedKind = thought.routedKind val routedId = thought.routedId return if (routedKind != null && routedId != null) { listOf(RoutedRecord(routedKind, routedId)) } else { emptyList() } } private fun standing(thought: Thought, count: Int): String = when { thought.routeStatus == "dismissed" -> "Dismissed — it stays on the record, out of the way."; count > 1 -> "This one became $count records."; thought.routeStatus != "pending" && count == 0 -> "Stayed a thought — nothing was made of it, and nothing needs to be."; else -> "Still waiting to be filed." } private fun proposalLine(thought: Thought): String? = when (thought.routeReason) { "low_confidence" -> proposalKind(thought)?.let { "Could be a $it — file it yourself." } ?: "Cotton could not place this yet."; "no_match" -> "Cotton could not place this yet."; else -> null } private fun proposalKind(thought: Thought): String? = thought.routeProposal?.get("target")?.jsonObjectOrNull()?.get("kind")?.jsonStringOrNull() ?: thought.routeProposal?.get("records")?.jsonArrayOrNull()?.firstOrNull()?.jsonObjectOrNull()?.get("target")?.jsonObjectOrNull()?.get("kind")?.jsonStringOrNull() private fun JsonElement.jsonObjectOrNull() = this as? kotlinx.serialization.json.JsonObject private fun JsonElement.jsonArrayOrNull() = this as? kotlinx.serialization.json.JsonArray private fun JsonElement.jsonStringOrNull() = (this as? kotlinx.serialization.json.JsonPrimitive)?.takeIf { it.isString }?.content private fun kindName(kind: String): String = when (kind) { "todo" -> "Todo"; "event" -> "Event"; "note" -> "Note"; "journal" -> "Journal"; "person_note" -> "Note"; "person" -> "Person"; "location" -> "Location"; "mood" -> "Mood"; "transaction" -> "Transaction"; else -> kind } private fun dateFact(kind: String, iso: String): String = when (kind) { "todo" -> "due $iso"; "event" -> "starts $iso"; "journal" -> "page for $iso"; "mood" -> "felt on $iso"; "transaction" -> "on $iso"; else -> iso } private fun recordPath(record: RoutedRecord, personId: String?): String? = when (record.kind) { "todo" -> "/todos/todo/${record.id}"; "event" -> "/calendar/event/${record.id}"; "note" -> "/notes/note/${record.id}"; "journal" -> "/journal"; "person_note" -> personId?.let { "/people/person/$it" }; "person" -> "/people/person/${record.id}"; "location" -> "/locations/location/${record.id}"; "mood" -> "/mood"; else -> null } private fun recordAge(iso: String?, clock: Clock): String { val instant = iso?.let { runCatching { Instant.parse(it) }.getOrNull() } ?: return ""; val minutes = Duration.between(instant, clock.instant()).toMinutes().coerceAtLeast(0); return when { minutes < 1 -> "just now"; minutes < 60 -> "${minutes}m ago"; minutes < 1440 -> "${minutes / 60}h ago"; else -> "${minutes / 1440}d ago" } }