package com.rosetta.messenger.ui.chats

import android.content.Context
import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.*
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.layout.*
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.filled.*
import androidx.compose.material.icons.outlined.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontFamily
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.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.airbnb.lottie.compose.*
import com.rosetta.messenger.R
import com.rosetta.messenger.data.RecentSearchesManager
import com.rosetta.messenger.network.ProtocolManager
import com.rosetta.messenger.network.ProtocolState
import com.rosetta.messenger.ui.components.AppleEmojiText
import com.rosetta.messenger.ui.onboarding.PrimaryBlue
import java.text.SimpleDateFormat
import java.util.*
import kotlinx.coroutines.launch

@Immutable
data class Chat(
        val id: String,
        val name: String,
        val lastMessage: String,
        val lastMessageTime: Date,
        val unreadCount: Int = 0,
        val isOnline: Boolean = false,
        val publicKey: String,
        val isSavedMessages: Boolean = false,
        val isPinned: Boolean = false
)

// Avatar colors matching React Native app (Mantine inspired)
// Light theme colors (background lighter, text darker)
private val avatarColorsLight =
        listOf(
                Color(0xFF1971c2) to Color(0xFFd0ebff), // blue
                Color(0xFF0c8599) to Color(0xFFc5f6fa), // cyan
                Color(0xFF9c36b5) to Color(0xFFeebefa), // grape
                Color(0xFF2f9e44) to Color(0xFFd3f9d8), // green
                Color(0xFF4263eb) to Color(0xFFdbe4ff), // indigo
                Color(0xFF5c940d) to Color(0xFFe9fac8), // lime
                Color(0xFFd9480f) to Color(0xFFffe8cc), // orange
                Color(0xFFc2255c) to Color(0xFFffdeeb), // pink
                Color(0xFFe03131) to Color(0xFFffe0e0), // red
                Color(0xFF099268) to Color(0xFFc3fae8), // teal
                Color(0xFF6741d9) to Color(0xFFe5dbff) // violet
        )

// Dark theme colors (background darker, text lighter)
private val avatarColorsDark =
        listOf(
                Color(0xFF7dd3fc) to Color(0xFF2d3548), // blue
                Color(0xFF67e8f9) to Color(0xFF2d4248), // cyan
                Color(0xFFd8b4fe) to Color(0xFF39334c), // grape
                Color(0xFF86efac) to Color(0xFF2d3f32), // green
                Color(0xFFa5b4fc) to Color(0xFF333448), // indigo
                Color(0xFFbef264) to Color(0xFF383f2d), // lime
                Color(0xFFfdba74) to Color(0xFF483529), // orange
                Color(0xFFf9a8d4) to Color(0xFF482d3d), // pink
                Color(0xFFfca5a5) to Color(0xFF482d2d), // red
                Color(0xFF5eead4) to Color(0xFF2d4340), // teal
                Color(0xFFc4b5fd) to Color(0xFF3a334c) // violet
        )

// Cache для цветов аватаров
data class AvatarColors(val textColor: Color, val backgroundColor: Color)

private val avatarColorCache = mutableMapOf<String, AvatarColors>()

fun getAvatarColor(name: String, isDarkTheme: Boolean): AvatarColors {
        val cacheKey = "${name}_${if (isDarkTheme) "dark" else "light"}"
        return avatarColorCache.getOrPut(cacheKey) {
                val colors = if (isDarkTheme) avatarColorsDark else avatarColorsLight
                val index =
                        name.hashCode().mod(colors.size).let {
                                if (it < 0) it + colors.size else it
                        }
                val (textColor, bgColor) = colors[index]
                AvatarColors(textColor, bgColor)
        }
}

// Cache для инициалов
private val initialsCache = mutableMapOf<String, String>()

fun getInitials(name: String): String {
        return initialsCache.getOrPut(name) {
                val words = name.trim().split(Regex("\\s+")).filter { it.isNotEmpty() }
                when {
                        words.isEmpty() -> "??"
                        words.size == 1 -> words[0].take(2).uppercase()
                        else -> "${words[0].first()}${words[1].first()}".uppercase()
                }
        }
}

// Get avatar text from public key (first 2 chars)
fun getAvatarText(publicKey: String): String {
        return publicKey.take(2).uppercase()
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChatsListScreen(
        isDarkTheme: Boolean,
        accountName: String,
        accountPhone: String,
        accountPublicKey: String,
        accountPrivateKey: String = "",
        privateKeyHash: String = "",
        onToggleTheme: () -> Unit,
        onProfileClick: () -> Unit,
        onNewGroupClick: () -> Unit,
        onContactsClick: () -> Unit,
        onCallsClick: () -> Unit,
        onSavedMessagesClick: () -> Unit,
        onSettingsClick: () -> Unit,
        onInviteFriendsClick: () -> Unit,
        onSearchClick: () -> Unit,
        onNewChat: () -> Unit,
        onUserSelect: (com.rosetta.messenger.network.SearchUser) -> Unit = {},
        chatsViewModel: ChatsListViewModel = androidx.lifecycle.viewmodel.compose.viewModel(),
        onLogout: () -> Unit
) {
        // Theme transition state
        var hasInitialized by remember { mutableStateOf(false) }

        LaunchedEffect(Unit) { hasInitialized = true }

        val view = androidx.compose.ui.platform.LocalView.current
        val context = androidx.compose.ui.platform.LocalContext.current
        val focusManager = androidx.compose.ui.platform.LocalFocusManager.current
        val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
        val scope = rememberCoroutineScope()

        // 🔥 ВСЕГДА закрываем клавиатуру при появлении ChatsListScreen
        // Используем DisposableEffect чтобы срабатывало при каждом появлении экрана
        DisposableEffect(Unit) {
                // Закрываем клавиатуру сразу
                val imm =
                        context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as
                                android.view.inputmethod.InputMethodManager
                imm.hideSoftInputFromWindow(view.windowToken, 0)
                focusManager.clearFocus()

                onDispose {}
        }

        // Дополнительно закрываем клавиатуру с небольшой задержкой (на случай если она появляется
        // после)
        LaunchedEffect(Unit) {
                kotlinx.coroutines.delay(100)
                val imm =
                        context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as
                                android.view.inputmethod.InputMethodManager
                imm.hideSoftInputFromWindow(view.windowToken, 0)
                focusManager.clearFocus()
        }

        // Update status bar and completely hide navigation bar
        LaunchedEffect(isDarkTheme) {
                if (!view.isInEditMode) {
                        val window = (view.context as android.app.Activity).window
                        val insetsController =
                                androidx.core.view.WindowCompat.getInsetsController(window, view)

                        // Status bar
                        insetsController.isAppearanceLightStatusBars = !isDarkTheme
                        window.statusBarColor = android.graphics.Color.TRANSPARENT

                        // Completely hide navigation bar
                        insetsController.hide(
                                androidx.core.view.WindowInsetsCompat.Type.navigationBars()
                        )
                        insetsController.systemBarsBehavior =
                                androidx.core.view.WindowInsetsControllerCompat
                                        .BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
                }
        }

        // Colors - instant change, no animation - 🔥 КЭШИРУЕМ для производительности
        val backgroundColor =
                remember(isDarkTheme) { if (isDarkTheme) Color(0xFF1A1A1A) else Color(0xFFFFFFFF) }
        val drawerBackgroundColor =
                remember(isDarkTheme) { if (isDarkTheme) Color(0xFF212121) else Color(0xFFFFFFFF) }
        val textColor = remember(isDarkTheme) { if (isDarkTheme) Color.White else Color.Black }
        val secondaryTextColor =
                remember(isDarkTheme) { if (isDarkTheme) Color(0xFF8E8E8E) else Color(0xFF8E8E93) }

        // Protocol connection state
        val protocolState by ProtocolManager.state.collectAsState()

        // 🔥 Пользователи, которые сейчас печатают
        val typingUsers by ProtocolManager.typingUsers.collectAsState()

        // Load dialogs when account is available
        LaunchedEffect(accountPublicKey, accountPrivateKey) {
                if (accountPublicKey.isNotEmpty() && accountPrivateKey.isNotEmpty()) {
                        chatsViewModel.setAccount(accountPublicKey, accountPrivateKey)
                        // Устанавливаем аккаунт для RecentSearchesManager
                        RecentSearchesManager.setAccount(accountPublicKey)
                        // 🔥 КРИТИЧНО: Инициализируем MessageRepository для обработки входящих
                        // сообщений
                        ProtocolManager.initializeAccount(accountPublicKey, accountPrivateKey)
                }
        }

        // Status dialog state
        var showStatusDialog by remember { mutableStateOf(false) }
        val debugLogs by ProtocolManager.debugLogs.collectAsState()

        // 📱 FCM токен диалог
        var showFcmDialog by remember { mutableStateOf(false) }

        // 📬 Requests screen state
        var showRequestsScreen by remember { mutableStateOf(false) }

        // 🔥 Используем rememberSaveable чтобы сохранить состояние при навигации
        // Header сразу visible = true, без анимации при возврате из чата
        var visible by rememberSaveable { mutableStateOf(true) }

        // Confirmation dialogs state
        var dialogToDelete by remember { mutableStateOf<DialogUiModel?>(null) }
        var dialogToBlock by remember { mutableStateOf<DialogUiModel?>(null) }
        var dialogToUnblock by remember { mutableStateOf<DialogUiModel?>(null) }

        // Trigger для обновления статуса блокировки
        var blocklistUpdateTrigger by remember { mutableStateOf(0) }

        // Dev console dialog - commented out for now
        /*
        if (showDevConsole) {
            AlertDialog(
                onDismissRequest = { showDevConsole = false },
                title = { Text("Dev Console", fontWeight = FontWeight.Bold) },
                text = { Text("Dev console temporarily disabled") },
                confirmButton = {
                    Button(onClick = { showDevConsole = false }) {
                        Text("Close")
                    }
                },
                containerColor = if (isDarkTheme) Color(0xFF212121) else Color.White
            )
        }
        */

        // Status dialog
        if (showStatusDialog) {
                AlertDialog(
                        onDismissRequest = { showStatusDialog = false },
                        title = {
                                Text(
                                        "Connection Status",
                                        fontWeight = FontWeight.Bold,
                                        color = textColor
                                )
                        },
                        text = {
                                Column(modifier = Modifier.fillMaxWidth()) {
                                        // Status indicator
                                        Row(
                                                verticalAlignment = Alignment.CenterVertically,
                                                modifier =
                                                        Modifier.fillMaxWidth()
                                                                .padding(bottom = 12.dp)
                                        ) {
                                                Box(
                                                        modifier =
                                                                Modifier.size(12.dp)
                                                                        .clip(CircleShape)
                                                                        .background(
                                                                                when (protocolState
                                                                                ) {
                                                                                        ProtocolState
                                                                                                .AUTHENTICATED ->
                                                                                                Color(
                                                                                                        0xFF4CAF50
                                                                                                )
                                                                                        ProtocolState
                                                                                                .CONNECTING,
                                                                                        ProtocolState
                                                                                                .CONNECTED,
                                                                                        ProtocolState
                                                                                                .HANDSHAKING ->
                                                                                                Color(
                                                                                                        0xFFFFC107
                                                                                                )
                                                                                        ProtocolState
                                                                                                .DISCONNECTED ->
                                                                                                Color(
                                                                                                        0xFFF44336
                                                                                                )
                                                                                }
                                                                        )
                                                )
                                                Spacer(modifier = Modifier.width(12.dp))
                                                Text(
                                                        text =
                                                                when (protocolState) {
                                                                        ProtocolState
                                                                                .DISCONNECTED ->
                                                                                "Disconnected"
                                                                        ProtocolState.CONNECTING ->
                                                                                "Connecting..."
                                                                        ProtocolState.CONNECTED ->
                                                                                "Connected"
                                                                        ProtocolState.HANDSHAKING ->
                                                                                "Authenticating..."
                                                                        ProtocolState
                                                                                .AUTHENTICATED ->
                                                                                "Authenticated"
                                                                },
                                                        fontSize = 16.sp,
                                                        fontWeight = FontWeight.Medium,
                                                        color = textColor
                                                )
                                        }
                                }
                        },
                        confirmButton = {
                                Button(
                                        onClick = { showStatusDialog = false },
                                        colors =
                                                ButtonDefaults.buttonColors(
                                                        containerColor = PrimaryBlue
                                                )
                                ) { Text("Close", color = Color.White) }
                        },
                        containerColor = if (isDarkTheme) Color(0xFF212121) else Color.White
                )
        }

        // Simple background
        Box(modifier = Modifier.fillMaxSize().background(backgroundColor).navigationBarsPadding()) {
                ModalNavigationDrawer(
                        drawerState = drawerState,
                        drawerContent = {
                                ModalDrawerSheet(
                                        drawerContainerColor = Color.Transparent,
                                        windowInsets =
                                                WindowInsets(
                                                        0
                                                ), // 🎨 Убираем системные отступы - drawer идет до
                                        // верха
                                        modifier = Modifier.width(300.dp)
                                ) {
                                        Column(
                                                modifier =
                                                        Modifier.fillMaxSize()
                                                                .background(drawerBackgroundColor)
                                        ) {
                                                // ═══════════════════════════════════════════════════════════
                                                // 🎨 DRAWER HEADER - Avatar and status
                                                // ═══════════════════════════════════════════════════════════
                                                val headerColor =
                                                        if (isDarkTheme) {
                                                                Color(0xFF2C5282)
                                                        } else {
                                                                Color(0xFF4A90D9)
                                                        }

                                                Box(
                                                        modifier =
                                                                Modifier.fillMaxWidth()
                                                                        .background(
                                                                                color = headerColor
                                                                        )
                                                                        .statusBarsPadding() // 🎨
                                                                        // Контент начинается
                                                                        // после status bar
                                                                        .padding(
                                                                                top = 16.dp,
                                                                                start = 20.dp,
                                                                                end = 20.dp,
                                                                                bottom = 20.dp
                                                                        )
                                                ) {
                                                        Column {
                                                                // Avatar with border
                                                                val avatarColors =
                                                                        getAvatarColor(
                                                                                accountPublicKey,
                                                                                isDarkTheme
                                                                        )
                                                                Box(
                                                                        modifier =
                                                                                Modifier.size(72.dp)
                                                                                        .clip(
                                                                                                CircleShape
                                                                                        )
                                                                                        .background(
                                                                                                Color.White
                                                                                                        .copy(
                                                                                                                alpha =
                                                                                                                        0.2f
                                                                                                        )
                                                                                        )
                                                                                        .padding(
                                                                                                3.dp
                                                                                        )
                                                                                        .clip(
                                                                                                CircleShape
                                                                                        )
                                                                                        .background(
                                                                                                avatarColors
                                                                                                        .backgroundColor
                                                                                        ),
                                                                        contentAlignment =
                                                                                Alignment.Center
                                                                ) {
                                                                        Text(
                                                                                text =
                                                                                        getAvatarText(
                                                                                                accountPublicKey
                                                                                        ),
                                                                                fontSize = 26.sp,
                                                                                fontWeight =
                                                                                        FontWeight
                                                                                                .Bold,
                                                                                color =
                                                                                        avatarColors
                                                                                                .textColor
                                                                        )
                                                                }

                                                                Spacer(
                                                                        modifier =
                                                                                Modifier.height(
                                                                                        14.dp
                                                                                )
                                                                )

                                                                // Public key (username style) -
                                                                // clickable для копирования
                                                                val truncatedKey =
                                                                        if (accountPublicKey
                                                                                        .length > 16
                                                                        ) {
                                                                                "${accountPublicKey.take(8)}...${accountPublicKey.takeLast(6)}"
                                                                        } else accountPublicKey

                                                                val context =
                                                                        androidx.compose.ui.platform
                                                                                .LocalContext
                                                                                .current
                                                                var showCopiedToast by remember {
                                                                        mutableStateOf(false)
                                                                }

                                                                // Плавная замена текста -
                                                                // ускоренная анимация
                                                                AnimatedContent(
                                                                        targetState =
                                                                                showCopiedToast,
                                                                        transitionSpec = {
                                                                                fadeIn(
                                                                                        animationSpec =
                                                                                                tween(
                                                                                                        150
                                                                                                )
                                                                                ) togetherWith
                                                                                        fadeOut(
                                                                                                animationSpec =
                                                                                                        tween(
                                                                                                                150
                                                                                                        )
                                                                                        )
                                                                        },
                                                                        label = "copiedAnimation"
                                                                ) { isCopied ->
                                                                        Text(
                                                                                text =
                                                                                        if (isCopied
                                                                                        )
                                                                                                "Copied!"
                                                                                        else
                                                                                                truncatedKey,
                                                                                fontSize = 16.sp,
                                                                                fontWeight =
                                                                                        FontWeight
                                                                                                .SemiBold,
                                                                                color = Color.White,
                                                                                fontStyle =
                                                                                        if (isCopied
                                                                                        )
                                                                                                androidx.compose
                                                                                                        .ui
                                                                                                        .text
                                                                                                        .font
                                                                                                        .FontStyle
                                                                                                        .Italic
                                                                                        else
                                                                                                androidx.compose
                                                                                                        .ui
                                                                                                        .text
                                                                                                        .font
                                                                                                        .FontStyle
                                                                                                        .Normal,
                                                                                modifier =
                                                                                        Modifier
                                                                                                .clickable {
                                                                                                        if (!showCopiedToast
                                                                                                        ) {
                                                                                                                // Копируем публичный ключ
                                                                                                                val clipboard =
                                                                                                                        context.getSystemService(
                                                                                                                                android.content
                                                                                                                                        .Context
                                                                                                                                        .CLIPBOARD_SERVICE
                                                                                                                        ) as
                                                                                                                                android.content.ClipboardManager
                                                                                                                val clip =
                                                                                                                        android.content
                                                                                                                                .ClipData
                                                                                                                                .newPlainText(
                                                                                                                                        "Public Key",
                                                                                                                                        accountPublicKey
                                                                                                                                )
                                                                                                                clipboard
                                                                                                                        .setPrimaryClip(
                                                                                                                                clip
                                                                                                                        )
                                                                                                                showCopiedToast =
                                                                                                                        true
                                                                                                        }
                                                                                                }
                                                                        )
                                                                }

                                                                // Автоматически возвращаем обратно
                                                                // через 1.5 секунды
                                                                if (showCopiedToast) {
                                                                        LaunchedEffect(Unit) {
                                                                                kotlinx.coroutines
                                                                                        .delay(1500)
                                                                                showCopiedToast =
                                                                                        false
                                                                        }
                                                                }

                                                                Spacer(
                                                                        modifier =
                                                                                Modifier.height(
                                                                                        6.dp
                                                                                )
                                                                )

                                                                // Username display
                                                                if (accountName.isNotEmpty()) {
                                                                        Text(
                                                                                text =
                                                                                        "@$accountName",
                                                                                fontSize = 13.sp,
                                                                                color =
                                                                                        Color.White
                                                                                                .copy(
                                                                                                        alpha =
                                                                                                                0.85f
                                                                                                )
                                                                        )
                                                                }
                                                        }
                                                }

                                                // ═══════════════════════════════════════════════════════════
                                                // 📱 MENU ITEMS
                                                // ═══════════════════════════════════════════════════════════
                                                Column(
                                                        modifier =
                                                                Modifier.fillMaxWidth()
                                                                        .weight(1f)
                                                                        .verticalScroll(
                                                                                rememberScrollState()
                                                                        )
                                                                        .padding(vertical = 8.dp)
                                                ) {
                                                        val menuIconColor =
                                                                textColor.copy(alpha = 0.6f)

                                                        // 👤 Profile Section
                                                        DrawerMenuItemEnhanced(
                                                                icon = Icons.Outlined.Person,
                                                                text = "My Profile",
                                                                iconColor = menuIconColor,
                                                                textColor = textColor,
                                                                onClick = {
                                                                        scope.launch {
                                                                                drawerState.close()
                                                                        }
                                                                        onProfileClick()
                                                                }
                                                        )

                                                        // 📖 Saved Messages
                                                        DrawerMenuItemEnhanced(
                                                                icon = Icons.Outlined.Bookmark,
                                                                text = "Saved Messages",
                                                                iconColor = menuIconColor,
                                                                textColor = textColor,
                                                                onClick = {
                                                                        scope.launch {
                                                                                drawerState.close()
                                                                                // Ждём завершения
                                                                                // анимации закрытия
                                                                                // drawer
                                                                                kotlinx.coroutines
                                                                                        .delay(250)
                                                                                onSavedMessagesClick()
                                                                        }
                                                                }
                                                        )

                                                        DrawerDivider(isDarkTheme)

                                                        // 👥 Contacts
                                                        DrawerMenuItemEnhanced(
                                                                icon = Icons.Outlined.Contacts,
                                                                text = "Contacts",
                                                                iconColor = menuIconColor,
                                                                textColor = textColor,
                                                                onClick = {
                                                                        scope.launch {
                                                                                drawerState.close()
                                                                        }
                                                                        onContactsClick()
                                                                }
                                                        )

                                                        // 📞 Calls
                                                        DrawerMenuItemEnhanced(
                                                                icon = Icons.Outlined.Call,
                                                                text = "Calls",
                                                                iconColor = menuIconColor,
                                                                textColor = textColor,
                                                                onClick = {
                                                                        scope.launch {
                                                                                drawerState.close()
                                                                        }
                                                                        onCallsClick()
                                                                }
                                                        )

                                                        // ➕ Invite Friends
                                                        DrawerMenuItemEnhanced(
                                                                icon = Icons.Outlined.PersonAdd,
                                                                text = "Invite Friends",
                                                                iconColor = menuIconColor,
                                                                textColor = textColor,
                                                                onClick = {
                                                                        scope.launch {
                                                                                drawerState.close()
                                                                        }
                                                                        onInviteFriendsClick()
                                                                }
                                                        )

                                                        DrawerDivider(isDarkTheme)

                                                        // 🔔 FCM Logs
                                                        DrawerMenuItemEnhanced(
                                                                icon = Icons.Outlined.Notifications,
                                                                text = "FCM Token Logs",
                                                                iconColor = menuIconColor,
                                                                textColor = textColor,
                                                                onClick = {
                                                                        scope.launch {
                                                                                drawerState.close()
                                                                        }
                                                                        showFcmDialog = true
                                                                }
                                                        )

                                                        // ⚙️ Settings
                                                        DrawerMenuItemEnhanced(
                                                                icon = Icons.Outlined.Settings,
                                                                text = "Settings",
                                                                iconColor = menuIconColor,
                                                                textColor = textColor,
                                                                onClick = {
                                                                        scope.launch {
                                                                                drawerState.close()
                                                                        }
                                                                        onSettingsClick()
                                                                }
                                                        )

                                                        // 🌓 Theme Toggle
                                                        DrawerMenuItemEnhanced(
                                                                icon =
                                                                        if (isDarkTheme)
                                                                                Icons.Outlined
                                                                                        .LightMode
                                                                        else
                                                                                Icons.Outlined
                                                                                        .DarkMode,
                                                                text =
                                                                        if (isDarkTheme)
                                                                                "Light Mode"
                                                                        else "Dark Mode",
                                                                iconColor = menuIconColor,
                                                                textColor = textColor,
                                                                onClick = { onToggleTheme() }
                                                        )

                                                        // ❓ Help
                                                        DrawerMenuItemEnhanced(
                                                                icon = Icons.Outlined.HelpOutline,
                                                                text = "Help & FAQ",
                                                                iconColor = menuIconColor,
                                                                textColor = textColor,
                                                                onClick = {
                                                                        scope.launch {
                                                                                drawerState.close()
                                                                        }
                                                                        // TODO: Add help screen
                                                                        // navigation
                                                                }
                                                        )
                                                }

                                                // ═══════════════════════════════════════════════════════════
                                                // 🚪 FOOTER - Logout & Version
                                                // ═══════════════════════════════════════════════════════════
                                                Column(modifier = Modifier.fillMaxWidth()) {
                                                        Divider(
                                                                color =
                                                                        if (isDarkTheme)
                                                                                Color(0xFF2A2A2A)
                                                                        else Color(0xFFE8E8E8),
                                                                thickness = 0.5.dp
                                                        )

                                                        // Logout
                                                        DrawerMenuItemEnhanced(
                                                                icon = Icons.Outlined.Logout,
                                                                text = "Log Out",
                                                                iconColor = Color(0xFFFF4444),
                                                                textColor = Color(0xFFFF4444),
                                                                onClick = {
                                                                        scope.launch {
                                                                                drawerState.close()
                                                                                kotlinx.coroutines
                                                                                        .delay(150)
                                                                                onLogout()
                                                                        }
                                                                }
                                                        )

                                                        // Version info
                                                        Box(
                                                                modifier =
                                                                        Modifier.fillMaxWidth()
                                                                                .padding(
                                                                                        horizontal =
                                                                                                20.dp,
                                                                                        vertical =
                                                                                                12.dp
                                                                                ),
                                                                contentAlignment =
                                                                        Alignment.CenterStart
                                                        ) {
                                                                Text(
                                                                        text = "Rosetta v1.0.0",
                                                                        fontSize = 12.sp,
                                                                        color =
                                                                                if (isDarkTheme)
                                                                                        Color(
                                                                                                0xFF666666
                                                                                        )
                                                                                else
                                                                                        Color(
                                                                                                0xFF999999
                                                                                        )
                                                                )
                                                        }

                                                        Spacer(modifier = Modifier.height(16.dp))
                                                }
                                        }
                                }
                        }
                ) {
                        Scaffold(
                                topBar = {
                                        AnimatedVisibility(
                                                visible = visible,
                                                enter =
                                                        fadeIn(tween(300)) +
                                                                expandVertically(
                                                                        animationSpec =
                                                                                tween(
                                                                                        300,
                                                                                        easing =
                                                                                                FastOutSlowInEasing
                                                                                )
                                                                ),
                                                exit =
                                                        fadeOut(tween(200)) +
                                                                shrinkVertically(
                                                                        animationSpec = tween(200)
                                                                )
                                        ) {
                                                key(isDarkTheme, showRequestsScreen) {
                                                        TopAppBar(
                                                                navigationIcon = {
                                                                        if (showRequestsScreen) {
                                                                                // Back button for
                                                                                // Requests
                                                                                IconButton(
                                                                                        onClick = {
                                                                                                showRequestsScreen =
                                                                                                        false
                                                                                        }
                                                                                ) {
                                                                                        Icon(
                                                                                                Icons.Default
                                                                                                        .ArrowBack,
                                                                                                contentDescription =
                                                                                                        "Back",
                                                                                                tint =
                                                                                                        PrimaryBlue
                                                                                        )
                                                                                }
                                                                        } else {
                                                                                // Menu button for
                                                                                // main screen
                                                                                IconButton(
                                                                                        onClick = {
                                                                                                scope
                                                                                                        .launch {
                                                                                                                drawerState
                                                                                                                        .open()
                                                                                                        }
                                                                                        }
                                                                                ) {
                                                                                        Icon(
                                                                                                Icons.Default
                                                                                                        .Menu,
                                                                                                contentDescription =
                                                                                                        "Menu",
                                                                                                tint =
                                                                                                        textColor
                                                                                                                .copy(
                                                                                                                        alpha =
                                                                                                                                0.6f
                                                                                                                )
                                                                                        )
                                                                                }
                                                                        }
                                                                },
                                                                title = {
                                                                        if (showRequestsScreen) {
                                                                                // Requests title
                                                                                Text(
                                                                                        "Requests",
                                                                                        fontWeight =
                                                                                                FontWeight
                                                                                                        .Bold,
                                                                                        fontSize =
                                                                                                20.sp,
                                                                                        color =
                                                                                                textColor
                                                                                )
                                                                        } else {
                                                                                // Rosetta title
                                                                                // with status
                                                                                Row(
                                                                                        verticalAlignment =
                                                                                                Alignment
                                                                                                        .CenterVertically
                                                                                ) {
                                                                                        Text(
                                                                                                "Rosetta",
                                                                                                fontWeight =
                                                                                                        FontWeight
                                                                                                                .Bold,
                                                                                                fontSize =
                                                                                                        20.sp,
                                                                                                color =
                                                                                                        textColor
                                                                                        )
                                                                                        Spacer(
                                                                                                modifier =
                                                                                                        Modifier.width(
                                                                                                                8.dp
                                                                                                        )
                                                                                        )
                                                                                        Box(
                                                                                                modifier =
                                                                                                        Modifier.size(
                                                                                                                        10.dp
                                                                                                                )
                                                                                                                .clip(
                                                                                                                        CircleShape
                                                                                                                )
                                                                                                                .background(
                                                                                                                        when (protocolState
                                                                                                                        ) {
                                                                                                                                ProtocolState
                                                                                                                                        .AUTHENTICATED ->
                                                                                                                                        Color(
                                                                                                                                                0xFF4CAF50
                                                                                                                                        )
                                                                                                                                ProtocolState
                                                                                                                                        .CONNECTING,
                                                                                                                                ProtocolState
                                                                                                                                        .CONNECTED,
                                                                                                                                ProtocolState
                                                                                                                                        .HANDSHAKING ->
                                                                                                                                        Color(
                                                                                                                                                0xFFFFC107
                                                                                                                                        )
                                                                                                                                ProtocolState
                                                                                                                                        .DISCONNECTED ->
                                                                                                                                        Color(
                                                                                                                                                0xFFF44336
                                                                                                                                        )
                                                                                                                        }
                                                                                                                )
                                                                                                                .clickable {
                                                                                                                        showStatusDialog =
                                                                                                                                true
                                                                                                                }
                                                                                        )
                                                                                }
                                                                        }
                                                                },
                                                                actions = {
                                                                        // Search only on main
                                                                        // screen
                                                                        if (!showRequestsScreen) {
                                                                                IconButton(
                                                                                        onClick = {
                                                                                                if (protocolState ==
                                                                                                                ProtocolState
                                                                                                                        .AUTHENTICATED
                                                                                                ) {
                                                                                                        onSearchClick()
                                                                                                }
                                                                                        },
                                                                                        enabled =
                                                                                                protocolState ==
                                                                                                        ProtocolState
                                                                                                                .AUTHENTICATED
                                                                                ) {
                                                                                        Icon(
                                                                                                Icons.Default
                                                                                                        .Search,
                                                                                                contentDescription =
                                                                                                        "Search",
                                                                                                tint =
                                                                                                        if (protocolState ==
                                                                                                                        ProtocolState
                                                                                                                                .AUTHENTICATED
                                                                                                        )
                                                                                                                textColor
                                                                                                                        .copy(
                                                                                                                                alpha =
                                                                                                                                        0.6f
                                                                                                                        )
                                                                                                        else
                                                                                                                textColor
                                                                                                                        .copy(
                                                                                                                                alpha =
                                                                                                                                        0.5f
                                                                                                                        )
                                                                                        )
                                                                                }
                                                                        }
                                                                },
                                                                colors =
                                                                        TopAppBarDefaults
                                                                                .topAppBarColors(
                                                                                        containerColor =
                                                                                                backgroundColor,
                                                                                        scrolledContainerColor =
                                                                                                backgroundColor,
                                                                                        navigationIconContentColor =
                                                                                                textColor,
                                                                                        titleContentColor =
                                                                                                textColor,
                                                                                        actionIconContentColor =
                                                                                                textColor
                                                                                )
                                                        )
                                                }
                                        }
                                },
                                floatingActionButton = {
                                        AnimatedVisibility(
                                                visible = false, // Hidden for now
                                                enter =
                                                        fadeIn(tween(500, delayMillis = 300)) +
                                                                scaleIn(
                                                                        initialScale = 0.5f,
                                                                        animationSpec =
                                                                                tween(
                                                                                        500,
                                                                                        delayMillis =
                                                                                                300
                                                                                )
                                                                )
                                        ) {
                                                FloatingActionButton(
                                                        onClick = onNewChat,
                                                        containerColor = PrimaryBlue,
                                                        contentColor = Color.White,
                                                        shape = CircleShape
                                                ) {
                                                        Icon(
                                                                Icons.Default.Edit,
                                                                contentDescription = "New Chat"
                                                        )
                                                }
                                        }
                                },
                                containerColor = backgroundColor
                        ) { paddingValues ->
                                // Main content
                                Box(modifier = Modifier.fillMaxSize().padding(paddingValues)) {
                                        // � Используем комбинированное состояние для атомарного
                                        // обновления
                                        // Это предотвращает "дергание" UI когда dialogs и requests
                                        // обновляются
                                        // независимо
                                        val chatsState by chatsViewModel.chatsState.collectAsState()
                                        val requests = chatsState.requests
                                        val requestsCount = chatsState.requestsCount

                                        // 🔥 ИСПРАВЛЕНИЕ МЕРЦАНИЯ: Запоминаем, что контент УЖЕ был
                                        // показан
                                        // Это предотвращает показ EmptyState при временных пустых
                                        // обновлениях
                                        var hasShownContent by rememberSaveable {
                                                mutableStateOf(false)
                                        }
                                        if (chatsState.hasContent) {
                                                hasShownContent = true
                                        }

                                        // 🎯 Показываем Empty State только если контент НИКОГДА не
                                        // показывался
                                        val shouldShowEmptyState =
                                                chatsState.isEmpty && !hasShownContent

                                        // 🎬 Animated content transition between main list and
                                        // requests
                                        AnimatedContent(
                                                targetState = showRequestsScreen,
                                                transitionSpec = {
                                                        fadeIn(
                                                                animationSpec = tween(200)
                                                        ) togetherWith
                                                                fadeOut(animationSpec = tween(150))
                                                },
                                                label = "RequestsTransition"
                                        ) { isRequestsScreen ->
                                                if (isRequestsScreen) {
                                                        // 📬 Show Requests Screen
                                                        RequestsScreen(
                                                                requests = requests,
                                                                isDarkTheme = isDarkTheme,
                                                                onBack = {
                                                                        showRequestsScreen = false
                                                                },
                                                                onRequestClick = { request ->
                                                                        showRequestsScreen = false
                                                                        val user =
                                                                                chatsViewModel
                                                                                        .dialogToSearchUser(
                                                                                                request
                                                                                        )
                                                                        onUserSelect(user)
                                                                }
                                                        )
                                                } else if (shouldShowEmptyState) {
                                                        // 🔥 Empty state - показываем только если
                                                        // контент НЕ был показан ранее
                                                        EmptyChatsState(
                                                                isDarkTheme = isDarkTheme,
                                                                modifier = Modifier.fillMaxSize()
                                                        )
                                                } else {
                                                        // Show dialogs list
                                                        val dividerColor =
                                                                if (isDarkTheme) Color(0xFF3A3A3A)
                                                                else Color(0xFFE8E8E8)
                                                        // 🔥 Берем dialogs из chatsState для
                                                        // консистентности
                                                        val currentDialogs = chatsState.dialogs

                                                        LazyColumn(
                                                                modifier = Modifier.fillMaxSize()
                                                        ) {
                                                                // � FCM Logs Section
                                                                val fcmLogs =
                                                                        com.rosetta.messenger
                                                                                .MainActivity
                                                                                .fcmLogs
                                                                if (fcmLogs.isNotEmpty()) {
                                                                        item(
                                                                                key =
                                                                                        "fcm_logs_section"
                                                                        ) {
                                                                                FcmLogsSection(
                                                                                        logs =
                                                                                                fcmLogs,
                                                                                        isDarkTheme =
                                                                                                isDarkTheme,
                                                                                        onClearLogs = {
                                                                                                com.rosetta
                                                                                                        .messenger
                                                                                                        .MainActivity
                                                                                                        .clearFcmLogs()
                                                                                        }
                                                                                )
                                                                                Divider(
                                                                                        color =
                                                                                                dividerColor,
                                                                                        thickness =
                                                                                                0.5.dp
                                                                                )
                                                                        }
                                                                }

                                                                // �📬 Requests Section
                                                                if (requestsCount > 0) {
                                                                        item(
                                                                                key =
                                                                                        "requests_section"
                                                                        ) {
                                                                                RequestsSection(
                                                                                        count =
                                                                                                requestsCount,
                                                                                        isDarkTheme =
                                                                                                isDarkTheme,
                                                                                        onClick = {
                                                                                                showRequestsScreen =
                                                                                                        true
                                                                                        }
                                                                                )
                                                                                Divider(
                                                                                        color =
                                                                                                dividerColor,
                                                                                        thickness =
                                                                                                0.5.dp
                                                                                )
                                                                        }
                                                                }

                                                                items(
                                                                        currentDialogs,
                                                                        key = { it.opponentKey }
                                                                ) { dialog ->
                                                                        val isSavedMessages =
                                                                                dialog.opponentKey ==
                                                                                        accountPublicKey
                                                                        // Check if user is blocked
                                                                        var isBlocked by remember {
                                                                                mutableStateOf(
                                                                                        false
                                                                                )
                                                                        }
                                                                        LaunchedEffect(
                                                                                dialog.opponentKey,
                                                                                blocklistUpdateTrigger
                                                                        ) {
                                                                                isBlocked =
                                                                                        chatsViewModel
                                                                                                .isUserBlocked(
                                                                                                        dialog.opponentKey
                                                                                                )
                                                                        }

                                                                        Column {
                                                                                SwipeableDialogItem(
                                                                                        dialog =
                                                                                                dialog,
                                                                                        isDarkTheme =
                                                                                                isDarkTheme,
                                                                                        isTyping =
                                                                                                typingUsers
                                                                                                        .contains(
                                                                                                                dialog.opponentKey
                                                                                                        ),
                                                                                        isBlocked =
                                                                                                isBlocked,
                                                                                        isSavedMessages =
                                                                                                isSavedMessages,
                                                                                        onClick = {
                                                                                                val user =
                                                                                                        chatsViewModel
                                                                                                                .dialogToSearchUser(
                                                                                                                        dialog
                                                                                                                )
                                                                                                onUserSelect(
                                                                                                        user
                                                                                                )
                                                                                        },
                                                                                        onDelete = {
                                                                                                dialogToDelete =
                                                                                                        dialog
                                                                                        },
                                                                                        onBlock = {
                                                                                                dialogToBlock =
                                                                                                        dialog
                                                                                        },
                                                                                        onUnblock = {
                                                                                                dialogToUnblock =
                                                                                                        dialog
                                                                                        }
                                                                                )

                                                                                // 🔥 СЕПАРАТОР -
                                                                                // линия разделения
                                                                                // между диалогами
                                                                                Divider(
                                                                                        modifier =
                                                                                                Modifier.padding(
                                                                                                        start =
                                                                                                                84.dp
                                                                                                ),
                                                                                        color =
                                                                                                dividerColor,
                                                                                        thickness =
                                                                                                0.5.dp
                                                                                )
                                                                        }
                                                                }
                                                        }
                                                }
                                        } // Close AnimatedContent

                                        // Console button removed
                                }
                        }
                } // Close ModalNavigationDrawer

                // 🔥 Confirmation Dialogs

                // Delete Dialog Confirmation
                dialogToDelete?.let { dialog ->
                        AlertDialog(
                                onDismissRequest = { dialogToDelete = null },
                                containerColor =
                                        if (isDarkTheme) Color(0xFF2C2C2E) else Color.White,
                                title = {
                                        Text(
                                                "Delete Chat",
                                                fontWeight = FontWeight.Bold,
                                                color = textColor
                                        )
                                },
                                text = {
                                        Text(
                                                "Are you sure you want to delete this chat? This action cannot be undone.",
                                                color = secondaryTextColor
                                        )
                                },
                                confirmButton = {
                                        TextButton(
                                                onClick = {
                                                        val opponentKey = dialog.opponentKey
                                                        dialogToDelete = null
                                                        scope.launch {
                                                                chatsViewModel.deleteDialog(
                                                                        opponentKey
                                                                )
                                                        }
                                                }
                                        ) { Text("Delete", color = Color(0xFFFF3B30)) }
                                },
                                dismissButton = {
                                        TextButton(onClick = { dialogToDelete = null }) {
                                                Text("Cancel", color = PrimaryBlue)
                                        }
                                }
                        )
                }

                // Block Dialog Confirmation
                dialogToBlock?.let { dialog ->
                        AlertDialog(
                                onDismissRequest = { dialogToBlock = null },
                                containerColor =
                                        if (isDarkTheme) Color(0xFF2C2C2E) else Color.White,
                                title = {
                                        Text(
                                                "Block ${dialog.opponentTitle.ifEmpty { "User" }}",
                                                fontWeight = FontWeight.Bold,
                                                color = textColor
                                        )
                                },
                                text = {
                                        Text(
                                                "Are you sure you want to block this user? They won't be able to send you messages.",
                                                color = secondaryTextColor
                                        )
                                },
                                confirmButton = {
                                        TextButton(
                                                onClick = {
                                                        val opponentKey = dialog.opponentKey
                                                        dialogToBlock = null
                                                        scope.launch {
                                                                chatsViewModel.blockUser(
                                                                        opponentKey
                                                                )
                                                                blocklistUpdateTrigger++
                                                        }
                                                }
                                        ) { Text("Block", color = Color(0xFFFF3B30)) }
                                },
                                dismissButton = {
                                        TextButton(onClick = { dialogToBlock = null }) {
                                                Text("Cancel", color = PrimaryBlue)
                                        }
                                }
                        )
                }

                // Unblock Dialog Confirmation
                dialogToUnblock?.let { dialog ->
                        AlertDialog(
                                onDismissRequest = { dialogToUnblock = null },
                                containerColor =
                                        if (isDarkTheme) Color(0xFF2C2C2E) else Color.White,
                                title = {
                                        Text(
                                                "Unblock ${dialog.opponentTitle.ifEmpty { "User" }}",
                                                fontWeight = FontWeight.Bold,
                                                color = textColor
                                        )
                                },
                                text = {
                                        Text(
                                                "Are you sure you want to unblock this user? They will be able to send you messages again.",
                                                color = secondaryTextColor
                                        )
                                },
                                confirmButton = {
                                        TextButton(
                                                onClick = {
                                                        val opponentKey = dialog.opponentKey
                                                        dialogToUnblock = null
                                                        scope.launch {
                                                                chatsViewModel.unblockUser(
                                                                        opponentKey
                                                                )
                                                                blocklistUpdateTrigger++
                                                        }
                                                }
                                        ) { Text("Unblock", color = PrimaryBlue) }
                                },
                                dismissButton = {
                                        TextButton(onClick = { dialogToUnblock = null }) {
                                                Text("Cancel", color = Color(0xFF8E8E93))
                                        }
                                }
                        )
                }
        } // Close Box
}

@Composable
private fun EmptyChatsState(isDarkTheme: Boolean, modifier: Modifier = Modifier) {
        val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)

        // Lottie animation
        val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.letter))
        val progress by animateLottieCompositionAsState(composition = composition, iterations = 1)

        Column(
                modifier = modifier.fillMaxSize(),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
        ) {
                // Lottie animation
                LottieAnimation(
                        composition = composition,
                        progress = { progress },
                        modifier = Modifier.size(150.dp)
                )

                Spacer(modifier = Modifier.height(24.dp))

                Text(
                        text = "No conversations yet",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.SemiBold,
                        color = secondaryTextColor,
                        textAlign = TextAlign.Center
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                        text = "Start a new conversation to get started",
                        fontSize = 15.sp,
                        color = secondaryTextColor,
                        textAlign = TextAlign.Center
                )
        }
}

// Chat item for list
@Composable
fun ChatItem(chat: Chat, isDarkTheme: Boolean, onClick: () -> Unit) {
        val textColor = if (isDarkTheme) Color.White else Color.Black
        val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)
        val dividerColor = if (isDarkTheme) Color(0xFF3A3A3A) else Color(0xFFE8E8E8)

        val avatarColors = getAvatarColor(chat.publicKey, isDarkTheme)
        val avatarText = getAvatarText(chat.publicKey)

        Column {
                Row(
                        modifier =
                                Modifier.fillMaxWidth()
                                        .clickable(onClick = onClick)
                                        .padding(horizontal = 16.dp, vertical = 12.dp),
                        verticalAlignment = Alignment.CenterVertically
                ) {
                        // Avatar
                        Box(
                                modifier =
                                        Modifier.size(56.dp)
                                                .clip(CircleShape)
                                                .background(avatarColors.backgroundColor),
                                contentAlignment = Alignment.Center
                        ) {
                                Text(
                                        text = avatarText,
                                        fontSize = 20.sp,
                                        fontWeight = FontWeight.SemiBold,
                                        color = avatarColors.textColor
                                )

                                // Online indicator
                                if (chat.isOnline) {
                                        Box(
                                                modifier =
                                                        Modifier.align(Alignment.BottomEnd)
                                                                .offset(x = 2.dp, y = 2.dp)
                                                                .size(16.dp)
                                                                .clip(CircleShape)
                                                                .background(
                                                                        if (isDarkTheme)
                                                                                Color(0xFF1A1A1A)
                                                                        else Color.White
                                                                )
                                                                .padding(2.dp)
                                                                .clip(CircleShape)
                                                                .background(Color(0xFF4CAF50))
                                        )
                                }
                        }

                        Spacer(modifier = Modifier.width(12.dp))

                        Column(modifier = Modifier.weight(1f)) {
                                Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.SpaceBetween,
                                        verticalAlignment = Alignment.CenterVertically
                                ) {
                                        Text(
                                                text = chat.name,
                                                fontSize = 16.sp,
                                                fontWeight = FontWeight.SemiBold,
                                                color = textColor,
                                                maxLines = 1,
                                                overflow = TextOverflow.Ellipsis,
                                                modifier = Modifier.weight(1f)
                                        )

                                        Row(verticalAlignment = Alignment.CenterVertically) {
                                                // Read status
                                                Icon(
                                                        Icons.Default.DoneAll,
                                                        contentDescription = null,
                                                        tint = PrimaryBlue,
                                                        modifier = Modifier.size(16.dp)
                                                )
                                                Spacer(modifier = Modifier.width(4.dp))
                                                Text(
                                                        text = formatTime(chat.lastMessageTime),
                                                        fontSize = 13.sp,
                                                        color = secondaryTextColor
                                                )
                                        }
                                }

                                Spacer(modifier = Modifier.height(4.dp))

                                Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.SpaceBetween,
                                        verticalAlignment = Alignment.CenterVertically
                                ) {
                                        // 🔥 Используем AppleEmojiText для отображения эмодзи
                                        AppleEmojiText(
                                                text = chat.lastMessage,
                                                fontSize = 14.sp,
                                                color = secondaryTextColor,
                                                maxLines = 1,
                                                overflow = android.text.TextUtils.TruncateAt.END,
                                                modifier = Modifier.weight(1f)
                                        )

                                        Row(verticalAlignment = Alignment.CenterVertically) {
                                                // Pin icon
                                                if (chat.isPinned) {
                                                        Icon(
                                                                Icons.Default.PushPin,
                                                                contentDescription = "Pinned",
                                                                tint =
                                                                        secondaryTextColor.copy(
                                                                                alpha = 0.6f
                                                                        ),
                                                                modifier =
                                                                        Modifier.size(16.dp)
                                                                                .padding(end = 4.dp)
                                                        )
                                                }

                                                // Unread badge
                                                if (chat.unreadCount > 0) {
                                                        Box(
                                                                modifier =
                                                                        Modifier.clip(CircleShape)
                                                                                .background(
                                                                                        PrimaryBlue
                                                                                )
                                                                                .padding(
                                                                                        horizontal =
                                                                                                8.dp,
                                                                                        vertical =
                                                                                                2.dp
                                                                                ),
                                                                contentAlignment = Alignment.Center
                                                        ) {
                                                                Text(
                                                                        text =
                                                                                if (chat.unreadCount >
                                                                                                99
                                                                                )
                                                                                        "99+"
                                                                                else
                                                                                        chat.unreadCount
                                                                                                .toString(),
                                                                        fontSize = 12.sp,
                                                                        fontWeight =
                                                                                FontWeight.SemiBold,
                                                                        color = Color.White
                                                                )
                                                        }
                                                }
                                        }
                                }
                        }
                }

                Divider(
                        modifier = Modifier.padding(start = 84.dp),
                        color = dividerColor,
                        thickness = 0.5.dp
                )
        }
}

// Cache для SimpleDateFormat - создание дорогостоящее
private val timeFormatCache =
        java.lang.ThreadLocal.withInitial { SimpleDateFormat("HH:mm", Locale.getDefault()) }
private val weekFormatCache =
        java.lang.ThreadLocal.withInitial { SimpleDateFormat("EEE", Locale.getDefault()) }
private val monthFormatCache =
        java.lang.ThreadLocal.withInitial { SimpleDateFormat("MMM d", Locale.getDefault()) }
private val yearFormatCache =
        java.lang.ThreadLocal.withInitial { SimpleDateFormat("dd.MM.yy", Locale.getDefault()) }

private fun formatTime(date: Date): String {
        val now = Calendar.getInstance()
        val messageTime = Calendar.getInstance().apply { time = date }

        return when {
                now.get(Calendar.DATE) == messageTime.get(Calendar.DATE) -> {
                        timeFormatCache.get()?.format(date) ?: ""
                }
                now.get(Calendar.DATE) - messageTime.get(Calendar.DATE) == 1 -> {
                        "Yesterday"
                }
                now.get(Calendar.WEEK_OF_YEAR) == messageTime.get(Calendar.WEEK_OF_YEAR) -> {
                        weekFormatCache.get()?.format(date) ?: ""
                }
                now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR) -> {
                        monthFormatCache.get()?.format(date) ?: ""
                }
                else -> {
                        yearFormatCache.get()?.format(date) ?: ""
                }
        }
}

/** Элемент меню в боковом drawer */
@Composable
fun DrawerMenuItem(
        icon: androidx.compose.ui.graphics.vector.ImageVector,
        text: String,
        isDarkTheme: Boolean,
        isDestructive: Boolean = false,
        onClick: () -> Unit
) {
        val textColor =
                if (isDestructive) {
                        Color(0xFFFF3B30)
                } else {
                        if (isDarkTheme) Color.White else Color.Black
                }

        val backgroundColor = if (isDarkTheme) Color(0xFF2C2C2E) else Color(0xFFF2F2F7)

        Row(
                modifier =
                        Modifier.fillMaxWidth()
                                .padding(horizontal = 16.dp, vertical = 4.dp)
                                .clip(RoundedCornerShape(12.dp))
                                .background(backgroundColor)
                                .clickable(onClick = onClick)
                                .padding(horizontal = 16.dp, vertical = 14.dp),
                verticalAlignment = Alignment.CenterVertically
        ) {
                Icon(
                        imageVector = icon,
                        contentDescription = null,
                        tint = textColor.copy(alpha = 0.6f),
                        modifier = Modifier.size(24.dp)
                )

                Spacer(modifier = Modifier.width(16.dp))

                Text(
                        text = text,
                        fontSize = 16.sp,
                        color = textColor,
                        fontWeight = FontWeight.Medium
                )
        }
}

/**
 * 🔥 Swipeable wrapper для DialogItem с кнопками Block и Delete Свайп влево показывает действия
 * (как в React Native версии)
 */
@Composable
fun SwipeableDialogItem(
        dialog: DialogUiModel,
        isDarkTheme: Boolean,
        isTyping: Boolean = false,
        isBlocked: Boolean = false,
        isSavedMessages: Boolean = false,
        onClick: () -> Unit,
        onDelete: () -> Unit = {},
        onBlock: () -> Unit = {},
        onUnblock: () -> Unit = {}
) {
        val backgroundColor = if (isDarkTheme) Color(0xFF1A1A1A) else Color(0xFFFFFFFF)
        var offsetX by remember { mutableStateOf(0f) }
        val swipeWidthDp = if (isSavedMessages) 80.dp else 160.dp
        val density = androidx.compose.ui.platform.LocalDensity.current
        val swipeWidthPx = with(density) { swipeWidthDp.toPx() }

        // Фиксированная высота элемента (как в DialogItem)
        val itemHeight = 80.dp

        // Анимация возврата
        val animatedOffsetX by
                animateFloatAsState(
                        targetValue = offsetX,
                        animationSpec = spring(dampingRatio = 0.7f, stiffness = 400f),
                        label = "swipeOffset"
                )

        Box(modifier = Modifier.fillMaxWidth().height(itemHeight).clipToBounds()) {
                // 1. КНОПКИ - позиционированы справа, всегда видны при свайпе
                Row(
                        modifier =
                                Modifier.align(Alignment.CenterEnd)
                                        .height(itemHeight)
                                        .width(swipeWidthDp)
                ) {
                        // Кнопка Block/Unblock (только если не Saved Messages)
                        if (!isSavedMessages) {
                                Box(
                                        modifier =
                                                Modifier.width(80.dp)
                                                        .fillMaxHeight()
                                                        .background(
                                                                if (isBlocked) Color(0xFF4CAF50)
                                                                else Color(0xFFFF6B6B)
                                                        )
                                                        .clickable {
                                                                if (isBlocked) onUnblock()
                                                                else onBlock()
                                                                offsetX = 0f
                                                        },
                                        contentAlignment = Alignment.Center
                                ) {
                                        Column(
                                                horizontalAlignment = Alignment.CenterHorizontally,
                                                verticalArrangement = Arrangement.Center
                                        ) {
                                                Icon(
                                                        imageVector =
                                                                if (isBlocked)
                                                                        Icons.Default.LockOpen
                                                                else Icons.Default.Block,
                                                        contentDescription =
                                                                if (isBlocked) "Unblock"
                                                                else "Block",
                                                        tint = Color.White,
                                                        modifier = Modifier.size(22.dp)
                                                )
                                                Spacer(modifier = Modifier.height(4.dp))
                                                Text(
                                                        text =
                                                                if (isBlocked) "Unblock"
                                                                else "Block",
                                                        color = Color.White,
                                                        fontSize = 12.sp,
                                                        fontWeight = FontWeight.SemiBold
                                                )
                                        }
                                }
                        }

                        // Кнопка Delete
                        Box(
                                modifier =
                                        Modifier.width(80.dp)
                                                .fillMaxHeight()
                                                .background(PrimaryBlue)
                                                .clickable {
                                                        // Закрываем свайп мгновенно перед удалением
                                                        offsetX = 0f
                                                        onDelete()
                                                },
                                contentAlignment = Alignment.Center
                        ) {
                                Column(
                                        horizontalAlignment = Alignment.CenterHorizontally,
                                        verticalArrangement = Arrangement.Center
                                ) {
                                        Icon(
                                                imageVector = Icons.Default.Delete,
                                                contentDescription = "Delete",
                                                tint = Color.White,
                                                modifier = Modifier.size(22.dp)
                                        )
                                        Spacer(modifier = Modifier.height(4.dp))
                                        Text(
                                                text = "Delete",
                                                color = Color.White,
                                                fontSize = 12.sp,
                                                fontWeight = FontWeight.SemiBold
                                        )
                                }
                        }
                }

                // 2. КОНТЕНТ - поверх кнопок, сдвигается при свайпе
                Column(
                        modifier =
                                Modifier.fillMaxSize()
                                        .offset { IntOffset(animatedOffsetX.toInt(), 0) }
                                        .background(backgroundColor)
                                        .pointerInput(Unit) {
                                                detectHorizontalDragGestures(
                                                        onDragEnd = {
                                                                // Если свайпнули больше чем на
                                                                // половину - фиксируем
                                                                if (kotlin.math.abs(offsetX) >
                                                                                swipeWidthPx / 2
                                                                ) {
                                                                        offsetX = -swipeWidthPx
                                                                } else {
                                                                        offsetX = 0f
                                                                }
                                                        },
                                                        onDragCancel = { offsetX = 0f },
                                                        onHorizontalDrag = { _, dragAmount ->
                                                                // Только свайп влево (отрицательное
                                                                // значение)
                                                                val newOffset = offsetX + dragAmount
                                                                offsetX =
                                                                        newOffset.coerceIn(
                                                                                -swipeWidthPx,
                                                                                0f
                                                                        )
                                                        }
                                                )
                                        }
                ) {
                        DialogItemContent(
                                dialog = dialog,
                                isDarkTheme = isDarkTheme,
                                isTyping = isTyping,
                                onClick = onClick
                        )

                        // Сепаратор внутри контента
                        val dividerColor = if (isDarkTheme) Color(0xFF3A3A3A) else Color(0xFFE8E8E8)
                        Divider(
                                modifier = Modifier.padding(start = 84.dp),
                                color = dividerColor,
                                thickness = 0.5.dp
                        )
                }
        }
}

/** Элемент диалога из базы данных - ОПТИМИЗИРОВАННЫЙ (без сепаратора для SwipeableDialogItem) */
@Composable
fun DialogItemContent(
        dialog: DialogUiModel,
        isDarkTheme: Boolean,
        isTyping: Boolean = false,
        onClick: () -> Unit
) {
        // 🔥 ОПТИМИЗАЦИЯ: Кешируем цвета и строки
        val textColor = remember(isDarkTheme) { if (isDarkTheme) Color.White else Color.Black }
        val secondaryTextColor =
                remember(isDarkTheme) { if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666) }

        val avatarColors =
                remember(dialog.opponentKey, isDarkTheme) {
                        getAvatarColor(dialog.opponentKey, isDarkTheme)
                }

        // 📁 Для Saved Messages показываем специальное имя
        // 🔥 Как в Архиве: title > username > "DELETED"
        val displayName =
                remember(
                        dialog.opponentTitle,
                        dialog.opponentUsername,
                        dialog.opponentKey,
                        dialog.isSavedMessages
                ) {
                        if (dialog.isSavedMessages) {
                                "Saved Messages"
                        } else if (dialog.opponentTitle.isNotEmpty() &&
                                        dialog.opponentTitle != dialog.opponentKey &&
                                        dialog.opponentTitle != dialog.opponentKey.take(7) &&
                                        dialog.opponentTitle != dialog.opponentKey.take(8)
                        ) {
                                // 🔥 Показываем title как основное имя (как в десктопной версии)
                                // Обрезаем до 15 символов как в Архиве
                                if (dialog.opponentTitle.length > 15) {
                                        dialog.opponentTitle.take(15) + "..."
                                } else {
                                        dialog.opponentTitle
                                }
                        } else if (dialog.opponentUsername.isNotEmpty()) {
                                // Username только если нет title
                                "@${dialog.opponentUsername}"
                        } else {
                                // 🔥 Как в Архиве - если нет информации, показываем часть ключа
                                dialog.opponentKey.take(7)
                        }
                }

        // 📁 Для Saved Messages показываем иконку закладки
        // 🔥 Как в Архиве: инициалы из title или username или DELETED
        val initials =
                remember(
                        dialog.opponentTitle,
                        dialog.opponentUsername,
                        dialog.opponentKey,
                        dialog.isSavedMessages
                ) {
                        if (dialog.isSavedMessages) {
                                "" // Для Saved Messages - пустая строка, будет использоваться
                                // иконка
                        } else if (dialog.opponentTitle.isNotEmpty() &&
                                        dialog.opponentTitle != dialog.opponentKey &&
                                        dialog.opponentTitle != dialog.opponentKey.take(7) &&
                                        dialog.opponentTitle != dialog.opponentKey.take(8)
                        ) {
                                // Используем title для инициалов
                                dialog.opponentTitle
                                        .split(" ")
                                        .take(2)
                                        .mapNotNull { it.firstOrNull()?.uppercase() }
                                        .joinToString("")
                                        .ifEmpty { dialog.opponentTitle.take(2).uppercase() }
                        } else if (dialog.opponentUsername.isNotEmpty()) {
                                // Если только username - берем первые 2 символа
                                dialog.opponentUsername.take(2).uppercase()
                        } else {
                                dialog.opponentKey.take(2).uppercase()
                        }
                }

        Row(
                modifier =
                        Modifier.fillMaxWidth()
                                .clickable(onClick = onClick)
                                .padding(horizontal = 16.dp, vertical = 12.dp),
                verticalAlignment = Alignment.CenterVertically
        ) {
                // Avatar container with online indicator
                Box(modifier = Modifier.size(56.dp)) {
                        // Avatar
                        Box(
                                modifier =
                                        Modifier.fillMaxSize()
                                                .clip(CircleShape)
                                                .background(
                                                        if (dialog.isSavedMessages) PrimaryBlue
                                                        else avatarColors.backgroundColor
                                                ),
                                contentAlignment = Alignment.Center
                        ) {
                                if (dialog.isSavedMessages) {
                                        Icon(
                                                Icons.Default.Bookmark,
                                                contentDescription = null,
                                                tint = Color.White,
                                                modifier = Modifier.size(24.dp)
                                        )
                                } else {
                                        Text(
                                                text = initials,
                                                color = avatarColors.textColor,
                                                fontWeight = FontWeight.SemiBold,
                                                fontSize = 18.sp
                                        )
                                }
                        }

                        // Online indicator - зелёный кружок с белой обводкой
                        if (dialog.isOnline == 1) {
                                Box(
                                        modifier =
                                                Modifier.size(18.dp)
                                                        .align(Alignment.BottomEnd)
                                                        .offset(x = (-2).dp, y = (-2).dp)
                                                        .clip(CircleShape)
                                                        .background(
                                                                if (isDarkTheme) Color(0xFF1C1C1E)
                                                                else Color.White
                                                        )
                                                        .padding(3.dp)
                                                        .clip(CircleShape)
                                                        .background(
                                                                Color(0xFF34C759)
                                                        ) // iOS зелёный цвет
                                )
                        }
                }

                Spacer(modifier = Modifier.width(12.dp))

                // Name and last message
                Column(modifier = Modifier.weight(1f)) {
                        Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                        ) {
                                Text(
                                        text = displayName,
                                        fontWeight = FontWeight.SemiBold,
                                        fontSize = 16.sp,
                                        color = textColor,
                                        maxLines = 1,
                                        overflow = TextOverflow.Ellipsis,
                                        modifier = Modifier.weight(1f)
                                )

                                Row(
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.End
                                ) {
                                        // 📁 Для Saved Messages ВСЕГДА показываем синие двойные
                                        // галочки (прочитано)
                                        if (dialog.isSavedMessages) {
                                                Icon(
                                                        imageVector = Icons.Default.DoneAll,
                                                        contentDescription = null,
                                                        tint = PrimaryBlue,
                                                        modifier = Modifier.size(16.dp)
                                                )
                                                Spacer(modifier = Modifier.width(4.dp))
                                        } else if (dialog.lastMessageFromMe == 1) {
                                                // Показываем статус только для исходящих сообщений
                                                // (кроме Saved Messages)
                                                // 🔥 ПРАВИЛЬНАЯ ЛОГИКА (синхронизировано с
                                                // ChatViewModel):
                                                // - lastMessageDelivered == 3 → две синие галочки
                                                // (прочитано собеседником)
                                                // - lastMessageDelivered == 1 → одна галочка
                                                // (доставлено)
                                                // - lastMessageDelivered == 0 → часики
                                                // (отправляется)
                                                // - lastMessageDelivered == 2 → ошибка
                                                when (dialog.lastMessageDelivered) {
                                                        2 -> {
                                                                // ERROR - показываем иконку ошибки
                                                                Icon(
                                                                        imageVector =
                                                                                Icons.Outlined
                                                                                        .ErrorOutline,
                                                                        contentDescription =
                                                                                "Sending failed",
                                                                        tint =
                                                                                Color(
                                                                                        0xFFFF3B30
                                                                                ), // iOS красный
                                                                        modifier =
                                                                                Modifier.size(16.dp)
                                                                )
                                                                Spacer(
                                                                        modifier =
                                                                                Modifier.width(4.dp)
                                                                )
                                                        }
                                                        3 -> {
                                                                // READ (delivered=3) - две синие
                                                                // галочки
                                                                Icon(
                                                                        imageVector =
                                                                                Icons.Default
                                                                                        .DoneAll,
                                                                        contentDescription = null,
                                                                        tint = PrimaryBlue,
                                                                        modifier =
                                                                                Modifier.size(16.dp)
                                                                )
                                                                Spacer(
                                                                        modifier =
                                                                                Modifier.width(4.dp)
                                                                )
                                                        }
                                                        else -> {
                                                                // DELIVERED (1) или SENDING (0) -
                                                                // одна серая галочка
                                                                Icon(
                                                                        imageVector =
                                                                                Icons.Default.Done,
                                                                        contentDescription = null,
                                                                        tint =
                                                                                secondaryTextColor
                                                                                        .copy(
                                                                                                alpha =
                                                                                                        0.6f
                                                                                        ),
                                                                        modifier =
                                                                                Modifier.size(16.dp)
                                                                )
                                                                Spacer(
                                                                        modifier =
                                                                                Modifier.width(4.dp)
                                                                )
                                                        }
                                                }
                                        }

                                        Text(
                                                text =
                                                        formatTime(
                                                                Date(dialog.lastMessageTimestamp)
                                                        ),
                                                fontSize = 13.sp,
                                                color =
                                                        if (dialog.unreadCount > 0) PrimaryBlue
                                                        else secondaryTextColor
                                        )
                                }
                        }

                        Spacer(modifier = Modifier.height(4.dp))

                        Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                        ) {
                                // 🔥 Показываем typing индикатор или последнее сообщение
                                if (isTyping) {
                                        TypingIndicatorSmall()
                                } else {
                                        // 🔥 Используем AppleEmojiText для отображения эмодзи
                                        // Если есть непрочитанные - текст темнее
                                        AppleEmojiText(
                                                text = dialog.lastMessage.ifEmpty { "No messages" },
                                                fontSize = 14.sp,
                                                color =
                                                        if (dialog.unreadCount > 0)
                                                                textColor.copy(alpha = 0.85f)
                                                        else secondaryTextColor,
                                                fontWeight =
                                                        if (dialog.unreadCount > 0)
                                                                FontWeight.Medium
                                                        else FontWeight.Normal,
                                                maxLines = 1,
                                                overflow = android.text.TextUtils.TruncateAt.END,
                                                modifier = Modifier.weight(1f)
                                        )
                                }

                                // Unread badge
                                if (dialog.unreadCount > 0) {
                                        Spacer(modifier = Modifier.width(8.dp))
                                        val unreadText =
                                                when {
                                                        dialog.unreadCount > 999 -> "999+"
                                                        dialog.unreadCount > 99 -> "99+"
                                                        else -> dialog.unreadCount.toString()
                                                }
                                        Box(
                                                modifier =
                                                        Modifier.height(22.dp)
                                                                .widthIn(min = 22.dp)
                                                                .clip(RoundedCornerShape(11.dp))
                                                                .background(PrimaryBlue)
                                                                .padding(horizontal = 6.dp),
                                                contentAlignment = Alignment.Center
                                        ) {
                                                Text(
                                                        text = unreadText,
                                                        fontSize = 12.sp,
                                                        fontWeight = FontWeight.Bold,
                                                        color = Color.White,
                                                        maxLines = 1
                                                )
                                        }
                                }
                        }
                }
        }
}

/**
 * 🔥 Компактный индикатор typing для списка чатов Голубой текст "typing" с анимированными точками
 */
@Composable
fun TypingIndicatorSmall() {
        val infiniteTransition = rememberInfiniteTransition(label = "typing")
        val typingColor = PrimaryBlue

        Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(1.dp)
        ) {
                Text(
                        text = "typing",
                        fontSize = 14.sp,
                        color = typingColor,
                        fontWeight = FontWeight.Medium
                )

                // 3 анимированные точки
                repeat(3) { index ->
                        val offsetY by
                                infiniteTransition.animateFloat(
                                        initialValue = 0f,
                                        targetValue = -3f,
                                        animationSpec =
                                                infiniteRepeatable(
                                                        animation =
                                                                tween(
                                                                        durationMillis = 500,
                                                                        delayMillis = index * 120,
                                                                        easing = FastOutSlowInEasing
                                                                ),
                                                        repeatMode = RepeatMode.Reverse
                                                ),
                                        label = "dot$index"
                                )

                        Text(
                                text = ".",
                                fontSize = 14.sp,
                                color = typingColor,
                                fontWeight = FontWeight.Medium,
                                modifier = Modifier.offset(y = offsetY.dp)
                        )
                }
        }
}

/** 📬 Секция Requests - кнопка для перехода к списку запросов */
@Composable
fun RequestsSection(count: Int, isDarkTheme: Boolean, onClick: () -> Unit) {
        val textColor = if (isDarkTheme) Color(0xFF4DABF7) else Color(0xFF228BE6)
        val arrowColor = if (isDarkTheme) Color(0xFFC9C9C9) else Color(0xFF228BE6)

        Row(
                modifier =
                        Modifier.fillMaxWidth()
                                .clickable(onClick = onClick)
                                .padding(horizontal = 16.dp, vertical = 14.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
        ) {
                Text(
                        text = "Requests +$count",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.SemiBold,
                        color = textColor
                )

                Icon(
                        imageVector = Icons.Default.ChevronRight,
                        contentDescription = "Open requests",
                        tint = arrowColor.copy(alpha = 0.6f),
                        modifier = Modifier.size(24.dp)
                )
        }
}

/** 📬 Экран со списком Requests (без хедера - хедер в основном TopAppBar) */
@Composable
fun RequestsScreen(
        requests: List<DialogUiModel>,
        isDarkTheme: Boolean,
        onBack: () -> Unit,
        onRequestClick: (DialogUiModel) -> Unit
) {
        val backgroundColor = if (isDarkTheme) Color(0xFF1A1A1A) else Color(0xFFFFFFFF)
        val dividerColor = if (isDarkTheme) Color(0xFF3A3A3A) else Color(0xFFE8E8E8)

        Column(modifier = Modifier.fillMaxSize().background(backgroundColor)) {
                if (requests.isEmpty()) {
                        // Empty state
                        Box(
                                modifier = Modifier.fillMaxSize().padding(32.dp),
                                contentAlignment = Alignment.Center
                        ) {
                                Text(
                                        text = "No requests",
                                        fontSize = 16.sp,
                                        color =
                                                if (isDarkTheme) Color(0xFF8E8E8E)
                                                else Color(0xFF8E8E93),
                                        textAlign = TextAlign.Center
                                )
                        }
                } else {
                        // Requests list
                        LazyColumn(modifier = Modifier.fillMaxSize()) {
                                items(requests, key = { it.opponentKey }) { request ->
                                        DialogItemContent(
                                                dialog = request,
                                                isDarkTheme = isDarkTheme,
                                                isTyping = false,
                                                onClick = { onRequestClick(request) }
                                        )

                                        Divider(
                                                modifier = Modifier.padding(start = 84.dp),
                                                color = dividerColor,
                                                thickness = 0.5.dp
                                        )
                                }
                        }
                }
        }
}

/** 🎨 Enhanced Drawer Menu Item - красивый пункт меню с hover эффектом */
@Composable
fun DrawerMenuItemEnhanced(
        icon: androidx.compose.ui.graphics.vector.ImageVector,
        text: String,
        iconColor: Color,
        textColor: Color,
        badge: String? = null,
        onClick: () -> Unit
) {
        Row(
                modifier =
                        Modifier.fillMaxWidth()
                                .clickable(onClick = onClick)
                                .padding(horizontal = 20.dp, vertical = 14.dp),
                verticalAlignment = Alignment.CenterVertically
        ) {
                Icon(
                        imageVector = icon,
                        contentDescription = null,
                        tint = iconColor,
                        modifier = Modifier.size(24.dp)
                )

                Spacer(modifier = Modifier.width(20.dp))

                Text(
                        text = text,
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Normal,
                        color = textColor,
                        modifier = Modifier.weight(1f)
                )

                badge?.let {
                        Box(
                                modifier =
                                        Modifier.background(
                                                        color = Color(0xFF4A90D9),
                                                        shape = RoundedCornerShape(10.dp)
                                                )
                                                .padding(horizontal = 8.dp, vertical = 2.dp)
                        ) {
                                Text(
                                        text = it,
                                        fontSize = 12.sp,
                                        fontWeight = FontWeight.Medium,
                                        color = Color.White
                                )
                        }
                }
        }
}

/** 📏 Drawer Divider - разделитель между секциями */
@Composable
fun DrawerDivider(isDarkTheme: Boolean) {
        Spacer(modifier = Modifier.height(8.dp))
        Divider(
                modifier = Modifier.padding(horizontal = 20.dp),
                color = if (isDarkTheme) Color(0xFF2A2A2A) else Color(0xFFEEEEEE),
                thickness = 0.5.dp
        )
        Spacer(modifier = Modifier.height(8.dp))
}

/** 🔔 FCM Logs Section - отображение логов отправки FCM токена */
@Composable
fun FcmLogsSection(logs: List<String>, isDarkTheme: Boolean, onClearLogs: () -> Unit) {
        val backgroundColor = if (isDarkTheme) Color(0xFF2C2C2E) else Color(0xFFF8F9FA)
        val textColor = if (isDarkTheme) Color(0xFFE0E0E0) else Color(0xFF1A1A1A)
        val accentColor = if (isDarkTheme) Color(0xFF4A90D9) else Color(0xFF2979FF)

        var expanded by remember { mutableStateOf(true) }

        Column(modifier = Modifier.fillMaxWidth().background(backgroundColor)) {
                // Header
                Row(
                        modifier =
                                Modifier.fillMaxWidth()
                                        .clickable { expanded = !expanded }
                                        .padding(horizontal = 16.dp, vertical = 12.dp),
                        verticalAlignment = Alignment.CenterVertically
                ) {
                        Icon(
                                imageVector =
                                        if (expanded) Icons.Default.KeyboardArrowDown
                                        else Icons.Default.KeyboardArrowRight,
                                contentDescription = null,
                                tint = accentColor,
                                modifier = Modifier.size(24.dp)
                        )

                        Spacer(modifier = Modifier.width(12.dp))

                        Text(
                                text = "🔔 FCM Token Status",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Bold,
                                color = textColor,
                                modifier = Modifier.weight(1f)
                        )

                        // Clear button
                        if (logs.isNotEmpty()) {
                                TextButton(
                                        onClick = onClearLogs,
                                        contentPadding =
                                                PaddingValues(horizontal = 8.dp, vertical = 4.dp)
                                ) { Text(text = "Clear", fontSize = 13.sp, color = accentColor) }
                        }
                }

                // Logs content
                AnimatedVisibility(
                        visible = expanded,
                        enter = expandVertically() + fadeIn(),
                        exit = shrinkVertically() + fadeOut()
                ) {
                        Column(
                                modifier =
                                        Modifier.fillMaxWidth()
                                                .padding(horizontal = 16.dp, vertical = 8.dp)
                                                .background(
                                                        color =
                                                                if (isDarkTheme) Color(0xFF1A1A1A)
                                                                else Color.White,
                                                        shape = RoundedCornerShape(8.dp)
                                                )
                                                .padding(12.dp)
                        ) {
                                if (logs.isEmpty()) {
                                        Text(
                                                text = "No FCM logs yet...",
                                                fontSize = 14.sp,
                                                color =
                                                        if (isDarkTheme) Color(0xFF8E8E8E)
                                                        else Color(0xFF999999),
                                                fontFamily = FontFamily.Monospace
                                        )
                                } else {
                                        logs.take(10).forEach { log ->
                                                Text(
                                                        text = log,
                                                        fontSize = 12.sp,
                                                        color = textColor,
                                                        fontFamily = FontFamily.Monospace,
                                                        lineHeight = 18.sp,
                                                        modifier = Modifier.padding(vertical = 2.dp)
                                                )
                                        }

                                        if (logs.size > 10) {
                                                Spacer(modifier = Modifier.height(4.dp))
                                                Text(
                                                        text = "... и ещё ${logs.size - 10} логов",
                                                        fontSize = 11.sp,
                                                        color =
                                                                if (isDarkTheme) Color(0xFF8E8E8E)
                                                                else Color(0xFF999999),
                                                        fontStyle =
                                                                androidx.compose.ui.text.font
                                                                        .FontStyle.Italic
                                                )
                                        }
                                }
                        }
                }

                Spacer(modifier = Modifier.height(8.dp))
        }
}
