package app.closer.ui.challenges

import android.util.Log
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.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
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.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.TextButton
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import app.closer.ui.components.CloserHeartLoader
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
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.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.closer.core.billing.CouplePremiumChecker
import app.closer.core.navigation.AppRoute
import app.closer.data.challenges.ChallengesCatalog
import app.closer.data.remote.FirestoreChallengeDataSource
import app.closer.domain.ChallengeStateMachine
import app.closer.domain.model.ChallengeProgressState
import app.closer.domain.model.ChallengeState
import app.closer.domain.model.ChallengeStateInput
import app.closer.domain.model.ChallengeStatus
import app.closer.domain.model.ConnectionChallenge
import app.closer.domain.repository.AuthRepository
import app.closer.domain.repository.CoupleRepository
import java.time.LocalDate
import app.closer.ui.theme.CloserPalette
import app.closer.ui.theme.closerBackgroundBrush
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

// ── ViewModel ─────────────────────────────────────────────────────────────────

enum class ChallengesPhase { LOADING, PICK, ACTIVE }

data class ChallengesUiState(
    val phase: ChallengesPhase = ChallengesPhase.LOADING,
    val activeChallenge: ConnectionChallenge? = null,
    val progress: ChallengeProgressState? = null,
    val challengeState: ChallengeState? = null,
    val coupleId: String? = null,
    val userId: String? = null,
    val partnerId: String? = null,
    val hasPremium: Boolean = false,
    val error: String? = null,
    val navigateTo: String? = null,
    val showAbandonConfirm: Boolean = false
)

@HiltViewModel
class ConnectionChallengesViewModel @Inject constructor(
    private val authRepository: AuthRepository,
    private val coupleRepository: CoupleRepository,
    private val challengeDataSource: FirestoreChallengeDataSource,
    private val premiumChecker: CouplePremiumChecker
) : ViewModel() {

    private val _uiState = MutableStateFlow(ChallengesUiState())
    val uiState: StateFlow<ChallengesUiState> = _uiState.asStateFlow()

    private var progressJob: Job? = null

    init {
        premiumChecker.isPremium()
            .onEach { premium -> _uiState.update { it.copy(hasPremium = premium) } }
            .launchIn(viewModelScope)
        load()
    }

    private fun load() {
        viewModelScope.launch {
            val uid = authRepository.currentUserId ?: run {
                _uiState.update { it.copy(navigateTo = AppRoute.PLAY) }
                return@launch
            }
            val couple = coupleRepository.getCoupleForUser(uid) ?: run {
                _uiState.update { it.copy(navigateTo = AppRoute.CREATE_INVITE) }
                return@launch
            }
            val partnerId = couple.userIds.firstOrNull { it != uid } ?: uid

            val activeChallengeId = runCatching {
                challengeDataSource.getActiveChallengeId(couple.id)
            }.getOrNull()

            if (activeChallengeId != null) {
                val challenge = ChallengesCatalog.findById(activeChallengeId)
                if (challenge != null) {
                    observeChallenge(couple.id, uid, partnerId, challenge)
                    return@launch
                }
            }

            _uiState.update {
                it.copy(
                    phase = ChallengesPhase.PICK,
                    coupleId = couple.id,
                    userId = uid,
                    partnerId = partnerId
                )
            }
        }
    }

    private fun observeChallenge(
        coupleId: String,
        userId: String,
        partnerId: String,
        challenge: ConnectionChallenge
    ) {
        progressJob?.cancel()
        progressJob = viewModelScope.launch {
            challengeDataSource.observeProgress(coupleId, challenge.id, userId, partnerId)
                .collect { progress ->
                    val state = ChallengeStateMachine.compute(
                        ChallengeStateInput(
                            challenge = challenge,
                            progress = progress,
                            today = LocalDate.now()
                        )
                    )
                    _uiState.update {
                        it.copy(
                            phase = ChallengesPhase.ACTIVE,
                            coupleId = coupleId,
                            userId = userId,
                            partnerId = partnerId,
                            activeChallenge = challenge,
                            progress = progress,
                            challengeState = state
                        )
                    }
                    if (state.isComplete && progress.status == "active") {
                        runCatching { challengeDataSource.finishChallenge(coupleId, challenge.id) }
                    }
                }
        }
    }

    fun startChallenge(challenge: ConnectionChallenge) {
        val state = _uiState.value
        val coupleId = state.coupleId ?: run {
            _uiState.update { it.copy(error = "Something went wrong. Go back and try again.") }
            return
        }
        val userId = state.userId ?: run {
            _uiState.update { it.copy(error = "Something went wrong. Go back and try again.") }
            return
        }
        val partnerId = state.partnerId ?: userId
        viewModelScope.launch {
            runCatching { challengeDataSource.startChallenge(coupleId, challenge.id) }
                .onSuccess { observeChallenge(coupleId, userId, partnerId, challenge) }
                .onFailure {
                    Log.w(TAG, "Could not start challenge", it)
                    _uiState.update { s -> s.copy(error = "Could not start challenge. Try again.") }
                }
        }
    }

    fun markTodayComplete() {
        val state = _uiState.value
        val coupleId = state.coupleId ?: return
        val userId = state.userId ?: return
        val progress = state.progress ?: return
        val challenge = state.activeChallenge ?: return
        val day = progress.myNextDay
        if (day > challenge.durationDays) return
        viewModelScope.launch {
            runCatching { challengeDataSource.markDayComplete(coupleId, challenge.id, userId, day) }
                .onFailure { e ->
                    Log.w(TAG, "Could not mark day $day complete", e)
                    _uiState.update { s -> s.copy(error = "Couldn't save your progress. Check your connection and try again.") }
                }
        }
    }

    fun dismissError() = _uiState.update { it.copy(error = null) }

    fun showAbandonConfirm() = _uiState.update { it.copy(showAbandonConfirm = true) }
    fun dismissAbandonConfirm() = _uiState.update { it.copy(showAbandonConfirm = false) }

    fun abandonChallenge() {
        val state = _uiState.value
        val coupleId = state.coupleId ?: return
        val challengeId = state.activeChallenge?.id ?: return
        _uiState.update { it.copy(showAbandonConfirm = false) }
        progressJob?.cancel()
        viewModelScope.launch {
            runCatching { challengeDataSource.abandonChallenge(coupleId, challengeId) }
                .onSuccess {
                    _uiState.update { it.copy(
                        phase = ChallengesPhase.PICK,
                        activeChallenge = null,
                        progress = null,
                        challengeState = null
                    ) }
                }
                .onFailure { e ->
                    Log.w(TAG, "Could not abandon challenge", e)
                    _uiState.update { s -> s.copy(error = "Could not stop the challenge. Try again.") }
                }
        }
    }

    fun onNavigated() = _uiState.update { it.copy(navigateTo = null) }

    companion object {
        private const val TAG = "ChallengesViewModel"
    }
}

// ── Screen ────────────────────────────────────────────────────────────────────

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

    LaunchedEffect(state.navigateTo) {
        state.navigateTo?.let { onNavigate(it); viewModel.onNavigated() }
    }
    LaunchedEffect(state.error) {
        state.error?.let {
            snackbarHostState.showSnackbar(it)
            viewModel.dismissError()
        }
    }

    Scaffold(
        snackbarHost = { SnackbarHost(snackbarHostState) },
        containerColor = Color.Transparent
    ) { padding ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .background(closerBackgroundBrush())
        ) {
            when (state.phase) {
                ChallengesPhase.LOADING -> ChallengesLoadingScreen()
                ChallengesPhase.PICK -> ChallengesPickScreen(
                    hasPremium = state.hasPremium,
                    onBack = { onNavigate(AppRoute.PLAY) },
                    onPick = { viewModel.startChallenge(it) },
                    onPaywall = { onNavigate(AppRoute.PAYWALL) }
                )
                ChallengesPhase.ACTIVE -> {
                    val activeChallenge = state.activeChallenge
                    if (activeChallenge == null) {
                        ChallengesLoadingScreen()
                    } else ChallengesActiveScreen(
                    challenge = activeChallenge,
                    progress = state.progress ?: ChallengeProgressState(),
                    challengeState = state.challengeState,
                    onBack = { onNavigate(AppRoute.PLAY) },
                    onMarkComplete = { viewModel.markTodayComplete() },
                    onViewHistory = { onNavigate(AppRoute.GAME_HISTORY) },
                    showAbandonConfirm = state.showAbandonConfirm,
                    onRequestAbandon = { viewModel.showAbandonConfirm() },
                    onConfirmAbandon = { viewModel.abandonChallenge() },
                    onDismissAbandon = { viewModel.dismissAbandonConfirm() }
                )
                }
            }
        }
    }
}

// ── Loading ───────────────────────────────────────────────────────────────────

@Composable
private fun ChallengesLoadingScreen() {
    Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        CloserHeartLoader()
    }
}

// ── Pick ──────────────────────────────────────────────────────────────────────

@Composable
private fun ChallengesPickScreen(
    hasPremium: Boolean,
    onBack: () -> Unit,
    onPick: (ConnectionChallenge) -> Unit,
    onPaywall: () -> Unit
) {
    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .safeDrawingPadding()
            .navigationBarsPadding(),
        contentPadding = PaddingValues(horizontal = 20.dp, vertical = 16.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        item {
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                IconButton(onClick = onBack) {
                    Icon(
                        Icons.AutoMirrored.Filled.ArrowBack,
                        contentDescription = "Back",
                        tint = MaterialTheme.colorScheme.onBackground
                    )
                }
                Spacer(Modifier.width(4.dp))
                Column {
                    Text(
                        text = "Connection Challenges",
                        style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.SemiBold),
                        color = MaterialTheme.colorScheme.onBackground
                    )
                    Text(
                        text = "Pick a series to build a habit together.",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
        }

        items(ChallengesCatalog.all) { challenge ->
            ChallengePickCard(challenge = challenge, hasPremium = hasPremium, onPick = onPick, onPaywall = onPaywall)
        }

        item { Spacer(Modifier.height(8.dp)) }
    }
}

@Composable
private fun ChallengePickCard(
    challenge: ConnectionChallenge,
    hasPremium: Boolean,
    onPick: (ConnectionChallenge) -> Unit,
    onPaywall: () -> Unit
) {
    Card(
        onClick = { if (challenge.isPremium && !hasPremium) onPaywall() else onPick(challenge) },
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(20.dp),
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.spacedBy(14.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Surface(
                shape = RoundedCornerShape(16.dp),
                color = CloserPalette.PurpleDeep.copy(alpha = 0.10f),
                modifier = Modifier.size(52.dp)
            ) {
                Box(contentAlignment = Alignment.Center) {
                    Text(
                        text = challenge.emoji,
                        style = MaterialTheme.typography.headlineSmall
                    )
                }
            }

            Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = challenge.title,
                        style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold),
                        color = MaterialTheme.colorScheme.onSurface,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        modifier = Modifier.weight(1f)
                    )
                    Spacer(Modifier.width(8.dp))
                    if (challenge.isPremium) {
                        Surface(
                            shape = RoundedCornerShape(999.dp),
                            color = CloserPalette.Gold.copy(alpha = 0.15f)
                        ) {
                            Row(
                                modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp),
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.spacedBy(3.dp)
                            ) {
                                Icon(Icons.Filled.Lock, contentDescription = null, tint = CloserPalette.Gold, modifier = Modifier.size(10.dp))
                                Text("Premium", style = MaterialTheme.typography.labelSmall, color = CloserPalette.Gold, fontWeight = FontWeight.SemiBold)
                            }
                        }
                    } else {
                        Surface(
                            shape = RoundedCornerShape(999.dp),
                            color = CloserPalette.PurpleDeep.copy(alpha = 0.10f)
                        ) {
                            Text(
                                text = "${challenge.durationDays} days",
                                modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp),
                                style = MaterialTheme.typography.labelSmall,
                                color = CloserPalette.PurpleDeep,
                                fontWeight = FontWeight.SemiBold
                            )
                        }
                    }
                }
                Text(
                    text = challenge.description,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
                Text(
                    text = challenge.category,
                    style = MaterialTheme.typography.labelSmall,
                    color = CloserPalette.PurpleDeep.copy(alpha = 0.7f)
                )
            }
        }
    }
}

// ── Active ────────────────────────────────────────────────────────────────────

@Composable
private fun ChallengesActiveScreen(
    challenge: ConnectionChallenge,
    progress: ChallengeProgressState,
    challengeState: ChallengeState?,
    onBack: () -> Unit,
    onMarkComplete: () -> Unit,
    onViewHistory: () -> Unit,
    showAbandonConfirm: Boolean,
    onRequestAbandon: () -> Unit,
    onConfirmAbandon: () -> Unit,
    onDismissAbandon: () -> Unit
) {
    if (showAbandonConfirm) {
        AlertDialog(
            onDismissRequest = onDismissAbandon,
            title = { Text("Stop this challenge?") },
            text = { Text("Your progress will be lost and you can start a new challenge.") },
            confirmButton = {
                TextButton(onClick = onConfirmAbandon) {
                    Text("Stop it", color = MaterialTheme.colorScheme.error)
                }
            },
            dismissButton = {
                TextButton(onClick = onDismissAbandon) { Text("Keep going") }
            }
        )
    }
    val cs = challengeState
    val isComplete = cs?.isComplete == true || cs?.state == ChallengeStatus.CHALLENGE_COMPLETE
    val currentDay = cs?.currentDay ?: progress.myNextDay.coerceAtMost(challenge.durationDays)
    val stateCopy = cs?.copy ?: ""
    val ctaLabel: String? = cs?.cta
    val missedDay = cs?.missedDate

    // Route each CTA to its correct action.
    // BOTH_COMPLETED_TODAY: next day content is already visible — button is a no-op acknowledgement.
    // CHALLENGE_COMPLETE: cta is null so button never shows, but handled for safety.
    // Everything else (NOT_STARTED, STARTED_TODAY, DAY_MISSED): mark today complete.
    val ctaEnabled: Boolean
    val ctaAction: () -> Unit
    when (cs?.state) {
        ChallengeStatus.BOTH_COMPLETED_TODAY -> { ctaEnabled = true; ctaAction = {} }
        ChallengeStatus.CHALLENGE_COMPLETE   -> { ctaEnabled = true; ctaAction = onViewHistory }
        else -> { ctaEnabled = cs?.canAdvance ?: true; ctaAction = onMarkComplete }
    }

    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .safeDrawingPadding()
            .navigationBarsPadding(),
        contentPadding = PaddingValues(horizontal = 20.dp, vertical = 16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        item {
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                IconButton(onClick = onBack) {
                    Icon(
                        Icons.AutoMirrored.Filled.ArrowBack,
                        contentDescription = "Back",
                        tint = MaterialTheme.colorScheme.onBackground
                    )
                }
                Spacer(Modifier.width(4.dp))
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = challenge.title,
                        style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.SemiBold),
                        color = MaterialTheme.colorScheme.onBackground,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                    Text(
                        text = if (isComplete) "${cs?.badge ?: "🏅"} Completed" else "Day $currentDay of ${challenge.durationDays}",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                if (progress.jointStreak > 0 && !isComplete) {
                    Surface(
                        shape = RoundedCornerShape(999.dp),
                        color = CloserPalette.PurpleDeep.copy(alpha = 0.12f)
                    ) {
                        Text(
                            text = "🔥 ${progress.jointStreak}",
                            modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
                            style = MaterialTheme.typography.labelMedium,
                            color = CloserPalette.PurpleDeep,
                            fontWeight = FontWeight.SemiBold
                        )
                    }
                }
            }
        }

        item {
            DayTrackerStrip(
                totalDays = challenge.durationDays,
                myCompletedDays = progress.myCompletedDays,
                partnerCompletedDays = progress.partnerCompletedDays,
                currentDay = currentDay
            )
        }

        // Missed-day banner
        if (missedDay != null && !isComplete) {
            item {
                Surface(
                    shape = RoundedCornerShape(16.dp),
                    color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.6f)
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(14.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(10.dp)
                    ) {
                        Text("⚠️", style = MaterialTheme.typography.bodyMedium)
                        Text(
                            text = "You missed a day — no worries, just pick it back up.",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onErrorContainer
                        )
                    }
                }
            }
        }

        if (!isComplete) {
            val dayPrompt = challenge.days.getOrNull(currentDay - 1)

            if (dayPrompt != null) {
                item {
                    Card(
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(24.dp),
                        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
                        elevation = CardDefaults.cardElevation(defaultElevation = 6.dp)
                    ) {
                        Column(
                            modifier = Modifier.padding(20.dp),
                            verticalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            Surface(
                                shape = RoundedCornerShape(999.dp),
                                color = CloserPalette.PurpleDeep.copy(alpha = 0.10f)
                            ) {
                                Text(
                                    text = "Day $currentDay",
                                    modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp),
                                    style = MaterialTheme.typography.labelSmall,
                                    color = CloserPalette.PurpleDeep,
                                    fontWeight = FontWeight.SemiBold
                                )
                            }
                            Text(
                                text = dayPrompt.prompt,
                                style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Medium),
                                color = MaterialTheme.colorScheme.onSurface,
                                lineHeight = MaterialTheme.typography.bodyLarge.lineHeight
                            )
                            if (dayPrompt.hint.isNotBlank()) {
                                Text(
                                    text = dayPrompt.hint,
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    }
                }

                // State machine copy — describes current state (waiting, partner done, etc.)
                if (stateCopy.isNotBlank()) {
                    item {
                        val isWaiting = cs?.state == ChallengeStatus.WAITING_FOR_PARTNER
                        val isBothDone = cs?.state == ChallengeStatus.BOTH_COMPLETED_TODAY
                        Surface(
                            shape = RoundedCornerShape(16.dp),
                            color = when {
                                isBothDone -> CloserPalette.Evergreen.copy(alpha = 0.10f)
                                isWaiting -> CloserPalette.PurpleDeep.copy(alpha = 0.07f)
                                else -> MaterialTheme.colorScheme.surface.copy(alpha = 0.6f)
                            }
                        ) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(14.dp),
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.spacedBy(10.dp)
                            ) {
                                val icon = when {
                                    isBothDone -> Icons.Filled.Check
                                    else -> null
                                }
                                if (icon != null) {
                                    Icon(icon, contentDescription = null, tint = CloserPalette.Evergreen, modifier = Modifier.size(18.dp))
                                } else {
                                    Text(if (isWaiting) "⏳" else "💬", style = MaterialTheme.typography.bodySmall)
                                }
                                Text(
                                    text = stateCopy,
                                    style = MaterialTheme.typography.bodySmall,
                                    color = if (isBothDone) CloserPalette.Evergreen else MaterialTheme.colorScheme.onSurfaceVariant,
                                    fontWeight = if (isBothDone) FontWeight.Medium else FontWeight.Normal
                                )
                            }
                        }
                    }
                }

                if (ctaLabel != null && cs?.state != ChallengeStatus.BOTH_COMPLETED_TODAY) {
                    item {
                        Button(
                            onClick = ctaAction,
                            enabled = ctaEnabled,
                            modifier = Modifier
                                .fillMaxWidth()
                                .heightIn(min = 54.dp),
                            shape = RoundedCornerShape(18.dp),
                            colors = ButtonDefaults.buttonColors(
                                containerColor = CloserPalette.PurpleDeep,
                                disabledContainerColor = CloserPalette.PurpleDeep.copy(alpha = 0.35f)
                            )
                        ) {
                            Text(
                                text = ctaLabel,
                                style = MaterialTheme.typography.labelLarge,
                                color = Color.White
                            )
                        }
                    }
                }
            }
        } else {
            item {
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(24.dp),
                    colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
                    elevation = CardDefaults.cardElevation(defaultElevation = 6.dp)
                ) {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(28.dp),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        Text(cs?.badge ?: "🏅", style = MaterialTheme.typography.displaySmall)
                        Text(
                            text = "Challenge complete!",
                            style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.SemiBold),
                            color = MaterialTheme.colorScheme.onSurface,
                            textAlign = TextAlign.Center
                        )
                        Text(
                            text = cs?.copy ?: "You and your partner finished \"${challenge.title}\" together. That's ${challenge.durationDays} days of showing up.",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            textAlign = TextAlign.Center
                        )
                    }
                }
            }
            item {
                Button(
                    onClick = onViewHistory,
                    modifier = Modifier
                        .fillMaxWidth()
                        .heightIn(min = 54.dp),
                    shape = RoundedCornerShape(18.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = CloserPalette.PurpleDeep
                    )
                ) {
                    Text(
                        text = "View game history",
                        style = MaterialTheme.typography.labelLarge,
                        color = Color.White
                    )
                }
            }
        }

        if (!isComplete) {
            item {
                TextButton(
                    onClick = onRequestAbandon,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text(
                        "Stop challenge",
                        style = MaterialTheme.typography.labelMedium,
                        color = MaterialTheme.colorScheme.error.copy(alpha = 0.55f)
                    )
                }
            }
        }

        item { Spacer(Modifier.height(8.dp)) }
    }
}

@Composable
private fun DayTrackerStrip(
    totalDays: Int,
    myCompletedDays: List<Int>,
    partnerCompletedDays: List<Int>,
    currentDay: Int
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        for (day in 1..totalDays) {
            val myDone = day in myCompletedDays
            val partnerDone = day in partnerCompletedDays
            val jointDone = myDone && partnerDone
            val isCurrent = day == currentDay.coerceAtMost(totalDays) && !myDone

            val bg = when {
                jointDone -> CloserPalette.PurpleDeep
                myDone -> CloserPalette.PurpleDeep.copy(alpha = 0.45f)
                isCurrent -> CloserPalette.PurpleDeep.copy(alpha = 0.15f)
                else -> MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
            }

            Box(
                modifier = Modifier
                    .weight(1f)
                    .height(36.dp)
                    .clip(RoundedCornerShape(10.dp))
                    .background(bg),
                contentAlignment = Alignment.Center
            ) {
                if (jointDone) {
                    Icon(Icons.Filled.Check, contentDescription = null, tint = Color.White, modifier = Modifier.size(14.dp))
                } else {
                    Text(
                        text = "$day",
                        style = MaterialTheme.typography.labelSmall,
                        color = if (myDone || isCurrent) Color.White else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f),
                        fontWeight = FontWeight.SemiBold
                    )
                }
            }
        }
    }
}
