package com.rosetta.messenger.ui.settings

import android.content.Context
import android.graphics.Bitmap
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicBlur
import android.view.PixelCopy
import android.view.View
import androidx.activity.compose.BackHandler
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import compose.icons.TablerIcons
import compose.icons.tablericons.*
import com.rosetta.messenger.ui.icons.TelegramIcons
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.clipPath
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.rosetta.messenger.repository.AvatarRepository
import com.rosetta.messenger.utils.AvatarFileManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import compose.icons.tablericons.Sun
import compose.icons.tablericons.Moon
import kotlin.math.hypot
import kotlin.math.max

/**
 * Экран кастомизации внешнего вида.
 * Позволяет выбрать цвет/градиент для background blur в профиле.
 * Preview повторяет avatar block из профиля — реальный blur + аватарка.
 */
@Composable
fun AppearanceScreen(
    isDarkTheme: Boolean,
    currentBlurColorId: String,
    onBack: () -> Unit,
    onBlurColorChange: (String) -> Unit,
    onToggleTheme: () -> Unit = {},
    onAppIconClick: () -> Unit = {},
    accountPublicKey: String = "",
    accountName: String = "",
    avatarRepository: AvatarRepository? = null
) {
    val view = LocalView.current
    if (!view.isInEditMode) {
        DisposableEffect(isDarkTheme) {
            val window = (view.context as android.app.Activity).window
            val insetsController = androidx.core.view.WindowCompat.getInsetsController(window, view)
            val prev = insetsController.isAppearanceLightStatusBars
            insetsController.isAppearanceLightStatusBars = !isDarkTheme
            window.statusBarColor = android.graphics.Color.TRANSPARENT
            onDispose { insetsController.isAppearanceLightStatusBars = prev }
        }
    }

    val backgroundColor = if (isDarkTheme) Color(0xFF1A1A1A) else Color(0xFFFFFFFF)
    val textColor = if (isDarkTheme) Color.White else Color.Black
    val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)

    var selectedId by remember { mutableStateOf(currentBlurColorId) }

    // ── Circular reveal state ──
    val scope = rememberCoroutineScope()
    var screenshotBitmap by remember { mutableStateOf<Bitmap?>(null) }
    val revealProgress = remember { Animatable(1f) } // 1 = fully revealed (no overlay)
    var revealCenter by remember { mutableStateOf(Offset.Zero) }
    var screenSize by remember { mutableStateOf(IntSize.Zero) }

    // Helper: capture screenshot of the current view, then animate circular reveal
    fun triggerCircularReveal(center: Offset, applyChange: () -> Unit) {
        // Don't start a new animation while one is running
        if (screenshotBitmap != null) return

        val rootView = view.rootView
        val width = rootView.width
        val height = rootView.height
        if (width <= 0 || height <= 0) {
            applyChange()
            return
        }

        val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)

        fun onScreenshotReady() {
            screenshotBitmap = bmp
            revealCenter = center
            scope.launch {
                revealProgress.snapTo(0f)
                applyChange()
                revealProgress.animateTo(
                    targetValue = 1f,
                    animationSpec = tween(durationMillis = 380)
                )
                screenshotBitmap = null
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val window = (view.context as? android.app.Activity)?.window
            if (window != null) {
                PixelCopy.request(
                    window,
                    bmp,
                    { result ->
                        if (result == PixelCopy.SUCCESS) {
                            onScreenshotReady()
                        } else {
                            applyChange()
                        }
                    },
                    Handler(Looper.getMainLooper())
                )
                return
            }
        }
        // Fallback for older APIs
        @Suppress("DEPRECATION")
        rootView.isDrawingCacheEnabled = true
        @Suppress("DEPRECATION")
        rootView.buildDrawingCache()
        @Suppress("DEPRECATION")
        val cache = rootView.drawingCache
        if (cache != null) {
            val canvas = android.graphics.Canvas(bmp)
            canvas.drawBitmap(cache, 0f, 0f, null)
            @Suppress("DEPRECATION")
            rootView.destroyDrawingCache()
            onScreenshotReady()
        } else {
            applyChange()
        }
    }

    BackHandler { onBack() }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .onGloballyPositioned { screenSize = it.size }
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(backgroundColor)
        ) {
        // ═══════════════════════════════════════════════════════════
        // CONTENT
        // ═══════════════════════════════════════════════════════════
        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
        ) {
            // ═══════════════════════════════════════════════════════
            // LIVE PREVIEW — реальный avatar block из профиля
            // Покрывает status bar, кнопки overlay поверх
            // ═══════════════════════════════════════════════════════
            Box {
                ProfileBlurPreview(
                    selectedId = selectedId,
                    isDarkTheme = isDarkTheme,
                    publicKey = accountPublicKey,
                    displayName = accountName,
                    avatarRepository = avatarRepository
                )

                // Overlay: кнопка назад (слева) и смена темы (справа)
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .statusBarsPadding()
                        .padding(horizontal = 4.dp, vertical = 8.dp),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    IconButton(onClick = onBack) {
                        Icon(
                            imageVector = TablerIcons.ChevronLeft,
                            contentDescription = "Back",
                            tint = Color.White
                        )
                    }
                    var themeButtonCenter by remember { mutableStateOf(Offset.Zero) }
                    IconButton(
                        onClick = {
                            triggerCircularReveal(themeButtonCenter) {
                                onToggleTheme()
                            }
                        },
                        modifier = Modifier.onGloballyPositioned { coords ->
                            val bounds = coords.boundsInRoot()
                            themeButtonCenter = bounds.center
                        }
                    ) {
                        Icon(
                            imageVector = if (isDarkTheme) TablerIcons.Sun else TablerIcons.Moon,
                            contentDescription = "Toggle theme",
                            tint = Color.White
                        )
                    }
                }
            }

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

            // ═══════════════════════════════════════════════════════
            // SECTION TITLE
            // ═══════════════════════════════════════════════════════
            Text(
                text = "BACKGROUND COLOR",
                fontSize = 13.sp,
                fontWeight = FontWeight.Medium,
                color = secondaryTextColor,
                letterSpacing = 0.5.sp,
                modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
            )

            // ═══════════════════════════════════════════════════════
            // COLOR GRID
            // ═══════════════════════════════════════════════════════
            ColorSelectionGrid(
                selectedId = selectedId,
                isDarkTheme = isDarkTheme,
                onSelect = { id, centerInRoot ->
                    if (id != selectedId) {
                        triggerCircularReveal(centerInRoot) {
                            selectedId = id
                            onBlurColorChange(id)
                        }
                    }
                }
            )

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

            Text(
                text = "Choose a color or gradient overlay for the blurred header background in your profile.",
                fontSize = 13.sp,
                color = secondaryTextColor,
                modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
                lineHeight = 18.sp
            )

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

            // ═══════════════════════════════════════════════════════
            // APP ICON SECTION
            // ═══════════════════════════════════════════════════════
            Text(
                text = "APP ICON",
                fontSize = 13.sp,
                fontWeight = FontWeight.Medium,
                color = secondaryTextColor,
                letterSpacing = 0.5.sp,
                modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
            )

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable { onAppIconClick() }
                    .padding(horizontal = 16.dp, vertical = 14.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = "Change App Icon",
                    fontSize = 16.sp,
                    color = textColor
                )
                Icon(
                    imageVector = TablerIcons.ChevronRight,
                    contentDescription = null,
                    tint = secondaryTextColor,
                    modifier = Modifier.size(20.dp)
                )
            }

            Text(
                text = "Disguise Rosetta as a calculator, weather app, or notes.",
                fontSize = 13.sp,
                color = secondaryTextColor,
                modifier = Modifier.padding(horizontal = 16.dp),
                lineHeight = 18.sp
            )

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

        // ── Circular reveal overlay ──
        // Screenshot of old state is drawn with a circular hole that grows,
        // revealing the new state underneath.
        val bmp = screenshotBitmap
        if (bmp != null) {
            val progress = revealProgress.value
            val maxRadius = hypot(
                max(revealCenter.x, screenSize.width - revealCenter.x),
                max(revealCenter.y, screenSize.height - revealCenter.y)
            )
            val currentRadius = maxRadius * progress

            Canvas(
                modifier = Modifier
                    .fillMaxSize()
                    .graphicsLayer { compositingStrategy = androidx.compose.ui.graphics.CompositingStrategy.Offscreen }
            ) {
                // Draw the old screenshot
                drawImage(
                    image = bmp.asImageBitmap()
                )
                // Cut a circular hole — reveals new content underneath
                drawCircle(
                    color = Color.Black,
                    radius = currentRadius,
                    center = revealCenter,
                    blendMode = BlendMode.DstOut
                )
            }
        }
    }
}


// ═══════════════════════════════════════════════════════════════════════
// 🎨 LIVE PREVIEW — повторяет avatar block из ProfileScreen
// Реальный blur аватарки + overlay + круглая аватарка + имя
// ═══════════════════════════════════════════════════════════════════════

@Composable
private fun ProfileBlurPreview(
    selectedId: String,
    isDarkTheme: Boolean,
    publicKey: String,
    displayName: String,
    avatarRepository: AvatarRepository?
) {
    val option = BackgroundBlurPresets.findById(selectedId)
    val overlayColors = BackgroundBlurPresets.getOverlayColors(selectedId)
    val shouldUseAvatarBlur = overlayColors.isNullOrEmpty() && selectedId != "none"
    val avatarColors = getAvatarColor(publicKey, isDarkTheme)

    // Загрузка аватарки
    val avatars by avatarRepository?.getAvatars(publicKey, allDecode = false)?.collectAsState()
        ?: remember { mutableStateOf(emptyList()) }

    val avatarKey = remember(avatars) { avatars.firstOrNull()?.timestamp ?: 0L }
    var avatarBitmap by remember { mutableStateOf<Bitmap?>(null) }
    var blurredBitmap by remember { mutableStateOf<Bitmap?>(null) }
    val blurContext = LocalContext.current

    LaunchedEffect(avatarKey, shouldUseAvatarBlur) {
        val current = avatars
        if (current.isNotEmpty()) {
            val decoded = withContext(Dispatchers.IO) {
                AvatarFileManager.base64ToBitmap(current.first().base64Data)
            }
            if (decoded != null) {
                avatarBitmap = decoded
                blurredBitmap =
                    if (shouldUseAvatarBlur) {
                        withContext(Dispatchers.Default) {
                            appearanceGaussianBlur(blurContext, decoded, radius = 20f, passes = 2)
                        }
                    } else {
                        null
                    }
            }
        } else {
            avatarBitmap = null
            blurredBitmap = null
        }
    }

    // Анимированный label
    val labelText = if (option.colors.isEmpty()) "Avatar Blur" else option.label

    // Preview — повторяет profile header, покрывает status bar
    val statusBarHeight = WindowInsets.statusBars.asPaddingValues().calculateTopPadding()
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(280.dp + statusBarHeight)
    ) {
            // ═══════════════════════════════════════════════════
            // LAYER 1: Blurred avatar background (идентично BlurredAvatarBackground)
            // ═══════════════════════════════════════════════════
            if (shouldUseAvatarBlur && blurredBitmap != null) {
                val blurImgAlpha = 0.9f
                Image(
                    bitmap = blurredBitmap!!.asImageBitmap(),
                    contentDescription = null,
                    modifier = Modifier
                        .fillMaxSize()
                        .graphicsLayer { alpha = blurImgAlpha },
                    contentScale = ContentScale.Crop
                )
            }

            // ═══════════════════════════════════════════════════
            // LAYER 2: Color/gradient overlay (или fallback)
            // ═══════════════════════════════════════════════════
            if (selectedId == "none") {
                // None — стандартный цвет шапки
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(if (isDarkTheme) Color(0xFF2A2A2A) else Color(0xFF0D8CF4))
                )
            } else if (overlayColors != null && overlayColors.isNotEmpty()) {
                val overlayMod = if (overlayColors.size == 1) {
                    Modifier
                        .fillMaxSize()
                        .background(overlayColors[0])
                } else {
                    Modifier
                        .fillMaxSize()
                        .background(
                            Brush.linearGradient(
                                colors = overlayColors
                            )
                        )
                }
                Box(modifier = overlayMod)
            } else if (shouldUseAvatarBlur && blurredBitmap != null) {
                // Стандартный тинт (идентичен BlurredAvatarBackground)
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(avatarColors.backgroundColor.copy(alpha = 0.12f))
                )
            } else {
                // Нет аватарки и нет overlay — fallback цвет
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(
                            if (isDarkTheme) Color(0xFF2A2A2E) else Color(0xFFD8D8DC)
                        )
                )
            }

            // ═══════════════════════════════════════════════════
            // LAYER 3: Нижний градиент (идентичен BlurredAvatarBackground)
            // ═══════════════════════════════════════════════════
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(
                        Brush.verticalGradient(
                            colors = listOf(
                                Color.Transparent,
                                Color.Transparent,
                                Color.Black.copy(alpha = if (selectedId == "none") 0f else 0.2f)
                            )
                        )
                    )
            )

            // ═══════════════════════════════════════════════════
            // LAYER 4: Avatar circle + Name + subtitle
            // Повторяет layout из CollapsingProfileHeader
            // ═══════════════════════════════════════════════════
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(top = statusBarHeight)
                    .padding(bottom = 24.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                // Круглая аватарка с shadow — 120dp как в ProfileScreen
                Box(
                    modifier = Modifier
                        .size(120.dp)
                        .shadow(12.dp, CircleShape)
                        .clip(CircleShape)
                        .background(avatarColors.backgroundColor),
                    contentAlignment = Alignment.Center
                ) {
                    if (avatarBitmap != null) {
                        Image(
                            bitmap = avatarBitmap!!.asImageBitmap(),
                            contentDescription = "Avatar",
                            modifier = Modifier.fillMaxSize(),
                            contentScale = ContentScale.Crop
                        )
                    } else {
                        // Placeholder с инициалами (40sp как в ProfileScreen)
                        Text(
                            text = getInitials(displayName.ifBlank { publicKey.take(6) }),
                            fontSize = 40.sp,
                            fontWeight = FontWeight.Bold,
                            color = avatarColors.textColor
                        )
                    }
                }

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

                // Имя пользователя
                Text(
                    text = displayName.ifBlank { publicKey.take(10) + "..." },
                    fontSize = 24.sp,
                    fontWeight = FontWeight.SemiBold,
                    color = Color.White,
                    textAlign = TextAlign.Center,
                    maxLines = 1
                )

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

                // Label текущего пресета — с иконкой стрелки для градиентов
                val labelParts = labelText.split("|")
                if (labelParts.size == 2) {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.Center
                    ) {
                        Text(
                            text = labelParts[0],
                            fontSize = 14.sp,
                            color = Color.White.copy(alpha = 0.7f)
                        )
                        Icon(
                            imageVector = TablerIcons.ArrowNarrowRight,
                            contentDescription = null,
                            tint = Color.White.copy(alpha = 0.5f),
                            modifier = Modifier
                                .padding(horizontal = 4.dp)
                                .size(16.dp)
                        )
                        Text(
                            text = labelParts[1],
                            fontSize = 14.sp,
                            color = Color.White.copy(alpha = 0.7f)
                        )
                    }
                } else {
                    Text(
                        text = labelText,
                        fontSize = 14.sp,
                        color = Color.White.copy(alpha = 0.7f),
                        textAlign = TextAlign.Center
                    )
                }
            }
        }
    }


// ═══════════════════════════════════════════════════════════════════
// 🎨 COLOR GRID — адаптивная сетка выбора цветов
// ═══════════════════════════════════════════════════════════════════

@Composable
private fun ColorSelectionGrid(
    selectedId: String,
    isDarkTheme: Boolean,
    onSelect: (String, Offset) -> Unit
) {
    val allOptions = BackgroundBlurPresets.allWithDefault
    val horizontalPadding = 12.dp
    val preferredColumns = 8
    val minColumns = 6
    val maxCircleSize = 40.dp
    val minCircleSize = 32.dp
    val minItemSpacing = 6.dp

    BoxWithConstraints(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = horizontalPadding)
    ) {
        val maxColumnsThatFit =
            ((maxWidth + minItemSpacing) / (maxCircleSize + minItemSpacing))
                .toInt()
                .coerceAtLeast(1)
        val columns =
            maxOf(minColumns, minOf(preferredColumns, maxColumnsThatFit))

        val circleSize =
            ((maxWidth - minItemSpacing * (columns - 1)) / columns)
                .coerceIn(minCircleSize, maxCircleSize)

        val itemSpacing =
            if (columns > 1) {
                ((maxWidth - circleSize * columns) / (columns - 1)).coerceAtLeast(minItemSpacing)
            } else {
                0.dp
            }

        Column(modifier = Modifier.fillMaxWidth()) {
        allOptions.chunked(columns).forEach { rowItems ->
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 6.dp),
                horizontalArrangement = Arrangement.spacedBy(itemSpacing, Alignment.CenterHorizontally)
            ) {
                rowItems.forEach { option ->
                    ColorCircleItem(
                        option = option,
                        isSelected = option.id == selectedId,
                        isDarkTheme = isDarkTheme,
                        circleSize = circleSize,
                        onSelectWithPosition = { centerInRoot -> onSelect(option.id, centerInRoot) }
                    )
                }
                repeat(columns - rowItems.size) {
                    Spacer(modifier = Modifier.size(circleSize))
                }
            }
        }
        }
    }
}

@Composable
private fun ColorCircleItem(
    option: BackgroundBlurOption,
    isSelected: Boolean,
    isDarkTheme: Boolean,
    circleSize: Dp,
    onSelectWithPosition: (Offset) -> Unit
) {
    val scale by animateFloatAsState(
        targetValue = if (isSelected) 1.08f else 1.0f,
        animationSpec = tween(200),
        label = "scale"
    )

    val borderColor by animateColorAsState(
        targetValue = if (isSelected) {
            if (isDarkTheme) Color.White else Color(0xFF222222)
        } else {
            Color.Transparent
        },
        animationSpec = tween(200),
        label = "border"
    )

    // Track center position in root coordinates for circular reveal
    var boundsInRoot by remember { mutableStateOf(Rect.Zero) }

    Box(
        modifier = Modifier
            .size(circleSize)
            .scale(scale)
            .onGloballyPositioned { coords ->
                boundsInRoot = coords.boundsInRoot()
            }
            .clip(CircleShape)
            .border(
                width = if (isSelected) 2.5.dp else 0.5.dp,
                color = if (isSelected) borderColor else if (isDarkTheme) Color.White.copy(alpha = 0.12f) else Color.Black.copy(alpha = 0.12f),
                shape = CircleShape
            )
            .clickable {
                val center = boundsInRoot.center
                onSelectWithPosition(center)
            },
        contentAlignment = Alignment.Center
    ) {
        when {
            option.id == "none" -> {
                // None — стандартные цвета, перечеркнутый круг
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(
                            if (isDarkTheme) Color(0xFF2A2A2A) else Color(0xFF0D8CF4)
                        ),
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        imageVector = TablerIcons.X,
                        contentDescription = "None",
                        tint = Color.White.copy(alpha = 0.9f),
                        modifier = Modifier.size((circleSize * 0.45f).coerceAtLeast(14.dp))
                    )
                }
            }
            option.id == "avatar" -> {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(
                            Brush.linearGradient(
                                colors = listOf(Color(0xFF3A3A3C), Color(0xFF8E8E93))
                            )
                        ),
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        imageVector = TablerIcons.CircleOff,
                        contentDescription = "Default",
                        tint = Color.White.copy(alpha = 0.9f),
                        modifier = Modifier.size((circleSize * 0.45f).coerceAtLeast(14.dp))
                    )
                }
            }
            option.colors.size == 1 -> {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(option.colors[0])
                )
            }
            option.colors.size >= 2 -> {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(
                            Brush.linearGradient(colors = option.colors)
                        )
                )
            }
        }

        // Галочка с затемнённым фоном (не для avatar/none — там уже иконка)
        if (isSelected && option.id != "avatar" && option.id != "none") {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.Black.copy(alpha = 0.25f)),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    painter = TelegramIcons.Done,
                    contentDescription = "Selected",
                    tint = Color.White,
                    modifier = Modifier.size((circleSize * 0.45f).coerceAtLeast(14.dp))
                )
            }
        }
    }
}

/**
 * Proper Gaussian blur via RenderScript — smooth, non-pixelated.
 * Mirrors edges to eliminate banding artifacts.
 */
@Suppress("deprecation")
private fun appearanceGaussianBlur(context: Context, source: Bitmap, radius: Float = 20f, passes: Int = 2): Bitmap {
    val w = (source.width / 3).coerceAtLeast(32)
    val h = (source.height / 3).coerceAtLeast(32)
    val scaled = Bitmap.createScaledBitmap(source, w, h, true)

    // Pad with mirrored edges to eliminate edge banding
    val pad = (radius * passes).toInt().coerceAtLeast(8)
    val paddedW = w + pad * 2
    val paddedH = h + pad * 2
    val padded = Bitmap.createBitmap(paddedW, paddedH, Bitmap.Config.ARGB_8888)
    val canvas = android.graphics.Canvas(padded)
    canvas.drawBitmap(scaled, pad.toFloat(), pad.toFloat(), null)

    for (x in 0 until pad) {
        for (y in 0 until h) {
            padded.setPixel(x, y + pad, scaled.getPixel((pad - x - 1).coerceIn(0, w - 1), y))
            padded.setPixel(paddedW - 1 - x, y + pad, scaled.getPixel((w - 1 - x.coerceIn(0, w - 1)), y))
        }
    }
    for (y in 0 until pad) {
        for (x in 0 until paddedW) {
            val srcX = (x - pad).coerceIn(0, w - 1)
            padded.setPixel(x, y, scaled.getPixel(srcX, (pad - y - 1).coerceIn(0, h - 1)))
            padded.setPixel(x, paddedH - 1 - y, scaled.getPixel(srcX, (h - 1 - y.coerceIn(0, h - 1))))
        }
    }

    var current = padded.copy(Bitmap.Config.ARGB_8888, true)

    val rs = RenderScript.create(context)
    val blur = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs))
    blur.setRadius(radius.coerceIn(1f, 25f))

    repeat(passes) {
        val input = Allocation.createFromBitmap(rs, current)
        val output = Allocation.createFromBitmap(rs, current)
        blur.setInput(input)
        blur.forEach(output)
        output.copyTo(current)
        input.destroy()
        output.destroy()
    }

    blur.destroy()
    rs.destroy()
    return Bitmap.createBitmap(current, pad, pad, w, h)
}
