package com.rosetta.messenger.ui.chats.components

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.net.Uri
import android.util.Log
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.runtime.getValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.foundation.*
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.zIndex
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.exifinterface.media.ExifInterface
import app.rosette.android.ui.keyboard.AnimatedKeyboardTransition
import app.rosette.android.ui.keyboard.rememberKeyboardTransitionCoordinator
import com.rosetta.messenger.ui.components.AppleEmojiTextField
import com.rosetta.messenger.ui.components.KeyboardHeightProvider
import com.rosetta.messenger.ui.components.OptimizedEmojiPicker
import com.rosetta.messenger.ui.onboarding.PrimaryBlue
import com.rosetta.messenger.ui.utils.SystemBarsStyleUtils
import com.yalantis.ucrop.UCrop
import compose.icons.TablerIcons
import compose.icons.tablericons.*
import com.rosetta.messenger.ui.icons.TelegramIcons
import ja.burhanrashid52.photoeditor.PhotoEditor
import ja.burhanrashid52.photoeditor.PhotoEditorView
import ja.burhanrashid52.photoeditor.SaveSettings
import java.io.File
import kotlin.coroutines.resume
import kotlin.math.abs
import kotlin.math.roundToInt
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext

private const val TAG = "ImageEditorScreen"

/** Linear interpolation between two values */
private fun lerp(start: Float, stop: Float, fraction: Float): Float = start + (stop - start) * fraction

/** Telegram-style easing */
private val TelegramEasing = CubicBezierEasing(0.25f, 0.1f, 0.25f, 1.0f)

/**
 * 📍 Data class для позиции thumbnail (для Telegram-style анимации)
 */
data class ThumbnailPosition(
    val x: Float,           // X позиция в окне
    val y: Float,           // Y позиция в окне  
    val width: Float,       // Ширина thumbnail
    val height: Float,      // Высота thumbnail
    val cornerRadius: Float = 4f  // Закругление углов (dp)
)

/** Available editing tools */
enum class EditorTool {
    NONE,
    DRAW,
    CROP,
    ROTATE,
    TEXT
}

/** Drawing colors - Telegram style palette */
val drawingColors = listOf(
    Color.White,
    Color.Black,
    Color(0xFFFF3B30), // Red
    Color(0xFFFF9500), // Orange
    Color(0xFFFFCC00), // Yellow
    Color(0xFF34C759), // Green
    Color(0xFF007AFF), // Blue
    Color(0xFF5856D6), // Purple
    Color(0xFFFF2D55), // Pink
)

/**
 * 📸 Telegram-style Image Editor Screen
 *
 * Features:
 * - Fullscreen edge-to-edge photo display
 * - Transparent overlay controls
 * - Smooth Telegram-style enter/exit animations
 * - Drawing, Crop, Rotate tools
 * - Caption input with send button
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ImageEditorScreen(
    imageUri: Uri,
    onDismiss: () -> Unit,
    onSave: (Uri) -> Unit,
    onSaveWithCaption: ((Uri, String) -> Unit)? = null,
    isDarkTheme: Boolean = true,
    showCaptionInput: Boolean = false,
    recipientName: String? = null,
    thumbnailPosition: ThumbnailPosition? = null, // Позиция для Telegram-style анимации
    skipEnterAnimation: Boolean = false // Из камеры — без fade, мгновенно
) {
    Dialog(
        onDismissRequest = onDismiss,
        properties = DialogProperties(
            dismissOnBackPress = false, // BackHandler handles this
            dismissOnClickOutside = false,
            usePlatformDefaultWidth = false,
            decorFitsSystemWindows = false
        )
    ) {
        // Configure Dialog window for fullscreen edge-to-edge
        val dialogView = LocalView.current
        SideEffect {
            val dialogWindow = (dialogView.parent as? androidx.compose.ui.window.DialogWindowProvider)?.window
                ?: (dialogView.context as? Activity)?.window
            dialogWindow?.let { win ->
                androidx.core.view.WindowCompat.setDecorFitsSystemWindows(win, false)
                win.statusBarColor = android.graphics.Color.BLACK
                win.navigationBarColor = android.graphics.Color.BLACK
                win.setWindowAnimations(0)
            }
        }

    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    val view = LocalView.current
    val focusManager = LocalFocusManager.current
    val density = LocalDensity.current
    val configuration = LocalConfiguration.current
    val screenWidth = configuration.screenWidthDp.dp
    val screenHeight = configuration.screenHeightDp.dp

    // ═══════════════════════════════════════════════════════════════
    // 🎬 TELEGRAM-STYLE ENTER/EXIT ANIMATION
    // ═══════════════════════════════════════════════════════════════
    var isClosing by remember { mutableStateOf(false) }
    val animationProgress = remember { Animatable(if (skipEnterAnimation) 1f else 0f) }
    
    // 🎬 Плавный easing для fade-out (как в Telegram)
    val smoothEasing = CubicBezierEasing(0.4f, 0.0f, 0.2f, 1.0f)
    
    // Запуск enter анимации (пропускаем если из камеры — уже alpha=1)
    LaunchedEffect(Unit) {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
        focusManager.clearFocus()

        if (!skipEnterAnimation) {
            animationProgress.animateTo(
                targetValue = 1f,
                animationSpec = tween(
                    durationMillis = 300,
                    easing = CubicBezierEasing(0.2f, 0.0f, 0.0f, 1.0f)
                )
            )
        }
    }
    
    // 🎨 System bars style
    val activity = context as? Activity
    val window = activity?.window
    val systemBarsState = remember(window, view) {
        SystemBarsStyleUtils.capture(window, view)
    }

    SideEffect {
        SystemBarsStyleUtils.applyFullscreenDark(window, view)
    }

    DisposableEffect(window, view, isDarkTheme, systemBarsState) {
        onDispose {
            SystemBarsStyleUtils.restoreChatAfterFullscreen(
                window = window,
                view = view,
                context = context,
                isDarkTheme = isDarkTheme,
                state = systemBarsState
            )
        }
    }

    // Функция для плавного закрытия
    fun animatedDismiss() {
        if (isClosing) return
        isClosing = true
        scope.launch {
            animationProgress.animateTo(
                targetValue = 0f,
                animationSpec = tween(
                    durationMillis = 350,  // 🎬 Более плавное закрытие
                    easing = smoothEasing
                )
            )
            onDismiss()
        }
    }

    // Editor state
    var currentTool by remember { mutableStateOf(EditorTool.NONE) }
    var selectedColor by remember { mutableStateOf(Color.White) }
    var brushSize by remember { mutableStateOf(12f) }
    var showColorPicker by remember { mutableStateOf(false) }
    var isSaving by remember { mutableStateOf(false) }
    var isEraserActive by remember { mutableStateOf(false) }

    // Caption state
    var caption by remember { mutableStateOf("") }

    // ═══════════════════════════════════════════════════════════════
    // 😀 EMOJI PICKER STATE - Telegram style с плавной анимацией
    // ═══════════════════════════════════════════════════════════════
    var showEmojiPicker by remember { mutableStateOf(false) }
    val coordinator = rememberKeyboardTransitionCoordinator()
    var editTextView by remember { mutableStateOf<com.rosetta.messenger.ui.components.AppleEmojiEditTextView?>(null) }
    var lastToggleTime by remember { mutableLongStateOf(0L) }
    val toggleCooldownMs = 500L

    // Отслеживание высоты клавиатуры
    val imeInsets = WindowInsets.ime
    var isKeyboardVisible by remember { mutableStateOf(false) }
    var lastStableKeyboardHeight by remember { mutableStateOf(0.dp) }

    // Update coordinator through snapshotFlow
    LaunchedEffect(Unit) {
        snapshotFlow { with(density) { imeInsets.getBottom(density).toDp() } }.collect { currentImeHeight ->
            val wasKeyboardVisible = isKeyboardVisible
            isKeyboardVisible = currentImeHeight > 50.dp
            coordinator.updateKeyboardHeight(currentImeHeight)
            if (currentImeHeight > 100.dp) {
                coordinator.syncHeights()
                lastStableKeyboardHeight = currentImeHeight
            }
            // 📊 Log IME height changes
            if (wasKeyboardVisible != isKeyboardVisible) {
            }
        }
    }

    // Load saved keyboard height
    LaunchedEffect(Unit) {
        KeyboardHeightProvider.getSavedKeyboardHeight(context)
    }

    // Save keyboard height when stable
    val isKeyboardVisibleForSave = WindowInsets.ime.getBottom(density) > 0
    LaunchedEffect(isKeyboardVisibleForSave, showEmojiPicker) {
        if (isKeyboardVisibleForSave && !showEmojiPicker) {
            delay(350)
            if (isKeyboardVisibleForSave && !showEmojiPicker && lastStableKeyboardHeight > 300.dp) {
                val heightPx = with(density) { lastStableKeyboardHeight.toPx().toInt() }
                KeyboardHeightProvider.saveKeyboardHeight(context, heightPx)
            }
        }
    }

    // Toggle emoji picker function
    fun toggleEmojiPicker() {
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastToggleTime < toggleCooldownMs) return
        lastToggleTime = currentTime

        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (coordinator.isEmojiVisible) {
            // EMOJI → KEYBOARD
            coordinator.requestShowKeyboard(
                showKeyboard = {
                    editTextView?.let { editText ->
                        editText.requestFocus()
                        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)
                    }
                },
                hideEmoji = { showEmojiPicker = false }
            )
        } else {
            // KEYBOARD → EMOJI
            coordinator.requestShowEmoji(
                hideKeyboard = { imm.hideSoftInputFromWindow(view.windowToken, 0) },
                showEmoji = { showEmojiPicker = true }
            )
        }
    }

    // Current image URI (can change after crop)
    var currentImageUri by remember { mutableStateOf(imageUri) }

    // Rotation state
    var rotationAngle by remember { mutableStateOf(0f) }
    var isFlippedHorizontally by remember { mutableStateOf(false) }
    var isFlippedVertically by remember { mutableStateOf(false) }

    // PhotoEditor reference
    var photoEditor by remember { mutableStateOf<PhotoEditor?>(null) }
    var photoEditorView by remember { mutableStateOf<PhotoEditorView?>(null) }

    // Track whether user made drawing edits (to skip PhotoEditor save when only cropping)
    var hasDrawingEdits by remember { mutableStateOf(false) }

    // UCrop launcher
    val cropLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.let { data ->
                UCrop.getOutput(data)?.let { croppedUri ->
                    currentImageUri = croppedUri
                }
            }
        }
    }

    // Загружаем изображение с корректным EXIF, чтобы в редакторе не было переворота/зеркала.
    LaunchedEffect(currentImageUri, photoEditorView) {
        val targetView = photoEditorView ?: return@LaunchedEffect
        val orientedBitmap = withContext(Dispatchers.IO) {
            loadBitmapRespectExif(context, currentImageUri)
        }
        orientedBitmap?.let { bitmap ->
            targetView.source.setImageBitmap(bitmap)
            targetView.source.scaleType = ImageView.ScaleType.FIT_CENTER
            targetView.source.adjustViewBounds = true
            targetView.source.setPadding(0, 0, 0, 0)
        }
    }

    BackHandler { animatedDismiss() }

    // ═══════════════════════════════════════════════════════════════
    // 🎬 ANIMATED CONTAINER - Telegram-style morph animation
    // ═══════════════════════════════════════════════════════════════
    val progress = animationProgress.value
    
    // Вычисляем анимированные значения
    val screenWidthPx = with(density) { screenWidth.toPx() }
    val screenHeightPx = with(density) { screenHeight.toPx() }
    
    // Если есть позиция thumbnail - делаем morph анимацию
    val animatedScale: Float
    val animatedTranslationX: Float
    val animatedTranslationY: Float
    val animatedCornerRadius: Float
    val animatedBackgroundAlpha: Float
    
    if (thumbnailPosition != null) {
        // Начальный масштаб (thumbnail → fullscreen)
        val startScale = thumbnailPosition.width / screenWidthPx
        animatedScale = startScale + (1f - startScale) * progress
        
        // Начальная позиция (центр thumbnail → центр экрана)
        val startX = thumbnailPosition.x + thumbnailPosition.width / 2 - screenWidthPx / 2
        val startY = thumbnailPosition.y + thumbnailPosition.height / 2 - screenHeightPx / 2
        animatedTranslationX = startX * (1f - progress)
        animatedTranslationY = startY * (1f - progress)
        
        // Закругление углов
        val cornerRadiusPx = with(density) { thumbnailPosition.cornerRadius.dp.toPx() }
        animatedCornerRadius = cornerRadiusPx * (1f - progress)
        
        // Альфа фона
        animatedBackgroundAlpha = progress
    } else {
        // ⚡ Простой fade - только opacity, без scale
        animatedScale = 1f
        animatedTranslationX = 0f
        animatedTranslationY = 0f
        animatedCornerRadius = 0f
        animatedBackgroundAlpha = progress
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .graphicsLayer { alpha = animatedBackgroundAlpha }
            .background(Color.Black)
            .zIndex(100f)
            .pointerInput(Unit) {
                awaitEachGesture {
                    val down = awaitFirstDown(requireUnconsumed = false)
                    down.consume()
                }
            }
    ) {
        Box(
            modifier =
                Modifier.fillMaxSize()
                    .graphicsLayer {
                        scaleX = animatedScale
                        scaleY = animatedScale
                        translationX = animatedTranslationX
                        translationY = animatedTranslationY
                        if (animatedCornerRadius > 0f) {
                            shape = RoundedCornerShape(animatedCornerRadius)
                            clip = true
                        }
                        alpha = animationProgress.value
                    }
        ) {
            // ═══════════════════════════════════════════════════════════
            // 📸 FULLSCREEN PHOTO - занимает ВЕСЬ экран, не реагирует на клавиатуру
            // ═══════════════════════════════════════════════════════════
            AndroidView(
                factory = { ctx ->
                    PhotoEditorView(ctx).apply {
                        photoEditorView = this

                        // Убираем отступы
                        setPadding(0, 0, 0, 0)
                        setBackgroundColor(android.graphics.Color.BLACK)

                        // Edge-to-edge: фото заполняет весь экран без чёрных полос
                        source.apply {
                            scaleType = ImageView.ScaleType.CENTER_CROP
                            adjustViewBounds = false
                            setPadding(0, 0, 0, 0)
                        }

                        photoEditor = PhotoEditor.Builder(ctx, this)
                            .setPinchTextScalable(true)
                            .setClipSourceImage(true)
                            .build()
                    }
                },
                update = { view ->
                    view.source.rotation = rotationAngle
                    view.source.scaleX = if (isFlippedHorizontally) -1f else 1f
                    view.source.scaleY = if (isFlippedVertically) -1f else 1f
                },
                // КРИТИЧНО: fillMaxSize без imePadding - фото НЕ сжимается при клавиатуре
                modifier = Modifier.fillMaxSize()
            )

        // TOP BAR
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .align(Alignment.TopCenter)
                .background(Color.Black)
                .statusBarsPadding()
                .padding(horizontal = 4.dp, vertical = 8.dp)
        ) {
            // Close button (X) - умное закрытие: клавиатура → emoji → экран
            IconButton(
                onClick = {
                    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

                    when {
                        // 1. Если emoji picker открыт - закрываем только его
                        showEmojiPicker -> {
                            showEmojiPicker = false
                        }
                        // 2. Если клавиатура открыта - закрываем только её
                        isKeyboardVisible -> {
                            imm.hideSoftInputFromWindow(view.windowToken, 0)
                            focusManager.clearFocus()
                        }
                        // 3. Иначе - выходим с экрана
                        else -> {
                            animatedDismiss()
                        }
                    }
                },
                modifier = Modifier.align(Alignment.CenterStart)
            ) {
                Icon(
                    painter = TelegramIcons.Close,
                    contentDescription = "Close",
                    tint = Color.White,
                    modifier = Modifier.size(28.dp)
                )
            }

            // Recipient name (center) - как в Telegram
            if (recipientName != null) {
                Text(
                    text = recipientName,
                    color = Color.White,
                    fontSize = 17.sp,
                    fontWeight = FontWeight.SemiBold,
                    maxLines = 1,
                    overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
                    modifier = Modifier
                        .align(Alignment.Center)
                        .padding(horizontal = 56.dp) // Отступы от кнопок
                )
            }

            // Undo / Redo buttons (center-right)
            Row(
                modifier = Modifier.align(Alignment.CenterEnd),
                horizontalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                IconButton(onClick = { photoEditor?.undo() }) {
                    Icon(
                        TablerIcons.ArrowBackUp,
                        contentDescription = "Undo",
                        tint = Color.White,
                        modifier = Modifier.size(26.dp)
                    )
                }
                IconButton(onClick = { photoEditor?.redo() }) {
                    Icon(
                        TablerIcons.ArrowForwardUp,
                        contentDescription = "Redo",
                        tint = Color.White,
                        modifier = Modifier.size(26.dp)
                    )
                }
            }
        }

        // ═══════════════════════════════════════════════════════════
        // 🎨 BOTTOM SECTION - TELEGRAM STYLE: всё overlay поверх фото!
        // Фото идёт ПОД toolbar и caption (они прозрачные)
        // ═══════════════════════════════════════════════════════════

        // Color picker (overlay)
        AnimatedVisibility(
            visible = currentTool == EditorTool.DRAW && showColorPicker,
            enter = slideInVertically(initialOffsetY = { it }) + fadeIn(),
            exit = slideOutVertically(targetOffsetY = { it }) + fadeOut(),
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(bottom = 140.dp) // над caption и toolbar
        ) {
            TelegramColorPicker(
                selectedColor = selectedColor,
                brushSize = brushSize,
                onColorSelected = { color ->
                    selectedColor = color
                    photoEditor?.brushColor = color.toArgb()
                },
                onBrushSizeChanged = { size ->
                    brushSize = size
                    photoEditor?.brushSize = size
                }
            )
        }

        // Rotate options (overlay)
        AnimatedVisibility(
            visible = currentTool == EditorTool.ROTATE,
            enter = slideInVertically(initialOffsetY = { it }) + fadeIn(),
            exit = slideOutVertically(targetOffsetY = { it }) + fadeOut(),
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(bottom = 140.dp)
        ) {
            TelegramRotateBar(
                onRotateLeft = { rotationAngle = (rotationAngle - 90f) % 360f },
                onRotateRight = { rotationAngle = (rotationAngle + 90f) % 360f },
                onFlipHorizontal = { isFlippedHorizontally = !isFlippedHorizontally },
                onFlipVertical = { isFlippedVertically = !isFlippedVertically }
            )
        }

        // ═══════════════════════════════════════════════════════════
        // 📝 CAPTION INPUT + EMOJI PICKER - Telegram style
        // Использует imePadding + AnimatedKeyboardTransition как в ChatDetailInput
        // ═══════════════════════════════════════════════════════════

        // 🔥 КЛЮЧЕВОЕ: imePadding применяется ТОЛЬКО когда emoji НЕ показан
        val shouldUseImePadding = !coordinator.isEmojiBoxVisible

        // 🔥 FIX: Сырое значение - emoji показан ИЛИ box виден
        val rawEmojiVisible = showEmojiPicker || coordinator.isEmojiBoxVisible

        // ═══════════════════════════════════════════════════════════════
        // 🎬 УПРОЩЁННАЯ АНИМАЦИЯ ИНПУТА
        // - Позиция: imePadding() + toolbarOffset (привязан к реальной высоте IME)
        // - Визуал: progress анимирует цвет, углы, иконки
        // ═══════════════════════════════════════════════════════════════

        // Состояние: развёрнуто когда клавиатура ИЛИ emoji видны
        val targetExpanded = isKeyboardVisible || rawEmojiVisible

        // Simple state-based padding (like ChatDetailInput)
        val shouldAddNavBarPadding = !isKeyboardVisible && !coordinator.isEmojiBoxVisible

        // Progress для ВИЗУАЛЬНЫХ изменений (цвет, углы, иконки)
        val visualProgress = remember { Animatable(0f) }
        LaunchedEffect(targetExpanded) {
            val targetValue = if (targetExpanded) 1f else 0f
            if (visualProgress.value != targetValue) {
                visualProgress.animateTo(
                    targetValue = targetValue,
                    animationSpec = tween(durationMillis = 250, easing = FastOutSlowInEasing)
                )
            }
        }

        AnimatedVisibility(
            visible = showCaptionInput && currentTool == EditorTool.NONE,
            enter = fadeIn(tween(200)) + expandVertically(expandFrom = Alignment.Bottom),
            exit = fadeOut(tween(150)) + shrinkVertically(shrinkTowards = Alignment.Bottom),
            modifier = Modifier
                .fillMaxWidth()
                .align(Alignment.BottomCenter)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    // Fixed padding: 0dp when keyboard/emoji shown, 100dp for toolbar when closed
                    .padding(bottom = if (isKeyboardVisible || rawEmojiVisible) 0.dp else 100.dp)
                    // imePadding for keyboard (only when emoji box not visible)
                    .then(if (shouldUseImePadding) Modifier.imePadding() else Modifier)
            ) {
                TelegramCaptionBar(
                    caption = caption,
                    onCaptionChange = { caption = it },
                    isSaving = isSaving,
                    // 🔥 Progress только для визуальных изменений (цвет, углы, иконки)
                    transitionProgress = visualProgress.value,
                    // Для иконки emoji/keyboard - используем актуальное состояние emoji
                    showEmojiPicker = rawEmojiVisible,
                    onToggleEmojiPicker = { toggleEmojiPicker() },
                    onEditTextViewCreated = { editTextView = it },
                    onSend = {
                        if (isSaving || isClosing) return@TelegramCaptionBar

                        val captionToSend = caption
                        val uriToSend = currentImageUri

                        scope.launch {
                            isSaving = true

                            val savedUri =
                                saveEditedImageSync(
                                    context = context,
                                    photoEditor = photoEditor,
                                    photoEditorView = photoEditorView,
                                    imageUri = uriToSend,
                                    hasDrawingEdits = hasDrawingEdits
                                )

                            isSaving = false

                            val finalUri = savedUri ?: uriToSend

                            // Сначала отправляем, затем закрываем экран
                            if (onSaveWithCaption != null) {
                                onSaveWithCaption(finalUri, captionToSend)
                            } else {
                                onSave(finalUri)
                            }

                            animatedDismiss()
                        }
                    }
                )

                // ═══════════════════════════════════════════════════════════
                // 🔥 EMOJI PICKER - используем AnimatedKeyboardTransition
                // Точно как в ChatDetailInput!
                // ═══════════════════════════════════════════════════════════
                AnimatedKeyboardTransition(
                    coordinator = coordinator,
                    showEmojiPicker = showEmojiPicker
                ) {
                    OptimizedEmojiPicker(
                        isVisible = true,
                        isDarkTheme = isDarkTheme,
                        onEmojiSelected = { emoji -> caption = caption + emoji },
                        onClose = { toggleEmojiPicker() },
                        modifier = Modifier.fillMaxWidth()
                    )
                }
            }
        }

        // ═══════════════════════════════════════════════════════════
        // 🛠️ TOOLBAR - показывается только когда клавиатура и emoji ЗАКРЫТЫ
        // ═══════════════════════════════════════════════════════════
        val isKeyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0

            AnimatedVisibility(
                visible = !isKeyboardOpen && !showEmojiPicker && !coordinator.isEmojiBoxVisible,
                enter = fadeIn() + slideInVertically { it },
                exit = fadeOut() + slideOutVertically { it },
                modifier = Modifier
                    .fillMaxWidth()
                    .align(Alignment.BottomCenter)
            ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(
                        Brush.verticalGradient(
                            colors = listOf(
                                Color.Transparent,
                                Color.Black.copy(alpha = 0.6f)
                            )
                        )
                    )
            ) {
                // Toolbar
                TelegramToolbar(
                    currentTool = currentTool,
                    showCaptionInput = showCaptionInput,
                    isSaving = isSaving,
                    isEraserActive = isEraserActive,
                    onCropClick = {
                        currentTool = EditorTool.NONE
                        showColorPicker = false
                        isEraserActive = false
                        photoEditor?.setBrushDrawingMode(false)
                        launchCrop(context, currentImageUri, cropLauncher)
                    },
                    onRotateClick = {
                        currentTool = if (currentTool == EditorTool.ROTATE) EditorTool.NONE else EditorTool.ROTATE
                        showColorPicker = false
                        isEraserActive = false
                        photoEditor?.setBrushDrawingMode(false)
                    },
                    onDrawClick = {
                        if (currentTool == EditorTool.DRAW) {
                            // Если ластик активен - переключаемся обратно на кисть
                            if (isEraserActive) {
                                isEraserActive = false
                                photoEditor?.setBrushDrawingMode(true)
                                photoEditor?.brushColor = selectedColor.toArgb()
                                photoEditor?.brushSize = brushSize
                            } else {
                                // Иначе показываем/скрываем color picker
                                showColorPicker = !showColorPicker
                            }
                        } else {
                            currentTool = EditorTool.DRAW
                            hasDrawingEdits = true
                            isEraserActive = false
                            photoEditor?.setBrushDrawingMode(true)
                            photoEditor?.brushColor = selectedColor.toArgb()
                            photoEditor?.brushSize = brushSize
                            showColorPicker = true
                        }
                    },
                    onEraserClick = {
                        isEraserActive = !isEraserActive
                        if (isEraserActive) {
                            photoEditor?.brushEraser()
                        } else {
                            // Возвращаемся к обычной кисти
                            photoEditor?.setBrushDrawingMode(true)
                            photoEditor?.brushColor = selectedColor.toArgb()
                            photoEditor?.brushSize = brushSize
                        }
                    },
                    onDrawDoneClick = {
                        // Принимаем изменения рисования и выходим из режима
                        currentTool = EditorTool.NONE
                        showColorPicker = false
                        isEraserActive = false
                        photoEditor?.setBrushDrawingMode(false)
                    },
                    onDoneClick = {
                        if (!showCaptionInput) {
                            scope.launch {
                                isSaving = true
                                val savedUri =
                                    saveEditedImageSync(
                                        context = context,
                                        photoEditor = photoEditor,
                                        photoEditorView = photoEditorView,
                                        imageUri = currentImageUri,
                                        hasDrawingEdits = hasDrawingEdits
                                    )
                                isSaving = false
                                onSave(savedUri ?: currentImageUri)
                            }
                        }
                    }
                )

                Spacer(modifier = Modifier.navigationBarsPadding())
            }
        }
    }
    }
    } // Dialog
}

/**
 * Telegram-style toolbar - icons only, no labels
 */
@Composable
internal fun TelegramToolbar(
    currentTool: EditorTool,
    showCaptionInput: Boolean,
    isSaving: Boolean,
    isEraserActive: Boolean = false,
    onCropClick: () -> Unit,
    onRotateClick: () -> Unit,
    onDrawClick: () -> Unit,
    onEraserClick: () -> Unit,
    onDrawDoneClick: () -> Unit = {},
    onDoneClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 8.dp, vertical = 12.dp),
        horizontalArrangement = Arrangement.SpaceEvenly,
        verticalAlignment = Alignment.CenterVertically
    ) {
        // Crop
        TelegramToolButton(
            icon = TablerIcons.Crop,
            isSelected = currentTool == EditorTool.CROP,
            onClick = onCropClick
        )

        // Rotate
        TelegramToolButton(
            icon = TablerIcons.Rotate,
            isSelected = currentTool == EditorTool.ROTATE,
            onClick = onRotateClick
        )

        // Draw
        TelegramToolButton(
            icon = TablerIcons.Pencil,
            isSelected = currentTool == EditorTool.DRAW && !isEraserActive,
            onClick = onDrawClick
        )

        // Eraser (visible when drawing) - подсвечивается синим когда активен
        AnimatedVisibility(
            visible = currentTool == EditorTool.DRAW,
            enter = scaleIn() + fadeIn(),
            exit = scaleOut() + fadeOut()
        ) {
            TelegramToolButton(
                icon = TablerIcons.Eraser,
                isSelected = isEraserActive,
                onClick = onEraserClick
            )
        }

        // ✅ Check button to accept drawing changes (visible when drawing)
        AnimatedVisibility(
            visible = currentTool == EditorTool.DRAW,
            enter = scaleIn() + fadeIn(),
            exit = scaleOut() + fadeOut()
        ) {
            IconButton(
                onClick = onDrawDoneClick,
                modifier = Modifier.size(48.dp)
            ) {
                Icon(
                    TablerIcons.Check,
                    contentDescription = "Accept drawing",
                    tint = Color(0xFF4CAF50), // Зелёный цвет для подтверждения
                    modifier = Modifier.size(26.dp)
                )
            }
        }

        // Done/Check button (if no caption input and not in draw mode)
        if (!showCaptionInput && currentTool != EditorTool.DRAW) {
            Spacer(modifier = Modifier.weight(1f))

            Box(
                modifier = Modifier
                    .size(48.dp)
                    .clip(CircleShape)
                    .background(PrimaryBlue)
                    .clickable(enabled = !isSaving) { onDoneClick() },
                contentAlignment = Alignment.Center
            ) {
                if (isSaving) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(22.dp),
                        color = Color.White,
                        strokeWidth = 2.dp
                    )
                } else {
                    Icon(
                        TablerIcons.Check,
                        contentDescription = "Done",
                        tint = Color.White,
                        modifier = Modifier.size(24.dp)
                    )
                }
            }
        }
    }
}

/**
 * Single tool button - Telegram style (no label)
 */
@Composable
private fun TelegramToolButton(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    IconButton(
        onClick = onClick,
        modifier = Modifier.size(48.dp)
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            tint = if (isSelected) PrimaryBlue else Color.White,
            modifier = Modifier.size(26.dp)
        )
    }
}

/**
 * Telegram-style color picker with brush size
 */
@Composable
internal fun TelegramColorPicker(
    selectedColor: Color,
    brushSize: Float,
    onColorSelected: (Color) -> Unit,
    onBrushSizeChanged: (Float) -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 12.dp)
    ) {
        // Brush size slider
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Box(
                modifier = Modifier
                    .size(8.dp)
                    .clip(CircleShape)
                    .background(selectedColor)
            )

            Slider(
                value = brushSize,
                onValueChange = onBrushSizeChanged,
                valueRange = 5f..40f,
                modifier = Modifier
                    .weight(1f)
                    .padding(horizontal = 12.dp),
                colors = SliderDefaults.colors(
                    thumbColor = selectedColor,
                    activeTrackColor = selectedColor,
                    inactiveTrackColor = Color.White.copy(alpha = 0.3f)
                )
            )

            Box(
                modifier = Modifier
                    .size(20.dp)
                    .clip(CircleShape)
                    .background(selectedColor)
            )
        }

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

        // Colors row
        LazyRow(
            horizontalArrangement = Arrangement.spacedBy(10.dp),
            contentPadding = PaddingValues(horizontal = 4.dp)
        ) {
            items(drawingColors) { color ->
                Box(
                    modifier = Modifier
                        .size(32.dp)
                        .clip(CircleShape)
                        .background(color)
                        .then(
                            if (color == selectedColor) {
                                Modifier.border(3.dp, Color.White, CircleShape)
                            } else {
                                Modifier.border(1.dp, Color.White.copy(alpha = 0.3f), CircleShape)
                            }
                        )
                        .clickable { onColorSelected(color) },
                    contentAlignment = Alignment.Center
                ) {
                    if (color == selectedColor) {
                        Icon(
                            TablerIcons.Check,
                            contentDescription = null,
                            tint = if (color == Color.White) Color.Black else Color.White,
                            modifier = Modifier.size(16.dp)
                        )
                    }
                }
            }
        }
    }
}

/**
 * Telegram-style rotate bar
 */
@Composable
internal fun TelegramRotateBar(
    onRotateLeft: () -> Unit,
    onRotateRight: () -> Unit,
    onFlipHorizontal: () -> Unit,
    onFlipVertical: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 12.dp),
        horizontalArrangement = Arrangement.SpaceEvenly,
        verticalAlignment = Alignment.CenterVertically
    ) {
        TelegramToolButton(
            icon = TablerIcons.RotateClockwise2,
            isSelected = false,
            onClick = onRotateLeft
        )

        TelegramToolButton(
            icon = TablerIcons.Rotate2,
            isSelected = false,
            onClick = onRotateRight
        )

        TelegramToolButton(
            icon = TablerIcons.FlipHorizontal,
            isSelected = false,
            onClick = onFlipHorizontal
        )

        TelegramToolButton(
            icon = TablerIcons.FlipVertical,
            isSelected = false,
            onClick = onFlipVertical
        )
    }
}

/**
 * Telegram-style caption input bar with emoji support
 * Использует единый transitionProgress для синхронной анимации всех параметров:
 * - 0f = компактный режим (клавиатура закрыта, "Add a caption" капсула)
 * - 1f = развёрнутый режим (клавиатура/emoji открыты, полный инпут)
 */
@Composable
private fun TelegramCaptionBar(
    caption: String,
    onCaptionChange: (String) -> Unit,
    isSaving: Boolean,
    transitionProgress: Float, // 0f = compact, 1f = expanded
    showEmojiPicker: Boolean = false,
    onToggleEmojiPicker: () -> Unit = {},
    onEditTextViewCreated: ((com.rosetta.messenger.ui.components.AppleEmojiEditTextView) -> Unit)? = null,
    onSend: () -> Unit
) {
    // 🎬 Все параметры вычисляются через единый progress для идеальной синхронизации
    val progress = transitionProgress

    // Corner radius: 24dp (compact) → 0dp (expanded)
    val cornerRadius = lerp(24f, 0f, progress).dp

    // Horizontal padding: 12dp (compact) → 0dp (expanded)
    val horizontalPadding = lerp(12f, 0f, progress).dp

    // Background alpha: 0.85f (compact) → 0.75f (expanded)
    val backgroundAlpha = lerp(0.85f, 0.75f, progress)

    // Background color: interpolate between compact and expanded colors
    val compactColor = Color(0xFF2C2C2E)
    val expandedColor = Color.Black
    val backgroundColor = androidx.compose.ui.graphics.lerp(compactColor, expandedColor, progress)

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = horizontalPadding)
            // 🔥 FIX: Единый фон с анимированными параметрами - без мигания!
            .clip(RoundedCornerShape(cornerRadius))
            .background(backgroundColor.copy(alpha = backgroundAlpha))
            .padding(horizontal = 12.dp, vertical = 10.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(10.dp)
        ) {
            // 🎬 Левая иконка: плавная анимация через alpha
            // Emoji/Keyboard toggle - всегда виден
            Box(
                modifier = Modifier.size(32.dp),
                contentAlignment = Alignment.Center
            ) {
                // Emoji/Keyboard toggle
                IconButton(
                    onClick = onToggleEmojiPicker,
                    modifier = Modifier.size(32.dp)
                ) {
                    Icon(
                        painter = if (showEmojiPicker) TelegramIcons.Keyboard else TelegramIcons.Smile,
                        contentDescription = if (showEmojiPicker) "Keyboard" else "Emoji",
                        tint = Color.White.copy(alpha = 0.7f),
                        modifier = Modifier.size(26.dp)
                    )
                }
            }

            // Caption text field - использует AppleEmojiTextField для правильной работы с фокусом
            // 🎬 Высота через lerp для синхронной анимации
            val textFieldMaxHeight = lerp(24f, 100f, progress).dp

            Box(
                modifier = Modifier
                    .weight(1f)
                    .heightIn(min = 24.dp, max = textFieldMaxHeight)
            ) {
                AppleEmojiTextField(
                    value = caption,
                    onValueChange = onCaptionChange,
                    textColor = Color.White,
                    textSize = 16f,
                    hint = "Add a caption...",
                    hintColor = Color.White.copy(alpha = 0.5f),
                    modifier = Modifier.fillMaxWidth(),
                    requestFocus = false,
                    onViewCreated = { view -> onEditTextViewCreated?.invoke(view) },
                    onFocusChanged = { hasFocus ->
                        // Если получили фокус и emoji открыт - закрываем emoji
                        if (hasFocus && showEmojiPicker) {
                            onToggleEmojiPicker()
                        }
                    }
                )
            }

            // 🎬 Кнопка отправки: плавная анимация размера и иконки через progress
            // Размер: 36dp (compact) → 32dp (expanded)
            val buttonSize = lerp(36f, 32f, progress).dp
            val iconSize = lerp(22f, 20f, progress).dp
            val progressIndicatorSize = lerp(20f, 18f, progress).dp

            Box(
                modifier = Modifier
                    .size(buttonSize)
                    .clip(CircleShape)
                    .background(PrimaryBlue)
                    .clickable(enabled = !isSaving) { onSend() },
                contentAlignment = Alignment.Center
            ) {
                if (isSaving) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(progressIndicatorSize),
                        color = Color.White,
                        strokeWidth = 2.dp
                    )
                } else {
                    // Плавное переключение иконок через alpha
                    Box(contentAlignment = Alignment.Center) {
                        // Стрелка отправки - видна когда compact (progress близок к 0)
                        Icon(
                            TablerIcons.ArrowUp,
                            contentDescription = "Send",
                            tint = Color.White.copy(alpha = 1f - progress),
                            modifier = Modifier
                                .size(iconSize)
                                .graphicsLayer { alpha = 1f - progress }
                        )
                        // Галочка - видна когда expanded (progress близок к 1)
                        Icon(
                            TablerIcons.Check,
                            contentDescription = "Done",
                            tint = Color.White.copy(alpha = progress),
                            modifier = Modifier
                                .size(iconSize)
                                .graphicsLayer { alpha = progress }
                        )
                    }
                }
            }
        }
    }
}

/** Save edited image and return the URI (with all editor changes). */
private suspend fun saveEditedImage(
    context: Context,
    photoEditor: PhotoEditor?,
    photoEditorView: PhotoEditorView?,
    imageUri: Uri,
    onResult: (Uri?) -> Unit
) {
    saveEditedImageOld(
        context = context,
        photoEditor = photoEditor,
        photoEditorView = photoEditorView,
        imageUri = imageUri,
        onResult = onResult
    )
}

/** OLD VERSION - Save edited image with crop logic (disabled due to cropping issues) */
@Suppress("unused")
private suspend fun saveEditedImageOld(
    context: Context,
    photoEditor: PhotoEditor?,
    photoEditorView: PhotoEditorView?,
    imageUri: Uri,
    onResult: (Uri?) -> Unit
) {
    if (photoEditor == null || photoEditorView == null) {
        // Нет редактора - возвращаем оригинал
        onResult(imageUri)
        return
    }

    try {
        val tempFile = File(context.cacheDir, "edited_${System.currentTimeMillis()}.jpg")
        val saveSettings = SaveSettings.Builder()
            .setClearViewsEnabled(false)
            .setTransparencyEnabled(false)
            .setCompressFormat(Bitmap.CompressFormat.JPEG)
            .setCompressQuality(95)
            .build()

        val savedPath = suspendCancellableCoroutine<String?> { continuation ->
            photoEditor.saveAsFile(
                tempFile.absolutePath,
                saveSettings,
                object : PhotoEditor.OnSaveListener {
                    override fun onSuccess(imagePath: String) {
                        continuation.resume(imagePath)
                    }
                    override fun onFailure(exception: Exception) {
                        continuation.resume(null)
                    }
                }
            )
        }

        val rawResultUri = savedPath?.let { Uri.fromFile(File(it)) } ?: imageUri
        val normalizedUri =
            if (rawResultUri != imageUri) {
                removeLetterboxFromEditedImage(
                    context = context,
                    editedUri = rawResultUri,
                    sourceUri = imageUri
                ) ?: rawResultUri
            } else {
                rawResultUri
            }
        onResult(normalizedUri)
    } catch (e: Exception) {
        onResult(imageUri)
    }
}

/** Save edited image synchronously (with all editor changes). */
internal suspend fun saveEditedImageSync(
    context: Context,
    photoEditor: PhotoEditor?,
    photoEditorView: PhotoEditorView?,
    imageUri: Uri,
    hasDrawingEdits: Boolean = false
): Uri? {
    // No drawing edits — return the source URI directly (clean crop from UCrop, no letterbox)
    if (!hasDrawingEdits) {
        return imageUri
    }
    return saveEditedImageSyncOld(
        context = context,
        photoEditor = photoEditor,
        photoEditorView = photoEditorView,
        imageUri = imageUri
    )
}

/** Save edited image synchronously - OLD VERSION with crop logic (disabled) */
@Suppress("unused")
private suspend fun saveEditedImageSyncOld(
    context: Context,
    photoEditor: PhotoEditor?,
    photoEditorView: PhotoEditorView?,
    imageUri: Uri
): Uri? {
    if (photoEditor == null || photoEditorView == null) {
        // Нет редактора - возвращаем оригинал
        return imageUri
    }

    return try {
        val tempFile = File(
            context.cacheDir,
            "edited_${System.currentTimeMillis()}_${(0..9999).random()}.jpg"
        )

        val saveSettings = SaveSettings.Builder()
            .setClearViewsEnabled(false)
            .setTransparencyEnabled(false)
            .setCompressFormat(Bitmap.CompressFormat.JPEG)
            .setCompressQuality(95)
            .build()

        val savedPath = suspendCancellableCoroutine<String?> { continuation ->
            photoEditor.saveAsFile(
                tempFile.absolutePath,
                saveSettings,
                object : PhotoEditor.OnSaveListener {
                    override fun onSuccess(imagePath: String) {
                        continuation.resume(imagePath)
                    }
                    override fun onFailure(exception: Exception) {
                        continuation.resume(null)
                    }
                }
            )
        }

        val rawResultUri = savedPath?.let { Uri.fromFile(File(it)) } ?: imageUri
        if (rawResultUri == imageUri) {
            rawResultUri
        } else {
            removeLetterboxFromEditedImage(
                context = context,
                editedUri = rawResultUri,
                sourceUri = imageUri
            ) ?: rawResultUri
        }
    } catch (e: Exception) {
        imageUri
    }
}

/**
 * Removes black/transparent letterbox bars produced by PhotoEditor fullscreen save
 * by cropping to the source image aspect ratio inside edited bitmap bounds.
 */
private suspend fun removeLetterboxFromEditedImage(
    context: Context,
    editedUri: Uri,
    sourceUri: Uri
): Uri? = withContext(Dispatchers.IO) {
    runCatching {
        val editedFile = File(editedUri.path ?: return@runCatching null)
        if (!editedFile.exists()) return@runCatching null

        val editedBitmap = BitmapFactory.decodeFile(editedFile.absolutePath) ?: return@runCatching null
        val editedWidth = editedBitmap.width
        val editedHeight = editedBitmap.height
        if (editedWidth <= 0 || editedHeight <= 0) {
            editedBitmap.recycle()
            return@runCatching null
        }

        val (sourceWidth, sourceHeight) = getOrientedImageDimensions(context, sourceUri)
        if (sourceWidth <= 0 || sourceHeight <= 0) {
            editedBitmap.recycle()
            return@runCatching null
        }

        val scale = minOf(
            editedWidth / sourceWidth.toFloat(),
            editedHeight / sourceHeight.toFloat()
        )
        val expectedContentWidth = (sourceWidth * scale).roundToInt().coerceAtLeast(1)
        val expectedContentHeight = (sourceHeight * scale).roundToInt().coerceAtLeast(1)

        val left = ((editedWidth - expectedContentWidth) / 2f).roundToInt().coerceAtLeast(0)
        val top = ((editedHeight - expectedContentHeight) / 2f).roundToInt().coerceAtLeast(0)
        val cropWidth = expectedContentWidth.coerceAtMost(editedWidth - left)
        val cropHeight = expectedContentHeight.coerceAtMost(editedHeight - top)

        // Nothing to crop
        if (
            left <= 1 &&
                top <= 1 &&
                abs(cropWidth - editedWidth) <= 1 &&
                abs(cropHeight - editedHeight) <= 1
        ) {
            editedBitmap.recycle()
            return@runCatching editedUri
        }

        // Safety guard: only skip if crop is unreasonably small (< 5% of area)
        if (cropWidth < 10 || cropHeight < 10 ||
            (cropWidth.toLong() * cropHeight.toLong()) < (editedWidth.toLong() * editedHeight.toLong()) / 20
        ) {
            editedBitmap.recycle()
            return@runCatching editedUri
        }

        val cropped =
            Bitmap.createBitmap(
                editedBitmap,
                left,
                top,
                cropWidth.coerceAtMost(editedBitmap.width - left),
                cropHeight.coerceAtMost(editedBitmap.height - top)
            )
        editedBitmap.recycle()

        val normalizedFile =
            File(
                context.cacheDir,
                "edited_normalized_${System.currentTimeMillis()}_${(0..9999).random()}.jpg"
            )
        normalizedFile.outputStream().use { out ->
            cropped.compress(Bitmap.CompressFormat.JPEG, 95, out)
            out.flush()
        }
        cropped.recycle()

        Uri.fromFile(normalizedFile)
    }.getOrNull()
}

private fun getOrientedImageDimensions(context: Context, uri: Uri): Pair<Int, Int> {
    return try {
        val boundsOptions = BitmapFactory.Options().apply { inJustDecodeBounds = true }
        context.contentResolver.openInputStream(uri)?.use { input ->
            BitmapFactory.decodeStream(input, null, boundsOptions)
        }

        var width = boundsOptions.outWidth
        var height = boundsOptions.outHeight
        if (width <= 0 || height <= 0) return Pair(0, 0)

        val orientation = readExifOrientation(context, uri)
        val needsSwap =
            orientation == ExifInterface.ORIENTATION_ROTATE_90 ||
                orientation == ExifInterface.ORIENTATION_ROTATE_270 ||
                orientation == ExifInterface.ORIENTATION_TRANSPOSE ||
                orientation == ExifInterface.ORIENTATION_TRANSVERSE

        if (needsSwap) {
            val temp = width
            width = height
            height = temp
        }
        Pair(width, height)
    } catch (_: Exception) {
        Pair(0, 0)
    }
}

/** Launch UCrop activity */
internal fun launchCrop(
    context: Context,
    sourceUri: Uri,
    launcher: androidx.activity.result.ActivityResultLauncher<Intent>
) {
    try {
        val destinationFile = File(context.cacheDir, "cropped_${System.currentTimeMillis()}.jpg")
        val destinationUri = Uri.fromFile(destinationFile)

        val options = UCrop.Options().apply {
            setCompressionFormat(Bitmap.CompressFormat.JPEG)
            setCompressionQuality(95)
            // Dark theme
            setToolbarColor(android.graphics.Color.BLACK)
            setStatusBarColor(android.graphics.Color.BLACK)
            setActiveControlsWidgetColor(android.graphics.Color.parseColor("#007AFF"))
            setToolbarWidgetColor(android.graphics.Color.WHITE)
            setRootViewBackgroundColor(android.graphics.Color.WHITE)
            setFreeStyleCropEnabled(true)
            setShowCropGrid(true)
            setShowCropFrame(true)
            setHideBottomControls(false)
        }

        val intent = UCrop.of(sourceUri, destinationUri).withOptions(options).getIntent(context)
        launcher.launch(intent)
    } catch (e: Exception) {
        // Handle error
    }
}

/** Data class for image with caption */
data class ImageWithCaption(val uri: Uri, var caption: String = "")

/**
 * 📸 Multi-image editor with swipe (Telegram style)
 */
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun MultiImageEditorScreen(
    imageUris: List<Uri>,
    onDismiss: () -> Unit,
    onSendAll: (List<ImageWithCaption>) -> Unit,
    isDarkTheme: Boolean = true,
    recipientName: String? = null // Имя получателя (как в Telegram)
) {
    Dialog(
        onDismissRequest = onDismiss,
        properties = DialogProperties(
            dismissOnBackPress = false,
            dismissOnClickOutside = false,
            usePlatformDefaultWidth = false,
            decorFitsSystemWindows = false
        )
    ) {
        val dialogView = LocalView.current
        SideEffect {
            val dialogWindow = (dialogView.parent as? androidx.compose.ui.window.DialogWindowProvider)?.window
                ?: (dialogView.context as? Activity)?.window
            dialogWindow?.let { win ->
                androidx.core.view.WindowCompat.setDecorFitsSystemWindows(win, false)
                win.statusBarColor = android.graphics.Color.BLACK
                win.navigationBarColor = android.graphics.Color.BLACK
                win.setWindowAnimations(0)
            }
        }

    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    val view = LocalView.current
    val focusManager = LocalFocusManager.current

    // ═══════════════════════════════════════════════════════════════
    // 🎬 TELEGRAM-STYLE FADE ANIMATION
    // ═══════════════════════════════════════════════════════════════
    var isClosing by remember { mutableStateOf(false) }
    val animationProgress = remember { Animatable(0f) }
    
    // Запуск enter анимации
    LaunchedEffect(Unit) {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
        focusManager.clearFocus()

        animationProgress.animateTo(
            targetValue = 1f,
            animationSpec = tween(
                durationMillis = 250,
                easing = FastOutSlowInEasing
            )
        )
    }
    
    // 🎬 Плавный easing для fade-out
    val smoothEasing = CubicBezierEasing(0.4f, 0.0f, 0.2f, 1.0f)
    
    // Функция для плавного закрытия - простой быстрый fade-out
    fun animatedDismiss() {
        if (isClosing) return
        isClosing = true
        scope.launch {
            animationProgress.animateTo(
                targetValue = 0f,
                animationSpec = tween(
                    durationMillis = 150,  // ⚡ Быстрый fade-out
                    easing = LinearEasing
                )
            )
            onDismiss()
        }
    }

    // 🎨 System bars style
    val activity = context as? Activity
    val window = activity?.window
    val systemBarsState = remember(window, view) {
        SystemBarsStyleUtils.capture(window, view)
    }

    SideEffect {
        SystemBarsStyleUtils.applyFullscreenDark(window, view)
    }

    DisposableEffect(window, view, isDarkTheme, systemBarsState) {
        onDispose {
            SystemBarsStyleUtils.restoreChatAfterFullscreen(
                window = window,
                view = view,
                context = context,
                isDarkTheme = isDarkTheme,
                state = systemBarsState
            )
        }
    }

    val imagesWithCaptions = remember {
        mutableStateListOf<ImageWithCaption>().apply {
            addAll(imageUris.map { ImageWithCaption(it, "") })
        }
    }

    val pagerState = rememberPagerState(initialPage = 0, pageCount = { imagesWithCaptions.size })

    var isSaving by remember { mutableStateOf(false) }
    var currentTool by remember { mutableStateOf(EditorTool.NONE) }
    var selectedColor by remember { mutableStateOf(Color.White) }
    var brushSize by remember { mutableFloatStateOf(12f) }
    var showColorPicker by remember { mutableStateOf(false) }

    val photoEditors = remember { mutableStateMapOf<Int, PhotoEditor?>() }
    val photoEditorViews = remember { mutableStateMapOf<Int, PhotoEditorView?>() }
    val drawingEditPages = remember { mutableSetOf<Int>() }

    val cropLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.let { data ->
                UCrop.getOutput(data)?.let { croppedUri ->
                    val currentPage = pagerState.currentPage
                    if (currentPage < imagesWithCaptions.size) {
                        imagesWithCaptions[currentPage] = imagesWithCaptions[currentPage].copy(uri = croppedUri)
                    }
                }
            }
        }
    }

    LaunchedEffect(pagerState.currentPage) {
        currentTool = EditorTool.NONE
        showColorPicker = false
    }

    LaunchedEffect(selectedColor, brushSize) {
        val currentPage = pagerState.currentPage
        photoEditors[currentPage]?.let { editor ->
            if (currentTool == EditorTool.DRAW) {
                editor.brushColor = selectedColor.toArgb()
                editor.brushSize = brushSize
            }
        }
    }

    BackHandler { animatedDismiss() }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black)
            .zIndex(100f)
    ) {
        Box(
            modifier =
                Modifier.fillMaxSize()
                    .graphicsLayer { alpha = animationProgress.value }
        ) {
            // Pager
            HorizontalPager(
                state = pagerState,
                modifier = Modifier.fillMaxSize(),
                userScrollEnabled = currentTool == EditorTool.NONE
            ) { page ->
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    AndroidView(
                        factory = { ctx ->
                            PhotoEditorView(ctx).apply {
                                photoEditorViews[page] = this

                                setPadding(0, 0, 0, 0)
                                setBackgroundColor(android.graphics.Color.BLACK)

                                // Инициализация PhotoEditor синхронно в factory (уже на main thread)
                                val editor = PhotoEditor.Builder(ctx, this)
                                    .setPinchTextScalable(true)
                                    .setClipSourceImage(true)
                                    .build()
                                photoEditors[page] = editor

                                // Загружаем изображение асинхронно
                                scope.launch(Dispatchers.IO) {
                                    try {
                                        val bitmap = loadBitmapRespectExif(ctx, imagesWithCaptions[page].uri)

                                        withContext(Dispatchers.Main) {
                                            source.apply {
                                                if (bitmap != null) {
                                                    setImageBitmap(bitmap)
                                                }
                                                scaleType = ImageView.ScaleType.FIT_CENTER
                                                adjustViewBounds = true
                                                setPadding(0, 0, 0, 0)
                                            }
                                        }
                                    } catch (e: Exception) {
                                        // Handle error
                                    }
                                }
                            }
                        },
                        modifier = Modifier.fillMaxSize(),
                        update = { view ->
                            val currentUri = imagesWithCaptions.getOrNull(page)?.uri
                            if (currentUri != null) {
                                scope.launch(Dispatchers.IO) {
                                    try {
                                        val bitmap = loadBitmapRespectExif(context, currentUri)

                                        withContext(Dispatchers.Main) {
                                            if (bitmap != null) {
                                                view.source.setImageBitmap(bitmap)
                                            }
                                            view.source.scaleType = ImageView.ScaleType.FIT_CENTER
                                            view.source.adjustViewBounds = true
                                        }
                                    } catch (e: Exception) {
                                        // Handle error
                                    }
                                }
                            }
                        }
                    )
                }
            }

        // Top bar
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .align(Alignment.TopCenter)
                .background(Color.Black)
                .statusBarsPadding()
                .padding(horizontal = 4.dp, vertical = 8.dp)
        ) {
            IconButton(
                onClick = { animatedDismiss() },
                modifier = Modifier.align(Alignment.CenterStart)
            ) {
                Icon(
                    painter = TelegramIcons.Close,
                    contentDescription = "Close",
                    tint = Color.White,
                    modifier = Modifier.size(28.dp)
                )
            }

            // Recipient name (center) - как в Telegram
            if (recipientName != null) {
                Text(
                    text = recipientName,
                    color = Color.White,
                    fontSize = 17.sp,
                    fontWeight = FontWeight.SemiBold,
                    maxLines = 1,
                    overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
                    modifier = Modifier
                        .align(Alignment.Center)
                        .padding(horizontal = 56.dp)
                )
            }

            if (currentTool == EditorTool.DRAW) {
                IconButton(
                    onClick = { photoEditors[pagerState.currentPage]?.undo() },
                    modifier = Modifier.align(Alignment.CenterEnd)
                ) {
                    Icon(
                        TablerIcons.ArrowBackUp,
                        contentDescription = "Undo",
                        tint = Color.White,
                        modifier = Modifier.size(26.dp)
                    )
                }
            }
        }

        // Bottom section
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .align(Alignment.BottomCenter)
                .background(
                    Brush.verticalGradient(
                        colors = listOf(
                            Color.Transparent,
                            Color.Black.copy(alpha = 0.7f)
                        )
                    )
                )
        ) {
            // Color picker
            AnimatedVisibility(
                visible = showColorPicker && currentTool == EditorTool.DRAW,
                enter = slideInVertically(initialOffsetY = { it }) + fadeIn(),
                exit = slideOutVertically(targetOffsetY = { it }) + fadeOut()
            ) {
                TelegramColorPicker(
                    selectedColor = selectedColor,
                    brushSize = brushSize,
                    onColorSelected = { color ->
                        selectedColor = color
                        photoEditors[pagerState.currentPage]?.brushColor = color.toArgb()
                    },
                    onBrushSizeChanged = { size ->
                        brushSize = size
                        photoEditors[pagerState.currentPage]?.brushSize = size
                    }
                )
            }

            // Thumbnails strip
            if (imagesWithCaptions.size > 1 && currentTool == EditorTool.NONE) {
                LazyRow(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 12.dp, vertical = 8.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    items(imagesWithCaptions.size) { index ->
                        val isSelected = pagerState.currentPage == index
                        Box(
                            modifier = Modifier
                                .size(56.dp)
                                .clip(RoundedCornerShape(8.dp))
                                .border(
                                    width = if (isSelected) 2.dp else 0.dp,
                                    color = if (isSelected) PrimaryBlue else Color.Transparent,
                                    shape = RoundedCornerShape(8.dp)
                                )
                                .clickable {
                                    scope.launch {
                                        pagerState.animateScrollToPage(index)
                                    }
                                }
                        ) {
                            AsyncImageLoader(
                                uri = imagesWithCaptions[index].uri,
                                modifier = Modifier.fillMaxSize()
                            )
                        }
                    }
                }
            }

            // Toolbar
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 8.dp, vertical = 12.dp),
                horizontalArrangement = Arrangement.SpaceEvenly,
                verticalAlignment = Alignment.CenterVertically
            ) {
                TelegramToolButton(
                    icon = TablerIcons.Crop,
                    isSelected = false,
                    onClick = {
                        currentTool = EditorTool.NONE
                        showColorPicker = false
                        photoEditors[pagerState.currentPage]?.setBrushDrawingMode(false)
                        launchCrop(context, imagesWithCaptions[pagerState.currentPage].uri, cropLauncher)
                    }
                )

                TelegramToolButton(
                    icon = TablerIcons.Pencil,
                    isSelected = currentTool == EditorTool.DRAW,
                    onClick = {
                        val currentEditor = photoEditors[pagerState.currentPage]
                        if (currentTool == EditorTool.DRAW) {
                            showColorPicker = !showColorPicker
                        } else {
                            currentTool = EditorTool.DRAW
                            drawingEditPages.add(pagerState.currentPage)
                            currentEditor?.setBrushDrawingMode(true)
                            currentEditor?.brushColor = selectedColor.toArgb()
                            currentEditor?.brushSize = brushSize
                            showColorPicker = true
                        }
                    }
                )

                AnimatedVisibility(
                    visible = currentTool == EditorTool.DRAW,
                    enter = scaleIn() + fadeIn(),
                    exit = scaleOut() + fadeOut()
                ) {
                    TelegramToolButton(
                        icon = TablerIcons.Eraser,
                        isSelected = false,
                        onClick = { photoEditors[pagerState.currentPage]?.brushEraser() }
                    )
                }

                Spacer(modifier = Modifier.weight(1f))

                // Send button
                Box(
                    modifier = Modifier
                        .size(48.dp)
                        .clip(CircleShape)
                        .background(PrimaryBlue)
                        .clickable(enabled = !isSaving && !isClosing) {
                            val imagesToSend = imagesWithCaptions.toList()

                            scope.launch {
                                isSaving = true
                                val savedImages = mutableListOf<ImageWithCaption>()

                                for (i in imagesToSend.indices) {
                                    val editor = photoEditors[i]
                                    val editorView = photoEditorViews[i]
                                    val originalImage = imagesToSend[i]

                                    if (editor != null) {
                                        val savedUri = saveEditedImageSync(context, editor, editorView, originalImage.uri, hasDrawingEdits = i in drawingEditPages)
                                        if (savedUri != null) {
                                            savedImages.add(originalImage.copy(uri = savedUri))
                                        } else {
                                            savedImages.add(originalImage)
                                        }
                                    } else {
                                        savedImages.add(originalImage)
                                    }
                                }

                                onSendAll(savedImages)
                                isSaving = false
                                animatedDismiss()
                            }
                        },
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        TablerIcons.ArrowUp,
                        contentDescription = "Send",
                        tint = Color.White,
                        modifier = Modifier.size(22.dp)
                    )
                }
            }

            Spacer(modifier = Modifier.navigationBarsPadding())
        }
        }
    }
    } // Dialog
}

private fun loadBitmapRespectExif(context: Context, uri: Uri): Bitmap? {
    return try {
        val orientation = readExifOrientation(context, uri)
        val decodedBitmap =
            context.contentResolver.openInputStream(uri)?.use { input ->
                BitmapFactory.decodeStream(input)
            } ?: return null
        applyExifOrientation(decodedBitmap, orientation)
    } catch (_: Exception) {
        null
    }
}

private fun readExifOrientation(context: Context, uri: Uri): Int {
    return try {
        context.contentResolver.openInputStream(uri)?.use { input ->
            ExifInterface(input).getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL
            )
        } ?: ExifInterface.ORIENTATION_NORMAL
    } catch (_: Exception) {
        ExifInterface.ORIENTATION_NORMAL
    }
}

private fun applyExifOrientation(bitmap: Bitmap, orientation: Int): Bitmap {
    val matrix = Matrix()
    when (orientation) {
        ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90f)
        ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180f)
        ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270f)
        ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.preScale(-1f, 1f)
        ExifInterface.ORIENTATION_FLIP_VERTICAL -> matrix.preScale(1f, -1f)
        ExifInterface.ORIENTATION_TRANSPOSE -> {
            matrix.postRotate(90f)
            matrix.preScale(-1f, 1f)
        }
        ExifInterface.ORIENTATION_TRANSVERSE -> {
            matrix.postRotate(270f)
            matrix.preScale(-1f, 1f)
        }
        else -> return bitmap
    }

    return try {
        Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true).also {
            if (it != bitmap) bitmap.recycle()
        }
    } catch (_: Exception) {
        bitmap
    }
}

/** Async image loader */
@Composable
private fun AsyncImageLoader(uri: Uri, modifier: Modifier = Modifier) {
    val context = LocalContext.current
    var bitmap by remember(uri) { mutableStateOf<android.graphics.Bitmap?>(null) }

    LaunchedEffect(uri) {
        withContext(Dispatchers.IO) {
            try {
                val inputStream = context.contentResolver.openInputStream(uri)
                bitmap = BitmapFactory.decodeStream(inputStream)
                inputStream?.close()
            } catch (e: Exception) {
                // Handle error
            }
        }
    }

    bitmap?.let { bmp ->
        Image(
            bitmap = bmp.asImageBitmap(),
            contentDescription = null,
            modifier = modifier,
            contentScale = ContentScale.Crop
        )
    } ?: Box(
        modifier = modifier.background(Color.DarkGray),
        contentAlignment = Alignment.Center
    ) {
        CircularProgressIndicator(
            modifier = Modifier.size(24.dp),
            color = Color.White,
            strokeWidth = 2.dp
        )
    }
}
