package app.closer.ui.home

import app.closer.core.navigation.AppRoute
import app.closer.domain.model.Question
import app.closer.domain.model.QuestionCategory
import androidx.compose.foundation.layout.Spacer
import androidx.compose.material3.Button
import androidx.compose.ui.window.Dialog
import app.closer.ui.components.CelebrationOverlay
import app.closer.ui.components.CategoryGlyph
import app.closer.ui.components.CloserActionButton
import app.closer.ui.components.CloserButtonStyle
import app.closer.ui.components.CloserCard
import app.closer.ui.components.CloserClickableCard
import app.closer.ui.components.CloserElevations
import app.closer.ui.components.CloserPill
import app.closer.ui.components.CloserRadii
import app.closer.ui.components.ErrorState
import app.closer.ui.components.LoadingState
import app.closer.ui.questions.displayCategoryName
import app.closer.ui.settings.SettingsInk
import app.closer.ui.settings.SettingsMuted
import app.closer.ui.settings.SettingsSoft
import app.closer.ui.theme.CloserPalette
import app.closer.ui.theme.closerBackgroundBrush
import app.closer.ui.theme.closerCardColor
import app.closer.ui.theme.isCloserDarkTheme
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
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.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.TrendingUp
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.LocalFireDepartment
import app.closer.domain.model.OutcomeDay
import app.closer.ui.components.OutcomeCheckInDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
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 androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.foundation.clickable
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.hilt.navigation.compose.hiltViewModel
import app.closer.R

@Composable
fun HomeScreen(
    onNavigate: (String) -> Unit = {},
    viewModel: HomeViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()
    val snackbarHostState = remember { SnackbarHostState() }

    LaunchedEffect(state.partnerLeftEvent, state.partnerName) {
        if (state.partnerLeftEvent) {
            val partner = state.partnerName
            val message = if (!partner.isNullOrBlank()) {
                "You are no longer paired with $partner."
            } else {
                "You are no longer paired."
            }
            snackbarHostState.showSnackbar(message)
            viewModel.consumePartnerLeftEvent()
        }
    }

    LaunchedEffect(state.reminderSentEvent) {
        if (state.reminderSentEvent) {
            snackbarHostState.showSnackbar("Reminder sent to your partner.")
            viewModel.consumeReminderSentEvent()
        }
    }

    LaunchedEffect(state.needsRecovery) {
        if (state.needsRecovery) {
            onNavigate(app.closer.core.navigation.AppRoute.RECOVERY)
        }
    }

    var showBaselineDialog by remember { mutableStateOf(false) }
    var showFollowUpDialog by remember { mutableStateOf(false) }
    var pendingFollowUpDay by remember { mutableStateOf<OutcomeDay?>(null) }

    LaunchedEffect(state.showOutcomeBaselineDialog) {
        showBaselineDialog = state.showOutcomeBaselineDialog
    }
    LaunchedEffect(state.showOutcomeFollowUpDialog, state.outcomeFollowUpDay) {
        showFollowUpDialog = state.showOutcomeFollowUpDialog
        pendingFollowUpDay = state.outcomeFollowUpDay
    }

    if (showBaselineDialog) {
        OutcomeCheckInDialog(
            title = "Quick check-in",
            subtitle = "Before you start, how are you feeling about your relationship right now?",
            onDismiss = {
                viewModel.markBaselineOutcomeShown()
                showBaselineDialog = false
            },
            onSubmit = { scores ->
                viewModel.submitOutcome(OutcomeDay.BASELINE.key, scores)
                showBaselineDialog = false
            }
        )
    }

    pendingFollowUpDay?.let { day ->
        if (showFollowUpDialog) {
            OutcomeCheckInDialog(
                title = "${day.label} check-in",
                subtitle = "How are you feeling now compared to when you started?",
                onDismiss = {
                    viewModel.markFollowUpOutcomeShown(day.key)
                    showFollowUpDialog = false
                    pendingFollowUpDay = null
                },
                onSubmit = { scores ->
                    viewModel.submitOutcome(day.key, scores)
                    showFollowUpDialog = false
                    pendingFollowUpDay = null
                }
            )
        }
    }

    LaunchedEffect(state.outcomeSubmitSuccess, state.outcomeError) {
        state.outcomeError?.let { snackbarHostState.showSnackbar(it); viewModel.consumeOutcomeError() }
        if (state.outcomeSubmitSuccess) {
            snackbarHostState.showSnackbar("Check-in saved")
            viewModel.consumeOutcomeSuccess()
        }
    }

    state.streakMilestone?.let { milestone ->
        StreakMilestoneDialog(
            milestone = milestone,
            partnerName = state.partnerName,
            onDismiss = viewModel::consumeStreakMilestone
        )
    }

    HomeContent(
        state = state,
        snackbarHostState = snackbarHostState,
        onNavigate = onNavigate,
        onDailyQuestion = { onNavigate(AppRoute.DAILY_QUESTION) },
        onPacks = { onNavigate(AppRoute.QUESTION_PACKS) },
        onCategory = { categoryId -> onNavigate(AppRoute.questionCategory(categoryId)) },
        onHistory = { onNavigate(AppRoute.ANSWER_HISTORY) },
        onSettings = { onNavigate(AppRoute.SETTINGS) },
        onInvite = { onNavigate(AppRoute.CREATE_INVITE) },
        onAcceptInvite = { onNavigate(AppRoute.ACCEPT_INVITE) },
        onReminder = viewModel::sendGentleReminder,
        onReveal = { state.dailyQuestion?.id?.let { onNavigate(AppRoute.answerReveal(it)) } },
        onFollowUp = { state.dailyQuestion?.let { onNavigate(AppRoute.questionThread(state.coupleId ?: "", it.id)) } },
        onRefresh = viewModel::loadHome,
        onPartner = { if (state.isPaired) onNavigate(AppRoute.PARTNER_HOME) }
    )
}

data class HomeCallbacks(
    val onDailyQuestion: () -> Unit,
    val onReminder: () -> Unit,
    val onReveal: () -> Unit,
    val onFollowUp: () -> Unit,
    val onPacks: () -> Unit,
    val onCategory: (String) -> Unit,
    val onHistory: () -> Unit,
    val onSettings: () -> Unit,
    val onInvite: () -> Unit,
    val onAcceptInvite: () -> Unit,
    val onRefresh: () -> Unit
)

private fun HomeCallbacks.toActionHandler(onNavigate: (String) -> Unit): (HomeAction) -> Unit = { action ->
    when (action.target) {
        HomeActionTarget.InvitePartner -> onInvite()
        HomeActionTarget.DailyQuestion -> onDailyQuestion()
        HomeActionTarget.AnswerHistory -> onHistory()
        HomeActionTarget.QuestionPacks -> action.categoryId?.let(onCategory) ?: onPacks()
        HomeActionTarget.Settings -> onSettings()
        HomeActionTarget.AnswerReveal -> onReveal()
        // Resume the specific waiting game when known (B-002); fall back to the Play hub.
        HomeActionTarget.Game -> onNavigate(action.gameRoute ?: AppRoute.PLAY)
        HomeActionTarget.Challenge -> onNavigate(AppRoute.CONNECTION_CHALLENGES)
        HomeActionTarget.DatePlan -> onNavigate(AppRoute.DATE_MATCHES)
        HomeActionTarget.MemoryCapsule -> onNavigate(AppRoute.MEMORY_LANE)
    }
}

@Composable
private fun HomeContent(
    state: HomeUiState,
    snackbarHostState: SnackbarHostState,
    onNavigate: (String) -> Unit,
    onDailyQuestion: () -> Unit,
    onPacks: () -> Unit,
    onCategory: (String) -> Unit,
    onHistory: () -> Unit,
    onSettings: () -> Unit,
    onInvite: () -> Unit,
    onAcceptInvite: () -> Unit,
    onReminder: () -> Unit,
    onReveal: () -> Unit,
    onFollowUp: () -> Unit,
    onRefresh: () -> Unit,
    onPartner: () -> Unit = {}
) {
    val callbacks = remember(
        onDailyQuestion, onReminder, onReveal, onFollowUp,
        onPacks, onCategory, onHistory, onSettings, onInvite, onAcceptInvite, onRefresh
    ) {
        HomeCallbacks(
            onDailyQuestion = onDailyQuestion,
            onReminder = onReminder,
            onReveal = onReveal,
            onFollowUp = onFollowUp,
            onPacks = onPacks,
            onCategory = onCategory,
            onHistory = onHistory,
            onSettings = onSettings,
            onInvite = onInvite,
            onAcceptInvite = onAcceptInvite,
            onRefresh = onRefresh
        )
    }
    val onActionSelected = callbacks.toActionHandler(onNavigate)
    val onPendingActionSelected: (PendingActionCard) -> Unit = { card ->
        onActionSelected(
            HomeAction(
                eyebrow = "",
                title = "",
                body = "",
                cta = "",
                target = card.target,
                tone = HomeActionTone.Daily
            )
        )
    }
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(
                closerBackgroundBrush()
            )
    ) {
        SnackbarHost(
            hostState = snackbarHostState,
            modifier = Modifier
                .align(Alignment.TopCenter)
                .padding(top = 48.dp)
        )
        Column(
            modifier = Modifier
                .fillMaxSize()
                .safeDrawingPadding()
                .navigationBarsPadding()
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 20.dp, vertical = 20.dp),
            verticalArrangement = Arrangement.spacedBy(18.dp)
        ) {
            HomeHeader(
                partnerName = state.partnerName,
                streakCount = state.streakCount,
                isPaired = state.isPaired,
                unreadActivityCount = state.unreadActivityCount,
                onTogether = { onNavigate(AppRoute.ACTIVITY) }
            )

            if (state.isPaired) {
                StreakCard(
                    streakCount = state.streakCount,
                    partnerName = state.partnerName,
                    onPartner = onPartner
                )
            }

            when {
                state.isLoading -> LoadingHomeCard()
                state.error != null -> ErrorHomeCard(message = state.error, onRefresh = onRefresh)
                else -> {
                    state.pendingActions.takeIf { it.isNotEmpty() }?.let { pending ->
                        WaitingForYouSection(
                            actions = pending,
                            onAction = onPendingActionSelected
                        )
                    }

                    state.primaryAction?.let { action ->
                        if (!state.isPaired && action.target == HomeActionTarget.InvitePartner) {
                            PartnerActivationCard(
                                onInvite = callbacks.onInvite,
                                onAcceptInvite = callbacks.onAcceptInvite
                            )
                        } else {
                            PrimaryHomeActionCard(
                                action = action,
                                stats = state.answerStats,
                                streakCount = state.streakCount,
                                onAction = onActionSelected,
                                onReminder = callbacks.onReminder,
                                onReveal = callbacks.onReveal,
                                onFollowUp = callbacks.onFollowUp,
                                dailyQuestionState = state.dailyQuestionState,
                                dailyQuestion = state.dailyQuestion
                            )
                        }
                    }

                    ActionFeedSection(
                        actions = state.secondaryActions,
                        onAction = onActionSelected
                    )

                    if (state.primaryAction == null && state.secondaryActions.isEmpty()) {
                        EmptyHomeContent(
                            dailyQuestion = state.dailyQuestion,
                            onDailyQuestion = callbacks.onDailyQuestion,
                            onPacks = callbacks.onPacks
                        )
                    }

                    if (state.secondaryActions.any { it.target == HomeActionTarget.QuestionPacks } ||
                        state.primaryAction?.target != HomeActionTarget.QuestionPacks) {
                        MomentCueCard()
                    }

                    CategoryPreviewGrid(
                        categories = state.categories,
                        onCategory = onCategory,
                        onPacks = onPacks
                    )
                }
            }
        }
    }
}

@Composable
private fun StreakCard(
    streakCount: Int,
    partnerName: String?,
    onPartner: () -> Unit = {},
    modifier: Modifier = Modifier
) {
    val copy = when (streakCount) {
        0 -> "Your little ritual is waiting."
        1 -> "1 day showing up"
        else -> "$streakCount days showing up"
    }
    val partnerLine = if (streakCount > 0 && !partnerName.isNullOrBlank()) "with $partnerName" else null

    CloserCard(
        modifier = modifier.fillMaxWidth(),
        shape = RoundedCornerShape(CloserRadii.FeatureCard),
        containerColor = closerCardColor(alpha = 0.92f),
        elevation = CloserElevations.Card
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(20.dp),
            horizontalArrangement = Arrangement.spacedBy(14.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Surface(
                shape = RoundedCornerShape(CloserRadii.Tile),
                color = CloserPalette.PinkSoft.copy(alpha = 0.28f),
                modifier = Modifier.size(52.dp)
            ) {
                Box(contentAlignment = Alignment.Center) {
                    Icon(
                        imageVector = Icons.Filled.LocalFireDepartment,
                        contentDescription = null,
                        tint = CloserPalette.PinkAccentDeep,
                        modifier = Modifier.size(28.dp)
                    )
                }
            }
            Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
                if (streakCount > 0) {
                    Text(
                        text = streakCount.toString(),
                        style = MaterialTheme.typography.displaySmall.copy(fontWeight = FontWeight.SemiBold),
                        color = MaterialTheme.colorScheme.onSurface,
                        maxLines = 1
                    )
                }
                Text(
                    text = copy,
                    style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold),
                    color = if (streakCount > 0) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                partnerLine?.let {
                    Text(
                        text = it,
                        style = MaterialTheme.typography.bodyMedium,
                        color = CloserPalette.PurpleDeep,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        modifier = Modifier.clickable(onClick = onPartner)
                    )
                }
            }
        }
    }
}

@Composable
private fun HomeHeader(
    partnerName: String?,
    streakCount: Int,
    isPaired: Boolean,
    unreadActivityCount: Int = 0,
    onTogether: () -> Unit = {}
) {
    Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "For tonight",
                style = MaterialTheme.typography.headlineLarge.copy(fontWeight = FontWeight.SemiBold),
                color = MaterialTheme.colorScheme.onSurface,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier.weight(1f)
            )
            if (streakCount > 0) {
                HomePill("$streakCount nights")
            }
            // "Together" activity entry point with an unread badge.
            Box {
                Box(
                    modifier = Modifier
                        .size(40.dp)
                        .clip(RoundedCornerShape(999.dp))
                        .background(CloserPalette.PurpleSoft)
                        .clickable(onClick = onTogether),
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        Icons.Filled.Favorite,
                        contentDescription = "Together activity",
                        tint = CloserPalette.PurpleRich,
                        modifier = Modifier.size(20.dp)
                    )
                }
                if (unreadActivityCount > 0) {
                    Box(
                        modifier = Modifier
                            .align(Alignment.TopEnd)
                            .size(11.dp)
                            .clip(RoundedCornerShape(999.dp))
                            .background(CloserPalette.PinkBright)
                    )
                }
            }
        }
        Text(
            text = if (!isPaired)
                "Set up your shared space, then keep exploring at your own pace."
            else if (partnerName != null)
                "Connected with $partnerName. One clear next step, then the rest can stay quiet."
            else
                "Open the app, see what matters, and take one small step toward closeness.",
            style = MaterialTheme.typography.bodyLarge,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            maxLines = 3,
            overflow = TextOverflow.Ellipsis
        )
    }
}

@Composable
private fun PartnerActivationCard(
    onInvite: () -> Unit,
    onAcceptInvite: () -> Unit
) {
    val isDark = isCloserDarkTheme()
    val inviteTone = HomeActionTone.Invite.actionColors()
    CloserCard(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(CloserRadii.FeatureCard),
        containerColor = closerCardColor(alpha = 0.94f),
        elevation = CloserElevations.Feature
    ) {
        Column(
            modifier = Modifier
                .background(
                    Brush.linearGradient(
                        if (isDark) {
                            listOf(
                                MaterialTheme.colorScheme.surface,
                                MaterialTheme.colorScheme.surfaceVariant,
                                MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.72f)
                            )
                        } else {
                            listOf(
                                MaterialTheme.colorScheme.surface,
                                CloserPalette.PurpleSoft,
                                CloserPalette.PinkMist.copy(alpha = 0.84f)
                            )
                        },
                        start = Offset.Zero,
                        end = Offset.Infinite
                    )
                )
                .padding(20.dp),
            verticalArrangement = Arrangement.spacedBy(18.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                HomePill("1 of 2 connected")
                Surface(
                    shape = RoundedCornerShape(CloserRadii.Pill),
                    color = MaterialTheme.colorScheme.surface.copy(alpha = 0.76f)
                ) {
                    Row(
                        modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
                        horizontalArrangement = Arrangement.spacedBy(5.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Filled.Lock,
                            contentDescription = null,
                            tint = inviteTone.deep,
                            modifier = Modifier.size(14.dp)
                        )
                        Text(
                            text = "Private invite",
                            style = MaterialTheme.typography.labelSmall,
                            color = inviteTone.deep,
                            fontWeight = FontWeight.SemiBold,
                            textAlign = TextAlign.Center,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                        )
                    }
                }
            }

            Image(
                painter = painterResource(R.drawable.illustration_partner_activation),
                contentDescription = null,
                contentScale = ContentScale.Crop,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(142.dp)
                    .clip(RoundedCornerShape(22.dp))
            )

            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                Text(
                    text = "A private space for two",
                    style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.SemiBold),
                    color = MaterialTheme.colorScheme.onSurface,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
                Text(
                    text = "Invite your partner to unlock shared reveals, games, streaks, and answers you can both respond to.",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 4,
                    overflow = TextOverflow.Ellipsis
                )
            }

            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                ActivationBenefitPill("Private reveals", Modifier.weight(1f))
                ActivationBenefitPill("Shared streak", Modifier.weight(1f))
                ActivationBenefitPill("Games for two", Modifier.weight(1f))
            }

            Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
                CloserActionButton(
                    label = "Invite partner",
                    onClick = onInvite,
                    modifier = Modifier.fillMaxWidth(),
                    containerColor = inviteTone.accent,
                    contentColor = inviteTone.onAccent
                )
                CloserActionButton(
                    label = "Enter code",
                    onClick = onAcceptInvite,
                    modifier = Modifier.fillMaxWidth(),
                    style = CloserButtonStyle.Secondary,
                    containerColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.7f),
                    contentColor = inviteTone.deep
                )
            }
        }
    }
}

@Composable
private fun ActivationBenefitPill(
    label: String,
    modifier: Modifier = Modifier
) {
    val colors = HomeActionTone.Invite.actionColors()
    Surface(
        modifier = modifier,
        shape = RoundedCornerShape(CloserRadii.Pill),
        color = MaterialTheme.colorScheme.surface.copy(alpha = 0.66f)
    ) {
        Text(
            text = label,
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 9.dp, vertical = 7.dp),
            style = MaterialTheme.typography.labelSmall,
            color = colors.deep,
            fontWeight = FontWeight.SemiBold,
            textAlign = TextAlign.Center,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }
}

@Composable
private fun PrimaryHomeActionCard(
    action: HomeAction,
    stats: HomeAnswerStats,
    streakCount: Int,
    onAction: (HomeAction) -> Unit,
    onReminder: () -> Unit,
    onReveal: () -> Unit,
    onFollowUp: () -> Unit,
    dailyQuestionState: DailyQuestionState,
    dailyQuestion: Question?
) {
    val colors = action.tone.actionColors()
    val isDark = isCloserDarkTheme()
    val showTonightPartnerArt = action.target == HomeActionTarget.DailyQuestion &&
        (dailyQuestionState == DailyQuestionState.UNANSWERED ||
            dailyQuestionState == DailyQuestionState.PARTNER_ANSWERED_USER_PENDING)

    // For daily-question actions, route the CTA through the explicit state handlers
    // so the same button label maps to the correct next step (answer, remind,
    // reveal, or follow-up) even if the action target is still DailyQuestion.
    val ctaClick = when (action.target) {
        HomeActionTarget.DailyQuestion -> when (dailyQuestionState) {
            DailyQuestionState.USER_ANSWERED_PARTNER_PENDING -> onReminder
            DailyQuestionState.BOTH_ANSWERED -> onReveal
            DailyQuestionState.REVEALED -> onFollowUp
            else -> { { onAction(action) } }
        }
        else -> { { onAction(action) } }
    }

    val titleOverride = when (action.target) {
        HomeActionTarget.DailyQuestion -> when (dailyQuestionState) {
            DailyQuestionState.UNANSWERED -> "Tonight's question is ready."
            DailyQuestionState.USER_ANSWERED_PARTNER_PENDING -> "You showed up tonight. Waiting for your partner."
            DailyQuestionState.PARTNER_ANSWERED_USER_PENDING -> "Your partner answered. Your turn."
            DailyQuestionState.BOTH_ANSWERED -> "Reveal is ready."
            DailyQuestionState.REVEALED -> "You opened a conversation tonight."
        }
        else -> action.title
    }

    val bodyOverride = when (action.target) {
        HomeActionTarget.DailyQuestion -> when (dailyQuestionState) {
            DailyQuestionState.UNANSWERED ->
                dailyQuestion?.text ?: "Answer tonight's question privately, then choose when to share."
            DailyQuestionState.USER_ANSWERED_PARTNER_PENDING ->
                "Your answer is private until they answer too. No pressure — the reveal waits for both of you."
            DailyQuestionState.PARTNER_ANSWERED_USER_PENDING ->
                "Answer to unlock the reveal. Your response stays private until you are ready."
            DailyQuestionState.BOTH_ANSWERED ->
                "Both of you answered. Open it together when you are both in the right headspace."
            DailyQuestionState.REVEALED ->
                "You revealed an answer together. What comes next is up to both of you."
        }
        else -> action.body
    }

    val timeBudgetLabel = when (action.target) {
        HomeActionTarget.DailyQuestion -> when (dailyQuestion?.type) {
            "scale" -> "~1 min"
            "single_choice" -> "~2 min"
            "this_or_that" -> "~2 min"
            else -> "~3 min"
        }
        else -> null
    }

    CloserCard(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(CloserRadii.FeatureCard),
        containerColor = closerCardColor(alpha = 0.92f),
        elevation = CloserElevations.Feature
    ) {
        Column(
            modifier = Modifier
                .background(
                    Brush.linearGradient(
                        if (isDark) {
                            listOf(
                                MaterialTheme.colorScheme.surface,
                                MaterialTheme.colorScheme.surfaceVariant,
                                colors.soft.copy(alpha = 0.72f)
                            )
                        } else {
                            listOf(
                                MaterialTheme.colorScheme.surface,
                                colors.soft,
                                CloserPalette.PinkMist.copy(alpha = 0.72f)
                            )
                        },
                        start = Offset.Zero,
                        end = Offset.Infinite
                    )
                )
                .padding(20.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                HomePill(action.eyebrow)
                Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
                    timeBudgetLabel?.let { label ->
                        HomePill(label)
                    }
                    action.metric?.let { HomePill(it) }
                }
            }

            if (showTonightPartnerArt) {
                Image(
                    painter = painterResource(R.drawable.illustration_tonight_partner_prompt),
                    contentDescription = null,
                    contentScale = ContentScale.Crop,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(148.dp)
                        .clip(RoundedCornerShape(22.dp))
                )
            }

            if (action.target == HomeActionTarget.DailyQuestion && !showTonightPartnerArt) {
                Text(
                    text = "Got 5 min?",
                    style = MaterialTheme.typography.labelSmall.copy(fontWeight = FontWeight.SemiBold),
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }

            if (showTonightPartnerArt) {
                Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    Text(
                        text = titleOverride,
                        style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.SemiBold),
                        color = MaterialTheme.colorScheme.onSurface,
                        maxLines = 3,
                        overflow = TextOverflow.Ellipsis
                    )
                    Text(
                        text = bodyOverride,
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        maxLines = 4,
                        overflow = TextOverflow.Ellipsis
                    )
                }
            } else {
                Row(
                    horizontalArrangement = Arrangement.spacedBy(14.dp),
                    verticalAlignment = Alignment.Top
                ) {
                    Surface(
                        shape = RoundedCornerShape(CloserRadii.Tile),
                        color = colors.accent.copy(alpha = 0.16f),
                        modifier = Modifier.size(52.dp)
                    ) {
                        Box(contentAlignment = Alignment.Center) {
                            Icon(
                                imageVector = Icons.Filled.Favorite,
                                contentDescription = null,
                                tint = colors.deep,
                                modifier = Modifier.size(26.dp)
                            )
                        }
                    }

                    Column(
                        modifier = Modifier.weight(1f),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Text(
                            text = titleOverride,
                            style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.SemiBold),
                            color = MaterialTheme.colorScheme.onSurface,
                            maxLines = 3,
                            overflow = TextOverflow.Ellipsis
                        )
                        Text(
                            text = bodyOverride,
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            maxLines = 4,
                            overflow = TextOverflow.Ellipsis
                        )
                    }
                }
            }

            HomePulseStrip(stats = stats, streakCount = streakCount)

            CloserActionButton(
                label = action.cta,
                onClick = ctaClick,
                modifier = Modifier.fillMaxWidth(),
                containerColor = colors.accent,
                contentColor = colors.onAccent
            )
        }
    }
}

@Composable
private fun HomePulseStrip(
    stats: HomeAnswerStats,
    streakCount: Int
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(10.dp)
    ) {
        PulseMetric(
            label = "Saved",
            value = stats.total.toString(),
            modifier = Modifier.weight(1f)
        )
        PulseMetric(
            label = "Private",
            value = stats.private.toString(),
            modifier = Modifier.weight(1f)
        )
        PulseMetric(
            label = "Nights",
            value = streakCount.toString(),
            modifier = Modifier.weight(1f)
        )
    }
}

@Composable
private fun PulseMetric(
    label: String,
    value: String,
    modifier: Modifier = Modifier
) {
    Surface(
        modifier = modifier,
        shape = RoundedCornerShape(CloserRadii.Tile),
        color = MaterialTheme.colorScheme.surface.copy(alpha = 0.66f)
    ) {
        Column(
            modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
            verticalArrangement = Arrangement.spacedBy(2.dp)
        ) {
            Text(
                text = value,
                style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold),
                color = MaterialTheme.colorScheme.primary,
                maxLines = 1
            )
            Text(
                text = label,
                style = MaterialTheme.typography.labelMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}

@Composable
private fun ActionFeedSection(
    actions: List<HomeAction>,
    onAction: (HomeAction) -> Unit
) {
    if (actions.isEmpty()) return

    Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
        Text(
            text = "After that",
            style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold),
            color = MaterialTheme.colorScheme.onSurface
        )
        actions.forEach { action ->
            SecondaryHomeActionCard(action = action, onAction = onAction)
        }
    }
}

@Composable
private fun SecondaryHomeActionCard(
    action: HomeAction,
    onAction: (HomeAction) -> Unit
) {
    val colors = action.tone.actionColors()

    CloserClickableCard(
        onClick = { onAction(action) },
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(CloserRadii.Card),
        containerColor = MaterialTheme.colorScheme.surface,
        elevation = CloserElevations.Card
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.spacedBy(13.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .background(colors.soft, RoundedCornerShape(CloserRadii.Button)),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    imageVector = Icons.Filled.Favorite,
                    contentDescription = null,
                    tint = colors.deep,
                    modifier = Modifier.size(20.dp)
                )
            }
            Column(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                Text(
                    text = action.eyebrow,
                    style = MaterialTheme.typography.labelMedium,
                    color = colors.deep,
                    fontWeight = FontWeight.SemiBold,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                Text(
                    text = action.title,
                    style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.SemiBold),
                    color = MaterialTheme.colorScheme.onSurface,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                Text(
                    text = action.body,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
            }
            Surface(
                shape = RoundedCornerShape(CloserRadii.Button),
                color = colors.soft
            ) {
                Icon(
                    imageVector = Icons.AutoMirrored.Filled.ArrowForward,
                    contentDescription = action.cta,
                    tint = colors.deep,
                    modifier = Modifier
                        .padding(9.dp)
                        .size(18.dp)
                )
            }
        }
    }
}

@Composable
private fun MomentCueCard() {
    val isDark = isCloserDarkTheme()
    CloserCard(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(CloserRadii.Card),
        containerColor = if (isDark) {
            MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.58f)
        } else {
            CloserPalette.PinkMist.copy(alpha = 0.7f)
        },
        elevation = CloserElevations.Flat
    ) {
        Column(
            modifier = Modifier.padding(17.dp),
            verticalArrangement = Arrangement.spacedBy(7.dp)
        ) {
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                HomePill("Special dates")
                HomePill("Quiet reminder")
            }
            Text(
                text = "Keep important days close without turning them into chores.",
                style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.SemiBold),
                color = MaterialTheme.colorScheme.onSurface
            )
            Text(
                text = "Birthdays, anniversaries, and planned moments will sit here as gentle cues once they are saved.",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}

private data class HomeActionColors(
    val soft: Color,
    val accent: Color,
    val deep: Color,
    val onAccent: Color
)

@Composable
private fun HomeActionTone.actionColors(): HomeActionColors {
    val scheme = MaterialTheme.colorScheme
    if (isCloserDarkTheme()) {
        return when (this) {
            HomeActionTone.Daily,
            HomeActionTone.Ritual,
            HomeActionTone.Starter,
            HomeActionTone.Pack -> HomeActionColors(
                soft = scheme.secondaryContainer,
                accent = scheme.secondary,
                deep = scheme.secondary,
                onAccent = scheme.onSecondary
            )
            HomeActionTone.Reflection -> HomeActionColors(
                soft = scheme.tertiaryContainer,
                accent = scheme.tertiary,
                deep = scheme.tertiary,
                onAccent = scheme.onTertiary
            )
            else -> HomeActionColors(
                soft = scheme.primaryContainer,
                accent = scheme.primary,
                deep = scheme.primary,
                onAccent = scheme.onPrimary
            )
        }
    }

    return when (this) {
        HomeActionTone.Invite -> HomeActionColors(
            soft = CloserPalette.PurpleSoft,
            accent = MaterialTheme.colorScheme.primary,
            deep = CloserPalette.PurpleDeep,
            onAccent = MaterialTheme.colorScheme.onPrimary
        )
        HomeActionTone.Daily -> HomeActionColors(
            soft = CloserPalette.PinkSoft,
            accent = CloserPalette.PinkBright,
            deep = CloserPalette.PinkAccentDeep,
            onAccent = Color(0xFF24122F)
        )
        HomeActionTone.Reflection -> HomeActionColors(
            soft = CloserPalette.PurpleGlow,
            accent = CloserPalette.PurpleRich,
            deep = CloserPalette.PurpleDeep,
            onAccent = Color(0xFF24122F)
        )
        HomeActionTone.Ritual -> HomeActionColors(
            soft = CloserPalette.PurpleSoft,
            accent = CloserPalette.PinkBright,
            deep = CloserPalette.PinkAccentDeep,
            onAccent = Color(0xFF24122F)
        )
        HomeActionTone.Starter -> HomeActionColors(
            soft = CloserPalette.PinkSoft,
            accent = CloserPalette.PinkBright,
            deep = CloserPalette.PinkAccentDeep,
            onAccent = Color(0xFF24122F)
        )
        HomeActionTone.Pack -> HomeActionColors(
            soft = CloserPalette.PinkSoft,
            accent = CloserPalette.PinkBright,
            deep = CloserPalette.PinkAccentDeep,
            onAccent = Color(0xFF24122F)
        )
        HomeActionTone.Utility -> HomeActionColors(
            soft = CloserPalette.PurpleSoft,
            accent = MaterialTheme.colorScheme.primary,
            deep = CloserPalette.PurpleDeep,
            onAccent = MaterialTheme.colorScheme.onPrimary
        )
        HomeActionTone.Pending -> HomeActionColors(
            soft = CloserPalette.PurpleSoft,
            accent = MaterialTheme.colorScheme.primary,
            deep = CloserPalette.PurpleDeep,
            onAccent = MaterialTheme.colorScheme.onPrimary
        )
    }
}

@Composable
private fun CategoryPreviewGrid(
    categories: List<HomeCategorySummary>,
    onCategory: (String) -> Unit,
    onPacks: () -> Unit
) {
    val featuredCategories = categories.take(2)
    if (featuredCategories.isEmpty()) return

    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "More doorways",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.onSurface,
                fontWeight = FontWeight.SemiBold
            )
            CloserActionButton(
                label = "All packs",
                onClick = onPacks,
                style = CloserButtonStyle.Secondary
            )
        }

        featuredCategories.chunked(2).forEach { rowItems ->
            Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                rowItems.forEach { item ->
                    CategoryMiniCard(
                        item = item,
                        modifier = Modifier.weight(1f),
                        onClick = { onCategory(item.category.id) }
                    )
                }
                if (rowItems.size == 1) {
                    Box(modifier = Modifier.weight(1f))
                }
            }
        }
    }
}

@Composable
private fun CategoryMiniCard(
    item: HomeCategorySummary,
    modifier: Modifier,
    onClick: () -> Unit
) {
    CloserClickableCard(
        onClick = onClick,
        modifier = modifier,
        containerColor = closerCardColor(alpha = 0.82f),
        shape = RoundedCornerShape(CloserRadii.Card),
        elevation = CloserElevations.Card
    ) {
        Column(
            modifier = Modifier.padding(15.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            CategoryGlyph(
                categoryId = item.category.id,
                iconName = item.category.iconName,
                size = 42.dp,
                iconSize = 20.dp
            )
            Text(
                text = item.category.displayName.ifBlank { item.category.id.displayCategoryName() },
                style = MaterialTheme.typography.titleSmall,
                color = MaterialTheme.colorScheme.onSurface,
                fontWeight = FontWeight.SemiBold,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = "${item.questionCount} prompts",
                style = MaterialTheme.typography.labelMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}

@Composable
private fun WaitingForYouSection(
    actions: List<PendingActionCard>,
    onAction: (PendingActionCard) -> Unit
) {
    Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
        Text(
            text = "Waiting for you",
            style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold),
            color = MaterialTheme.colorScheme.onSurface
        )
        actions.take(3).forEach { card ->
            PendingActionCardView(card = card, onClick = { onAction(card) })
        }
    }
}

@Composable
private fun PendingActionCardView(
    card: PendingActionCard,
    onClick: () -> Unit
) {
    val colors = HomeActionTone.Pending.actionColors()

    CloserClickableCard(
        onClick = onClick,
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(CloserRadii.Card),
        containerColor = MaterialTheme.colorScheme.surface,
        elevation = CloserElevations.Card
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.spacedBy(13.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .background(colors.soft, RoundedCornerShape(CloserRadii.Button)),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    imageVector = Icons.Filled.Favorite,
                    contentDescription = null,
                    tint = colors.deep,
                    modifier = Modifier.size(20.dp)
                )
            }
            Column(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(2.dp)
            ) {
                Text(
                    text = card.title,
                    style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.SemiBold),
                    color = MaterialTheme.colorScheme.onSurface,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                card.subtitle?.let { subtitle ->
                    Text(
                        text = subtitle,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        maxLines = 2,
                        overflow = TextOverflow.Ellipsis
                    )
                }
            }
            Icon(
                imageVector = Icons.AutoMirrored.Filled.ArrowForward,
                contentDescription = "Open",
                tint = colors.deep,
                modifier = Modifier.size(20.dp)
            )
        }
    }
}

@Composable
private fun LoadingHomeCard() {
    LoadingState(message = "Opening your dashboard")
}

@Composable
private fun ErrorHomeCard(
    message: String,
    onRefresh: () -> Unit
) {
    ErrorState(
        title = "Home paused",
        message = message,
        retryLabel = "Retry",
        onRetry = onRefresh
    )
}

@Composable
private fun EmptyHomeContent(
    dailyQuestion: Question?,
    onDailyQuestion: () -> Unit,
    onPacks: () -> Unit
) {
    Column(
        modifier = Modifier.fillMaxWidth(),
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        CloserCard(
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(CloserRadii.Card),
            containerColor = closerCardColor(alpha = 0.82f),
            elevation = CloserElevations.Card
        ) {
            Column(
                modifier = Modifier.padding(18.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Text(
                    text = "You're all caught up",
                    style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold),
                    color = MaterialTheme.colorScheme.onSurface
                )
                Text(
                    text = "Nothing needs your attention right now. Come back later or explore a pack together.",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                CloserActionButton(
                    label = "Browse packs",
                    onClick = onPacks,
                    style = CloserButtonStyle.Secondary
                )
            }
        }
    }
}

@Composable
private fun HomePill(label: String) {
    CloserPill(
        label = label,
        containerColor = if (isCloserDarkTheme()) {
            MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.78f)
        } else {
            CloserPalette.PinkMist.copy(alpha = 0.72f)
        },
        contentColor = MaterialTheme.colorScheme.onSurface
    )
}

@Preview
@Composable
fun HomeScreenPreview() {
    HomeContent(
        state = HomeUiState(
            isLoading = false,
            dailyQuestion = Question(
                id = "demo",
                text = "What is one tiny thing that would help us feel close tonight?",
                category = "emotional_intimacy",
                depthLevel = 2
            ),
            answerStats = HomeAnswerStats(total = 4, revealed = 2, private = 2),
            partnerName = "Jordan",
            streakCount = 7,
            categories = listOf(
                HomeCategorySummary(
                    category = QuestionCategory(
                        id = "communication",
                        displayName = "Communication",
                        description = "",
                        access = "mixed",
                        iconName = "chat"
                    ),
                    questionCount = 250
                ),
                HomeCategorySummary(
                    category = QuestionCategory(
                        id = "trust",
                        displayName = "Trust",
                        description = "",
                        access = "mixed",
                        iconName = "heart"
                    ),
                    questionCount = 250
                )
            )
        ),
        snackbarHostState = remember { SnackbarHostState() },
        onNavigate = {},
        onDailyQuestion = {},
        onReminder = {},
        onReveal = {},
        onFollowUp = {},
        onPacks = {},
        onCategory = {},
        onHistory = {},
        onSettings = {},
        onInvite = {},
        onAcceptInvite = {},
        onRefresh = {}
    )
}

/**
 * Debug-only: renders the paired Home from mock state so the paired experience can be viewed
 * without actually pairing two devices. No data sources, no Firestore — pure UI preview.
 * Reachable from Settings → "Paired home (debug)" in debug builds only.
 */
@Composable
fun PairedHomePreviewScreen(onNavigate: (String) -> Unit = {}) {
    val demoState = HomeUiState(
        isLoading = false,
        isPaired = true,
        coupleId = "demo",
        partnerName = "Sofia",
        streakCount = 12,
        unreadActivityCount = 2,
        dailyQuestion = Question(
            id = "demo",
            text = "What's something I did recently that made you feel loved?",
            category = "emotional_intimacy",
            depthLevel = 2
        ),
        dailyQuestionState = DailyQuestionState.PARTNER_ANSWERED_USER_PENDING,
        hasPartnerAnsweredToday = true,
        partnerAnsweredQuestionId = "demo",
        answerStats = HomeAnswerStats(total = 24, revealed = 18, private = 6),
        primaryAction = HomeAction(
            eyebrow = "Tonight",
            title = "Sofia answered. Your turn.",
            body = "She shared what's on her heart tonight — open the question and answer back.",
            cta = "Answer now",
            target = HomeActionTarget.DailyQuestion,
            tone = HomeActionTone.Daily
        ),
        secondaryActions = listOf(
            HomeAction(
                eyebrow = "Keep playing",
                title = "Question packs",
                body = "Fresh prompts for the two of you.",
                cta = "Browse packs",
                target = HomeActionTarget.QuestionPacks,
                tone = HomeActionTone.Pack
            ),
            HomeAction(
                eyebrow = "Look back",
                title = "Your answers",
                body = "Revisit the moments you've shared.",
                cta = "Open history",
                target = HomeActionTarget.AnswerHistory,
                tone = HomeActionTone.Reflection
            )
        ),
        pendingActions = listOf(
            PendingActionCard(
                title = "Sofia is waiting to play",
                subtitle = "A game is ready for you both",
                priority = 1,
                target = HomeActionTarget.Game
            )
        ),
        categories = listOf(
            HomeCategorySummary(
                category = QuestionCategory(
                    id = "communication", displayName = "Communication",
                    description = "", access = "mixed", iconName = "chat"
                ),
                questionCount = 250
            ),
            HomeCategorySummary(
                category = QuestionCategory(
                    id = "trust", displayName = "Trust",
                    description = "", access = "mixed", iconName = "heart"
                ),
                questionCount = 250
            ),
            HomeCategorySummary(
                category = QuestionCategory(
                    id = "intimacy", displayName = "Intimacy",
                    description = "", access = "mixed", iconName = "heart"
                ),
                questionCount = 180
            )
        )
    )
    Box(modifier = Modifier.fillMaxSize()) {
        HomeContent(
            state = demoState,
            snackbarHostState = remember { SnackbarHostState() },
            onNavigate = onNavigate,
            onDailyQuestion = {}, onPacks = {}, onCategory = {}, onHistory = {},
            onSettings = {}, onInvite = {}, onAcceptInvite = {}, onReminder = {},
            onReveal = {}, onFollowUp = {}, onRefresh = {}, onPartner = {}
        )
    }
}

@Composable
internal fun StreakMilestoneDialog(
    milestone: Int,
    partnerName: String?,
    onDismiss: () -> Unit
) {
    Dialog(onDismissRequest = onDismiss) {
        Box(contentAlignment = Alignment.Center) {
            Surface(
                shape = RoundedCornerShape(28.dp),
                color = SettingsSoft,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 24.dp)
            ) {
                Column(
                    modifier = Modifier.padding(horizontal = 28.dp, vertical = 30.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Image(
                        painter = painterResource(R.drawable.illustration_streak_milestone),
                        contentDescription = null,
                        modifier = Modifier.size(156.dp)
                    )
                    Spacer(Modifier.height(18.dp))
                    Text(
                        text = "$milestone nights together",
                        style = MaterialTheme.typography.headlineSmall,
                        fontWeight = FontWeight.SemiBold,
                        color = SettingsInk,
                        textAlign = TextAlign.Center
                    )
                    Spacer(Modifier.height(8.dp))
                    Text(
                        text = partnerName?.takeIf { it.isNotBlank() }
                            ?.let { "You and $it keep showing up for each other — $milestone nights running. The small moments are adding up to something." }
                            ?: "You keep showing up — $milestone nights running. The small moments are adding up to something.",
                        style = MaterialTheme.typography.bodyMedium,
                        color = SettingsMuted,
                        textAlign = TextAlign.Center
                    )
                    Spacer(Modifier.height(24.dp))
                    CloserActionButton(
                        label = "Keep going together",
                        onClick = onDismiss,
                        modifier = Modifier.fillMaxWidth()
                    )
                }
            }
            CelebrationOverlay(visible = true, intensity = 1.4f)
        }
    }
}
