package app.closer.ui.answers

import app.closer.ui.theme.closerBackgroundBrush
import app.closer.ui.theme.closerCardColor
import app.closer.ui.theme.closerSoftPinkColor
import app.closer.ui.theme.closerSoftPurpleColor
import app.closer.ui.theme.closerSoftSurfaceColor
import android.provider.Settings
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.expandVertically
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.Image
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.ui.res.painterResource
import app.closer.R
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import app.closer.ui.components.CloserHeartLoader
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import app.closer.ui.components.CelebrationOverlay
import androidx.compose.ui.Alignment
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.closer.core.navigation.AppRoute
import app.closer.domain.model.LocalAnswer
import app.closer.domain.model.Question
import app.closer.domain.DailyModeResolver
import app.closer.ui.questions.displayCategoryName
import app.closer.ui.questions.displayQuestionType
import app.closer.ui.components.BrandMessageRotator

@Composable
fun AnswerRevealScreen(
    questionId: String,
    onNavigate: (String) -> Unit = {},
    viewModel: AnswerRevealViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()

    LaunchedEffect(state.isLoading, state.coupleId) {
        if (!state.isLoading && state.coupleId == null) {
            onNavigate(AppRoute.CREATE_INVITE)
        }
    }

    AnswerRevealContent(
        state = state,
        questionId = questionId,
        onReveal = {
            viewModel.revealAnswer()
            viewModel.refreshPartnerAnswer()
        },
        onRefresh = viewModel::refreshPartnerAnswer,
        onAnswerQuestion = {
            val coupleId = state.coupleId
            if (coupleId != null) {
                onNavigate(AppRoute.conversation(coupleId, "q_" + questionId))
            } else {
                // Discussing requires a paired partner; send unpaired users to invite one.
                onNavigate(AppRoute.CREATE_INVITE)
            }
        },
        onHistory = { onNavigate(AppRoute.ANSWER_HISTORY) },
        onHome = { onNavigate(AppRoute.HOME) },
        onFollowUpSelected = { option -> viewModel.onFollowUpSelected(option, onNavigate) },
        onSaveLore = viewModel::saveCoupleLoré,
        onTinyActionSaved = viewModel::onTinyActionSaved,
        onSnackbarShown = viewModel::clearSnackbar
    )
}

@Composable
private fun AnswerRevealContent(
    state: AnswerRevealUiState,
    questionId: String,
    onReveal: () -> Unit,
    onAnswerQuestion: () -> Unit,
    onHistory: () -> Unit,
    onHome: () -> Unit,
    onRefresh: () -> Unit = {},
    onFollowUpSelected: (FollowUpOption) -> Unit = {},
    onSaveLore: () -> Unit = {},
    onTinyActionSaved: () -> Unit = {},
    onSnackbarShown: () -> Unit = {}
) {
    val context = LocalContext.current
    val snackbarHostState = remember { SnackbarHostState() }
    val reducedMotion = Settings.Global.getFloat(
        context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f
    ) == 0f

    state.snackbarMessage?.let { message ->
        LaunchedEffect(message) {
            snackbarHostState.showSnackbar(message)
            onSnackbarShown()
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(
                closerBackgroundBrush()
            )
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .safeDrawingPadding()
                .navigationBarsPadding()
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 20.dp, vertical = 20.dp),
            verticalArrangement = Arrangement.spacedBy(18.dp)
        ) {
            RevealHeader()

            when {
                state.isLoading -> RevealMessageCard {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(14.dp)
                    ) {
                        CloserHeartLoader(size = 32.dp)
                        Text("Loading reveal")
                    }
                }
                state.error != null -> RevealMessageCard {
                    Text(
                        text = state.error,
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                state.answer == null -> NoAnswerState(
                    question = state.question,
                    questionId = questionId,
                    onAnswerQuestion = onAnswerQuestion,
                    onHome = onHome
                )
                // Sealed reveal phases (schemaVersion 3) — checked before isRevealed
                state.sealedRevealPhase == SealedRevealPhase.RELEASING_KEY ->
                    ReleasingKeyState()
                state.sealedRevealPhase == SealedRevealPhase.WAITING_FOR_PARTNER ->
                    WaitingForPartnerState(onRefresh = onRefresh, onHome = onHome)
                state.sealedRevealPhase == SealedRevealPhase.LOST_LOCAL_KEY ->
                    LostLocalKeyState(onHome = onHome)
                state.sealedRevealPhase == SealedRevealPhase.BOTH_ANSWERED ->
                    BothAnsweredSealedState(
                        question = state.question,
                        onReveal = onReveal,
                        onHistory = onHistory
                    )
                state.sealedRevealPhase == SealedRevealPhase.ANSWER_SEALED ->
                    AnswerSealedState(question = state.question, onHome = onHome)
                // Legacy (enc:v1:) reveal path
                !state.answer.isRevealed -> ReadyToRevealState(
                    answer = state.answer,
                    partnerAnswer = state.partnerAnswer,
                    question = state.question,
                    onReveal = onReveal,
                    onHistory = onHistory
                )
                else -> AnimatedVisibility(
                    visible = true,
                    enter = if (reducedMotion) fadeIn(tween(0))
                            else fadeIn(tween(380)) + expandVertically(tween(380))
                ) {
                    val tinyActionMode = state.question?.tags
                        ?.firstOrNull { it.startsWith("mode_") }
                        ?.removePrefix("mode_")
                        ?.let { DailyModeResolver.getMode(it) }

                    Column(verticalArrangement = Arrangement.spacedBy(18.dp)) {
                        RevealedState(
                            answer = state.answer,
                            partnerAnswer = state.partnerAnswer,
                            question = state.question,
                            onHistory = onHistory,
                            onHome = onHome,
                            onSaveLore = onSaveLore,
                            loreSaved = state.loreSaved,
                            wasSealed = state.answer.schemaVersion == 3
                        )
                        if (tinyActionMode != null) {
                            TinyActionCard(
                                mode = tinyActionMode,
                                onDoThis = onTinyActionSaved
                            )
                        }
                        if (state.followUpOptions.isNotEmpty()) {
                            FollowUpSection(
                                options = state.followUpOptions,
                                onOptionSelected = onFollowUpSelected
                            )
                        }
                    }
                }
            }
        }

        SnackbarHost(
            hostState = snackbarHostState,
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(horizontal = 20.dp, vertical = 24.dp)
        )

        // Calm celebration the moment both partners' answers are revealed on this device.
        var celebrate by remember { mutableStateOf(false) }
        var celebrated by remember { mutableStateOf(false) }
        LaunchedEffect(state.sealedRevealPhase, state.answer?.isRevealed, state.partnerAnswer) {
            val bothRevealed = state.sealedRevealPhase == SealedRevealPhase.REVEALED ||
                (state.answer?.isRevealed == true && state.partnerAnswer != null)
            if (bothRevealed && !celebrated) {
                celebrated = true
                celebrate = true
            }
        }
        CelebrationOverlay(visible = celebrate, onFinished = { celebrate = false })
    }
}

@Composable
private fun NoAnswerState(
    question: Question?,
    questionId: String,
    onAnswerQuestion: () -> Unit,
    onHome: () -> Unit
) {
    RevealMessageCard {
        Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
            RevealPill("No answer yet")
            Text(
                text = question?.text ?: "This prompt is ready when you are.",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.onSurface,
                fontWeight = FontWeight.SemiBold,
                maxLines = 4,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = "Answer privately first. Reveal can wait until there is something worth opening together.",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )
            Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                Button(
                    onClick = onAnswerQuestion,
                    modifier = Modifier
                        .weight(1f)
                        .heightIn(min = 48.dp),
                    shape = RoundedCornerShape(16.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0xFFB98AF4),
                        contentColor = Color(0xFF24122F)
                    )
                ) {
                    Text("Answer")
                }
                OutlinedButton(
                    onClick = onHome,
                    modifier = Modifier
                        .weight(1f)
                        .heightIn(min = 48.dp),
                    shape = RoundedCornerShape(16.dp)
                ) {
                    Text("Not now")
                }
            }
        }
    }
}

@Composable
private fun ReadyToRevealState(
    answer: LocalAnswer,
    partnerAnswer: LocalAnswer?,
    question: Question?,
    onReveal: () -> Unit,
    onHistory: () -> Unit
) {
    RevealMessageCard {
        Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
            RevealPill("Private answer saved")
            Text(
                text = question?.text ?: answer.questionText,
                style = MaterialTheme.typography.titleLarge,
                color = MaterialTheme.colorScheme.onSurface,
                fontWeight = FontWeight.SemiBold,
                maxLines = 4,
                overflow = TextOverflow.Ellipsis
            )
            AnswerPreview(answer = answer, revealed = false)
            PartnerAnswerSection(partnerAnswer = partnerAnswer, revealed = false)
            Text(
                text = "No rush. Reveal this only when you want the conversation to open.",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )
            Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                Button(
                    onClick = onReveal,
                    modifier = Modifier
                        .weight(1f)
                        .heightIn(min = 48.dp),
                    shape = RoundedCornerShape(16.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0xFFB98AF4),
                        contentColor = Color(0xFF24122F)
                    )
                ) {
                    Text("Reveal answer")
                }
                OutlinedButton(
                    onClick = onHistory,
                    modifier = Modifier
                        .weight(1f)
                        .heightIn(min = 48.dp),
                    shape = RoundedCornerShape(16.dp)
                ) {
                    Text("Saved answers")
                }
            }
        }
    }
}

// ── Sealed-answer reveal states (Batch 11) ───────────────────────────────────

private val waitingCopy = listOf(
    "Your answer is in. Now we wait dramatically.",
    "Locked in. Let's see what they choose.",
    "You picked. The suspense is tiny but real.",
)

private val matchedCopy = listOf(
    "You matched. Suspiciously cute.",
    "Same pick. The lore deepens.",
    "Both chose this. Tiny destiny.",
)

private val differentCopy = listOf(
    "Different picks. Honestly, useful.",
    "Two vibes entered the chat.",
    "Not a match, but very on-brand.",
)

private fun dayIndexCopy(list: List<String>): String {
    val doy = java.util.Calendar.getInstance().get(java.util.Calendar.DAY_OF_YEAR)
    return list[doy % list.size]
}

@Composable
private fun AnswerSealedState(
    question: Question?,
    onHome: () -> Unit
) {
    RevealMessageCard {
        Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
            RevealPill("Your answer is sealed")
            Text(
                text = question?.text ?: "Your answer is private.",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.onSurface,
                fontWeight = FontWeight.SemiBold,
                maxLines = 4,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = dayIndexCopy(waitingCopy),
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
            OutlinedButton(
                onClick = onHome,
                modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp),
                shape = RoundedCornerShape(16.dp)
            ) {
                Text("Back to home")
            }
        }
    }
}

@Composable
private fun BothAnsweredSealedState(
    question: Question?,
    onReveal: () -> Unit,
    onHistory: () -> Unit
) {
    RevealMessageCard {
        Column(
            verticalArrangement = Arrangement.spacedBy(14.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Image(
                painter = painterResource(R.drawable.illustration_reveal_celebration),
                contentDescription = null,
                modifier = Modifier.size(140.dp)
            )
            RevealPill("Both answers are in")
            Text(
                text = question?.text ?: "Both of you answered.",
                style = MaterialTheme.typography.titleLarge,
                color = MaterialTheme.colorScheme.onSurface,
                fontWeight = FontWeight.SemiBold,
                maxLines = 4,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = "Both of you picked. Tap reveal to find out.",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
            Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                Button(
                    onClick = onReveal,
                    modifier = Modifier.weight(1f).heightIn(min = 48.dp),
                    shape = RoundedCornerShape(16.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0xFFB98AF4),
                        contentColor = Color(0xFF24122F)
                    )
                ) {
                    Text("Reveal answer")
                }
                OutlinedButton(
                    onClick = onHistory,
                    modifier = Modifier.weight(1f).heightIn(min = 48.dp),
                    shape = RoundedCornerShape(16.dp)
                ) {
                    Text("Saved answers")
                }
            }
        }
    }
}

@Composable
private fun ReleasingKeyState() {
    RevealMessageCard {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(14.dp)
        ) {
            CloserHeartLoader(size = 32.dp)
            Text(
                text = "Opening reveal…",
                style = MaterialTheme.typography.bodyLarge,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

@Composable
private fun WaitingForPartnerState(
    onRefresh: () -> Unit,
    onHome: () -> Unit
) {
    RevealMessageCard {
        Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
            RevealPill("Almost there")
            Text(
                text = "Waiting for your partner to finish reveal.",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.onSurface,
                fontWeight = FontWeight.SemiBold,
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = "Your answer key is released. You'll get a notification when your partner completes the reveal — no need to keep checking.",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 4,
                overflow = TextOverflow.Ellipsis
            )
            Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                Button(
                    onClick = onRefresh,
                    modifier = Modifier.weight(1f).heightIn(min = 48.dp),
                    shape = RoundedCornerShape(16.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0xFFB98AF4),
                        contentColor = Color(0xFF24122F)
                    )
                ) {
                    Text("Check again")
                }
                OutlinedButton(
                    onClick = onHome,
                    modifier = Modifier.weight(1f).heightIn(min = 48.dp),
                    shape = RoundedCornerShape(16.dp)
                ) {
                    Text("Back to home")
                }
            }
        }
    }
}

@Composable
private fun LostLocalKeyState(onHome: () -> Unit) {
    RevealMessageCard {
        Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
            RevealPill("Reveal unavailable")
            Text(
                text = "This answer cannot be revealed from this device.",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.onSurface,
                fontWeight = FontWeight.SemiBold,
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = "The sealed answer key is stored on the device you originally answered on. Open the app on that device to complete the reveal.",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 5,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = "If you no longer have that device, this answer cannot be recovered.",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.error.copy(alpha = 0.75f),
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )
            OutlinedButton(
                onClick = onHome,
                modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp),
                shape = RoundedCornerShape(16.dp)
            ) {
                Text("Back to home")
            }
        }
    }
}

@Composable
private fun RevealedState(
    answer: LocalAnswer,
    partnerAnswer: LocalAnswer?,
    question: Question?,
    onHistory: () -> Unit,
    onHome: () -> Unit,
    onSaveLore: () -> Unit = {},
    loreSaved: Boolean = false,
    wasSealed: Boolean = false
) {
    val matchLine = if (partnerAnswer != null) {
        val ownIds = answer.selectedOptionIds.toSet()
        val partnerIds = partnerAnswer.selectedOptionIds.toSet()
        when {
            ownIds.isNotEmpty() && ownIds == partnerIds -> dayIndexCopy(matchedCopy)
            ownIds.isNotEmpty() && partnerIds.isNotEmpty() -> dayIndexCopy(differentCopy)
            else -> null
        }
    } else null

    RevealMessageCard {
        Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                RevealPill(if (wasSealed) "Sealed reveal" else "Revealed")
                RevealPill(answer.category.displayCategoryName())
                RevealPill(answer.answerType.displayQuestionType())
            }
            if (matchLine != null) {
                Text(
                    text = matchLine,
                    style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.SemiBold),
                    color = Color(0xFF56306F),
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
            Text(
                text = question?.text ?: answer.questionText,
                style = MaterialTheme.typography.titleLarge,
                color = MaterialTheme.colorScheme.onSurface,
                fontWeight = FontWeight.SemiBold,
                maxLines = 4,
                overflow = TextOverflow.Ellipsis
            )
            AnswerPreview(answer = answer, revealed = true)
            PartnerAnswerSection(partnerAnswer = partnerAnswer, revealed = true)
            Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                Button(
                    onClick = onHistory,
                    modifier = Modifier
                        .weight(1f)
                        .heightIn(min = 48.dp),
                    shape = RoundedCornerShape(16.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0xFFB98AF4),
                        contentColor = Color(0xFF24122F)
                    )
                ) {
                    Text("Saved answers")
                }
                OutlinedButton(
                    onClick = onHome,
                    modifier = Modifier
                        .weight(1f)
                        .heightIn(min = 48.dp),
                    shape = RoundedCornerShape(16.dp)
                ) {
                    Text("Home")
                }
            }
            if (!loreSaved) {
                androidx.compose.material3.TextButton(
                    onClick = onSaveLore,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text(
                        "Save to Couple Lore",
                        style = MaterialTheme.typography.labelMedium,
                        color = Color(0xFF56306F).copy(alpha = 0.75f)
                    )
                }
            } else {
                Text(
                    text = "Saved to Couple Lore.",
                    style = MaterialTheme.typography.labelSmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.fillMaxWidth(),
                    textAlign = androidx.compose.ui.text.style.TextAlign.Center
                )
            }
        }
    }
}

@Composable
private fun TinyActionCard(
    mode: DailyModeResolver.DailyMode,
    onDoThis: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(28.dp),
        colors = CardDefaults.cardColors(containerColor = closerSoftPinkColor(alpha = 0.84f)),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(20.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Text(
                text = mode.actionCopy,
                style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.SemiBold),
                color = MaterialTheme.colorScheme.onSecondaryContainer,
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )
            Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
                Button(
                    onClick = onDoThis,
                    modifier = Modifier
                        .weight(1f)
                        .heightIn(min = 40.dp),
                    shape = RoundedCornerShape(14.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0xFFB98AF4),
                        contentColor = Color(0xFF24122F)
                    )
                ) {
                    Text("Do this tonight", style = MaterialTheme.typography.labelMedium)
                }
            }
        }
    }
}

@Composable
private fun FollowUpSection(
    options: List<FollowUpOption>,
    onOptionSelected: (FollowUpOption) -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(28.dp),
        colors = CardDefaults.cardColors(containerColor = closerCardColor(alpha = 0.94f)),
        elevation = CardDefaults.cardElevation(defaultElevation = 6.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(20.dp),
            verticalArrangement = Arrangement.spacedBy(14.dp)
        ) {
            Text(
                text = "Want to keep the conversation going?",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.onSurface,
                fontWeight = FontWeight.SemiBold,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = "These are optional — no pressure, just possibilities.",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
            options.forEach { option ->
                FollowUpChip(
                    label = option.label,
                    onClick = { onOptionSelected(option) }
                )
            }
        }
    }
}

@Composable
private fun FollowUpChip(
    label: String,
    onClick: () -> Unit
) {
    Surface(
        modifier = Modifier
            .fillMaxWidth()
            .heightIn(min = 52.dp)
            .clickable(onClick = onClick),
        shape = RoundedCornerShape(18.dp),
        color = closerSoftSurfaceColor()
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 12.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = label,
                style = MaterialTheme.typography.bodyLarge,
                color = MaterialTheme.colorScheme.onPrimaryContainer,
                fontWeight = FontWeight.SemiBold,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier.weight(1f)
            )
            Text(
                text = "→",
                style = MaterialTheme.typography.titleMedium,
                color = Color(0xFFB98AF4),
                fontWeight = FontWeight.Bold
            )
        }
    }
}

@Composable
private fun RevealMessageCard(content: @Composable () -> Unit) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(28.dp),
        colors = CardDefaults.cardColors(containerColor = closerCardColor(alpha = 0.94f)),
        elevation = CardDefaults.cardElevation(defaultElevation = 10.dp)
    ) {
        Box(modifier = Modifier.padding(20.dp)) {
            content()
        }
    }
}

@Composable
private fun RevealHeader() {
    Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
        Text(
            text = "Reveal together",
            style = MaterialTheme.typography.headlineLarge.copy(fontWeight = FontWeight.SemiBold),
            color = MaterialTheme.colorScheme.onSurface,
            maxLines = 2,
            overflow = TextOverflow.Ellipsis
        )
        Text(
            text = "A saved answer can stay private, become a shared reflection, or simply wait for the right moment.",
            style = MaterialTheme.typography.bodyLarge,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            maxLines = 4,
            overflow = TextOverflow.Ellipsis
        )
    }
}

@Composable
private fun AnswerPreview(
    answer: LocalAnswer,
    revealed: Boolean
) {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(20.dp),
        color = if (revealed) closerSoftPurpleColor() else closerSoftSurfaceColor()
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(6.dp)
        ) {
            Text(
                text = if (revealed) "Opened answer" else "Private preview",
                style = MaterialTheme.typography.labelMedium,
                color = MaterialTheme.colorScheme.onPrimaryContainer,
                fontWeight = FontWeight.SemiBold
            )
            Text(
                text = if (revealed) answer.revealSummary() else answer.privatePreview(),
                style = MaterialTheme.typography.bodyLarge,
                color = MaterialTheme.colorScheme.onSurface,
                maxLines = 6,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}

@Composable
private fun RevealPill(label: String) {
    Surface(
        shape = RoundedCornerShape(999.dp),
        color = closerSoftSurfaceColor(),
        modifier = Modifier.heightIn(min = 32.dp)
    ) {
        Text(
            text = label,
            modifier = Modifier.padding(horizontal = 11.dp, vertical = 7.dp),
            style = MaterialTheme.typography.labelMedium,
            color = MaterialTheme.colorScheme.onSurface,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }
}

@Composable
private fun PartnerAnswerSection(partnerAnswer: LocalAnswer?, revealed: Boolean) {
    when {
        partnerAnswer == null -> WaitingForPartnerCard()
        revealed -> PartnerAnswerPreview(answer = partnerAnswer)
        else -> WaitingForPartnerCard()
    }
}

@Composable
private fun PartnerAnswerPreview(answer: LocalAnswer) {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(20.dp),
        color = MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.78f)
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(6.dp)
        ) {
            Text(
                text = "Your partner answered",
                style = MaterialTheme.typography.labelMedium,
                color = MaterialTheme.colorScheme.onTertiaryContainer,
                fontWeight = FontWeight.SemiBold
            )
            Text(
                text = answer.partnerRevealSummary(),
                style = MaterialTheme.typography.bodyLarge,
                color = MaterialTheme.colorScheme.onSurface,
                maxLines = 6,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}

@Composable
private fun WaitingForPartnerCard() {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(20.dp),
        color = closerSoftSurfaceColor(alpha = 0.60f)
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(6.dp)
        ) {
            Text(
                text = "Partner answer",
                style = MaterialTheme.typography.labelMedium,
                color = MaterialTheme.colorScheme.onPrimaryContainer,
                fontWeight = FontWeight.SemiBold
            )
            Text(
                text = "Waiting for your partner to answer...",
                style = MaterialTheme.typography.bodyLarge,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )
            BrandMessageRotator(style = MaterialTheme.typography.bodySmall)
        }
    }
}

fun LocalAnswer.revealSummary(): String {
    return when (answerType) {
        "written" -> writtenText.orEmpty()
        "scale" -> "You chose ${scaleValue ?: "-"}."
        "single_choice", "multi_choice", "this_or_that" -> selectedOptionTexts
            .ifEmpty { selectedOptionIds }
            .joinToString()
        else -> writtenText ?: selectedOptionTexts.joinToString().ifBlank { "Answer saved." }
    }
}

private fun LocalAnswer.privatePreview(): String {
    return when (answerType) {
        "written" -> writtenText?.takeIf { it.isNotBlank() }?.let { "Your written answer is saved." }
            ?: "Your answer is saved."
        "scale" -> "Your scale answer is saved."
        "single_choice", "multi_choice", "this_or_that" -> "Your choice is saved."
        else -> "Your answer is saved."
    }
}

private fun LocalAnswer.partnerRevealSummary(): String {
    return when (answerType) {
        "written" -> writtenText.orEmpty()
        "scale" -> "They chose ${scaleValue ?: "-"}."
        "single_choice", "multi_choice", "this_or_that" -> selectedOptionTexts
            .ifEmpty { selectedOptionIds }
            .joinToString()
        else -> writtenText ?: selectedOptionTexts.joinToString().ifBlank { "Answer saved." }
    }
}

@Preview
@Composable
fun AnswerRevealScreenPreview() {
    AnswerRevealContent(
        state = AnswerRevealUiState(
            isLoading = false,
            answer = LocalAnswer(
                questionId = "demo",
                questionText = "What helped you feel close this week?",
                category = "gratitude",
                answerType = "written",
                writtenText = "The quiet walk after dinner.",
                isRevealed = true
            ),
            followUpOptions = listOf(FollowUpOption.DEEPER_FOLLOW_UP, FollowUpOption.SAVE_MEMORY)
        ),
        questionId = "demo",
        onReveal = {},
        onAnswerQuestion = {},
        onHistory = {},
        onHome = {},
        onFollowUpSelected = {}
    )
}
