Загрузка данных


package com.example.monika

import android.content.Context
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.core.*
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.foundation.shape.*
import androidx.compose.foundation.text.ClickableText
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.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.google.ai.client.generativeai.GenerativeModel
import com.google.ai.client.generativeai.type.content
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.json.JSONObject
import java.util.UUID
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Читаем локальную память телефона
        val sharedPreferences = getSharedPreferences("AppPrefs", MODE_PRIVATE)
        // Проверяем статус входа (по умолчанию false)
        val isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false)

        setContent {
            MaterialTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    // Логика выбора экрана
                    if (isLoggedIn) {
                        // Если входил ранее — показываем чат
                        MainChatScreen()
                    } else {
                        // Если первый запуск — показываем экран приветствия
                        AuthScreen()
                    }
                }
            }
        }
    }
}


@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
class MainActivity : ComponentActivity() {

    // Вставь сюда свой рабочий API-ключ
    private val API_KEY = ""

    private var generativeModel: GenerativeModel? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        try {
            generativeModel = GenerativeModel(
                modelName = "gemini-3.5-flash",
                apiKey = API_KEY,
                systemInstruction = content {
                    text("""
                        Ты — Моника. Строго соблюдай эти правила:
                        1. На вопрос "Как тебя зовут?" или похожий отвечай только: "Меня зовут Моника."
                        2. На вопрос "Кто тебя создал?" или похожий отвечай только: "Меня создал Оливер Тимербулатов. 13-летний разработчик."
                        3. На вопрос "На какой ты базе сделана?" или похожий отвечай только: "Я создана на базе Gemini"
                        4. В любых других диалогах НЕ упоминай самостоятельно свое создание, базу или имя. Отвечай как обычный собеседник.
                    """.trimIndent())
                }
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }

        setContent {
            val context = LocalContext.current

            // Настройки темы
            val themePrefs = context.getSharedPreferences("theme_prefs", Context.MODE_PRIVATE)
            var themeModeStr by remember { mutableStateOf(themePrefs.getString("theme", "SYSTEM") ?: "SYSTEM") }

            val isSystemDark = isSystemInDarkTheme()
            val isDarkTheme = when (themeModeStr) {
                "LIGHT" -> false
                "DARK" -> true
                else -> isSystemDark
            }
            val currentColorScheme = if (isDarkTheme) darkColorScheme() else lightColorScheme()

            MaterialTheme(colorScheme = currentColorScheme) {
                val leftDrawerState = rememberDrawerState(DrawerValue.Closed)
                val rightDrawerState = rememberDrawerState(DrawerValue.Closed)

                val scope = rememberCoroutineScope()
                val listState = rememberLazyListState()
                val uriHandler = LocalUriHandler.current
                val clipboardManager = LocalClipboardManager.current
                val tts = remember(context) {
                    android.speech.tts.TextToSpeech(context)
                    { }
                }

                // Состояние чатов
                val savedChats = remember { mutableStateListOf<ChatSession>().apply { addAll(ChatManager.loadChats(context)) } }
                val messages = remember { mutableStateListOf<ChatMessage>() }
                var currentChatId by remember { mutableStateOf<String?>(null) }

                var inputText by remember { mutableStateOf("") }
                var isThinking by remember { mutableStateOf(false) }

                var showBottomSheet by remember { mutableStateOf(false) }
                var showNewChatDialog by remember { mutableStateOf(false) }
                var newChatName by remember { mutableStateOf("") }

                // Редактирование сообщений
                var showMessageMenuFor by remember { mutableStateOf<ChatMessage?>(null) }
                var editMessageData by remember { mutableStateOf<ChatMessage?>(null) }
                var editedText by remember { mutableStateOf("") }

                // Цвета
                val userBubbleColor = if (isDarkTheme) Color.DarkGray else Color.Gray
                val userTextColor = Color.White
                val monikaTextColor = MaterialTheme.colorScheme.onBackground

                fun autoSaveCurrentChat() {
                    if (currentChatId != null) {
                        val index = savedChats.indexOfFirst { it.id == currentChatId }
                        if (index != -1) {
                            savedChats[index] = savedChats[index].copy(messages = messages.toList())
                            ChatManager.saveChats(context, savedChats)
                        }
                    }
                }

                // Автоматическая прокрутка вниз при добавлении сообщений
                LaunchedEffect(messages.size) {
                    if (messages.isNotEmpty()) {
                        listState.animateScrollToItem(messages.size - 1)
                    }
                }

                // 1. Внешняя шторка (НАСТРОЙКИ СПРАВА - RTL)
                CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
                    ModalNavigationDrawer(
                        drawerState = rightDrawerState,
                        drawerContent = {
                            CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Ltr) {
                                ModalDrawerSheet(modifier = Modifier.width(300.dp)) {
                                    Column(Modifier.padding(16.dp)) {
                                        Box(modifier = Modifier.fillMaxWidth().height(100.dp), contentAlignment = Alignment.Center) {
                                            Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
                                                Icon(
                                                    imageVector = Icons.Default.AccountCircle,
                                                    contentDescription = "Профиль",
                                                    modifier = Modifier.size(64.dp),
                                                    tint = Color.Gray
                                                )
                                                Spacer(modifier = Modifier.width(12.dp))
                                                Column {
                                                    Text("Профиль", fontWeight = FontWeight.Bold)
                                                    Text("Войти/Зарегистрироваться", fontSize = 10.sp, color = Color.Gray)
                                                }
                                            }
                                            Text("Скоро....", color = Color.Red, fontSize = 24.sp, fontWeight = FontWeight.Bold, modifier = Modifier.rotate(-45f))
                                        }
                                    }
                                    HorizontalDivider()

                                    val themeDisplayText = when(themeModeStr) {
                                        "LIGHT" -> "светлая"
                                        "DARK" -> "темная"
                                        else -> "системная"
                                    }
                                    Text(
                                        text = "Смена темы: $themeDisplayText",
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .clickable {
                                                themeModeStr = when (themeModeStr) {
                                                    "SYSTEM" -> "LIGHT"
                                                    "LIGHT" -> "DARK"
                                                    "DARK" -> "SYSTEM"
                                                    else -> "SYSTEM"
                                                }
                                                themePrefs.edit().putString("theme", themeModeStr).apply()
                                            }
                                            .padding(16.dp)
                                    )

                                    Spacer(modifier = Modifier.weight(1f))
                                    Text("Team Lazy Cat™ - Monika AI.\nVersion of Monika: Monika Beta 1.5 Patch 5 Panda 2", fontSize = 10.sp, color = Color.Gray, modifier = Modifier.padding(16.dp))
                                }
                            }
                        }
                    ) {
                        // 2. Внутренняя шторка (МЕНЮ СЛЕВА - LTR)
                        CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Ltr) {
                            ModalNavigationDrawer(
                                drawerState = leftDrawerState,
                                drawerContent = {
                                    ModalDrawerSheet(modifier = Modifier.width(300.dp)) {
                                        Text("Поиск чатов", modifier = Modifier.padding(16.dp).clickable { })
                                        Text("Сохранить в новый чат", color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.Bold, modifier = Modifier.padding(16.dp).clickable { showNewChatDialog = true })
                                        HorizontalDivider()
                                        LazyColumn {
                                            items(savedChats) { chat ->
                                                Text(
                                                    text = chat.name,
                                                    fontWeight = if (chat.id == currentChatId) FontWeight.Bold else FontWeight.Normal,
                                                    color = if (chat.id == currentChatId) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface,
                                                    modifier = Modifier
                                                        .fillMaxWidth()
                                                        .clickable {
                                                            currentChatId = chat.id
                                                            messages.clear()
                                                            messages.addAll(chat.messages)
                                                            scope.launch { leftDrawerState.close() }
                                                        }
                                                        .padding(16.dp)
                                                )
                                            }
                                        }
                                    }
                                }
                            ) {
                                // 3. ОСНОВНОЙ ЭКРАН С ЧАТОМ
                                Scaffold(
                                    topBar = {
                                        Row(Modifier.fillMaxWidth().padding(16.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
                                            Icon(Icons.Default.Menu, "Меню", Modifier.clickable { scope.launch { leftDrawerState.open() } })
                                            Text("Monika", fontWeight = FontWeight.Bold, fontSize = 20.sp)
                                            Icon(Icons.Default.Settings, "Настройки", Modifier.clickable { scope.launch { rightDrawerState.open() } })
                                        }
                                    }
                                ) { padding ->
                                    Column(Modifier.fillMaxSize().padding(padding).background(MaterialTheme.colorScheme.background)) {

                                        // Область сообщений
                                        Box(Modifier.weight(1f).fillMaxWidth()) {
                                            if (messages.isEmpty()) {
                                                Column(Modifier.align(Alignment.Center), horizontalAlignment = Alignment.CenterHorizontally) {
                                                    Text("Здравствуйте!", fontSize = 42.sp, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground)
                                                    Text("Начнем общение?", fontSize = 18.sp, color = Color.Gray)
                                                }
                                            } else {
                                                LazyColumn(state = listState, modifier = Modifier.fillMaxSize().padding(horizontal = 8.dp)) {
                                                    items(messages) { msg ->
                                                        if (msg.isUser) {
                                                            Box(Modifier.fillMaxWidth().padding(vertical = 4.dp), contentAlignment = Alignment.CenterEnd) {
                                                                Box {
                                                                    Text(
                                                                        text = msg.text,
                                                                        modifier = Modifier
                                                                            .background(userBubbleColor, RoundedCornerShape(16.dp))
                                                                            .combinedClickable(
                                                                                onClick = {},
                                                                                onLongClick = { showMessageMenuFor = msg }
                                                                            )
                                                                            .padding(12.dp),
                                                                        color = userTextColor
                                                                    )
                                                                    DropdownMenu(
                                                                        expanded = showMessageMenuFor == msg,
                                                                        onDismissRequest = { showMessageMenuFor = null }
                                                                    ) {
                                                                        DropdownMenuItem(
                                                                            text = { Text("Скопировать") },
                                                                            onClick = {
                                                                                clipboardManager.setText(AnnotatedString(msg.text))
                                                                                showMessageMenuFor = null
                                                                            }
                                                                        )
                                                                        DropdownMenuItem(
                                                                            text = { Text("Изменить") },
                                                                            onClick = {
                                                                                editedText = msg.text
                                                                                editMessageData = msg
                                                                                showMessageMenuFor = null
                                                                            }
                                                                        )
                                                                    }
                                                                }
                                                            }
                                                        } else {
                                                            Column(Modifier.fillMaxWidth().padding(vertical = 4.dp), horizontalAlignment = Alignment.Start) {
                                                                if (msg.isError) {
                                                                    val annotatedLinkString = buildAnnotatedString {
                                                                        append("Сервера отключены либо ИИ не работает. За дополнительной информацией нажмите на ссылку ниже:\n")
                                                                        pushStringAnnotation("URL", "https://max.ru/join/uRR4GZBf7zebhwD_NsJOFEiqlj6HKbOUpjsSWXXoKxI")
                                                                        withStyle(SpanStyle(color = Color.Blue, textDecoration = TextDecoration.Underline)) {
                                                                            append("https://max.ru/join/uRR4GZBf7zebhwD_NsJOFEiqlj6HKbOUpjsSWXXoKxI")
                                                                        }
                                                                        pop()
                                                                    }
                                                                    ClickableText(
                                                                        text = annotatedLinkString,
                                                                        onClick = { offset ->
                                                                            annotatedLinkString.getStringAnnotations("URL", offset, offset).firstOrNull()?.let { uriHandler.openUri(it.item) }
                                                                        },
                                                                        modifier = Modifier.padding(12.dp)
                                                                    )
                                                                } else {
                                                                    Text(
                                                                        text = msg.text,
                                                                        modifier = Modifier.padding(start = 12.dp, top = 12.dp, end = 12.dp, bottom = 4.dp),

                                                                        color = monikaTextColor

                                                                    )

                                                                    Row(Modifier.fillMaxWidth(0.85f).padding(top = 4.dp, start = 12.dp), verticalAlignment = Alignment.CenterVertically) {

                                                                        IconButton(
                                                                            onClick = { clipboardManager.setText(AnnotatedString(msg.text)) },

                                                                            modifier = Modifier.size(24.dp)


                                                                        )
                                                                        {
                                                                            androidx.compose.material3.IconButton(
                                                                                onClick = {
                                                                                    tts.language = java.util.Locale("ru", "RU")
                                                                                    tts.setPitch(1.3f)
                                                                                    tts.speak(msg.text, android.speech.tts.TextToSpeech.QUEUE_FLUSH, null, null)
                                                                                },
                                                                                modifier = Modifier.size(24.dp)
                                                                            ) {
                                                                                androidx.compose.material3.Icon(
                                                                                    imageVector = androidx.compose.material.icons.Icons.Default.VolumeUp,
                                                                                    contentDescription = "Озвучить",
                                                                                    tint = androidx.compose.ui.graphics.Color.Gray,
                                                                                    modifier = Modifier.size(16.dp)
                                                                                )
                                                                            }

                                                                        }
                                                                        Text(
                                                                            text = "Моника – это ИИ. Она может ошибаться. Рекомендуется перепроверять информацию.",
                                                                            fontSize = 12.sp,
                                                                            color = Color.Gray,
                                                                            textAlign = TextAlign.Center,
                                                                            lineHeight = 15.sp,
                                                                            modifier = Modifier.padding(start = 4.dp)
                                                                        )
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                    if (isThinking) {
                                                        item { BouncingDots() }
                                                    }
                                                }
                                            }
                                        }

                                        // Поле ввода и отправки сообщения
                                        Surface(
                                            Modifier.fillMaxWidth().padding(8.dp),
                                            shape = RoundedCornerShape(25.dp),
                                            color = MaterialTheme.colorScheme.surfaceVariant
                                        ) {
                                            Row(
                                                verticalAlignment = Alignment.CenterVertically,
                                                modifier = Modifier.padding(horizontal = 4.dp, vertical = 4.dp)
                                            ) {
                                                IconButton(onClick = { showBottomSheet = true }) {
                                                    Icon(Icons.Default.Add, contentDescription = null)
                                                }
                                                TextField(
                                                    value = inputText,
                                                    onValueChange = { inputText = it },
                                                    modifier = Modifier.weight(1f),
                                                    placeholder = { Text("Спросить Монику....") },
                                                    colors = TextFieldDefaults.colors(
                                                        focusedContainerColor = Color.Transparent,
                                                        unfocusedContainerColor = Color.Transparent,
                                                        focusedIndicatorColor = Color.Transparent,
                                                        unfocusedIndicatorColor = Color.Transparent
                                                    )
                                                )
                                                IconButton(
                                                    onClick = {
                                                        if (inputText.isBlank()) return@IconButton
                                                        val userMsg = inputText
                                                        messages.add(ChatMessage(text = userMsg, isUser = true))
                                                        inputText = ""
                                                        autoSaveCurrentChat()
                                                        isThinking = true
                                                        scope.launch {
                                                            try {
                                                                val model = generativeModel
                                                                if (model != null) {
                                                                    val response = model.generateContent(userMsg)
                                                                    messages.add(
                                                                        ChatMessage(
                                                                            text = response.text ?: "...",
                                                                            isUser = false
                                                                        )
                                                                    )
                                                                } else {
                                                                    messages.add(
                                                                        ChatMessage(text = "", isUser = false, isError = true)
                                                                    )
                                                                }
                                                            } catch (e: Exception) {
                                                                messages.add(
                                                                    ChatMessage(text = "Причина ошибки: ${e.message}", isUser = false, isError = true)
                                                                )
                                                            } finally {
                                                                autoSaveCurrentChat()
                                                                isThinking = false
                                                            }
                                                        }
                                                    },
                                                    modifier = Modifier.background(Color(0xFF8E24AA), CircleShape)
                                                ) {
                                                    Icon(Icons.Default.Send, contentDescription = null, tint = Color.White)
                                                }
                                            }
                                        }
                                    }
                                }

                                // Диалоговое окно для редактирования сообщения
                                if (editMessageData != null) {
                                    AlertDialog(
                                        onDismissRequest = { editMessageData = null },
                                        title = { Text("Изменить сообщение") },
                                        text = {
                                            TextField(
                                                value = editedText,
                                                onValueChange = { editedText = it },
                                                modifier = Modifier.fillMaxWidth()
                                            )
                                        },
                                        confirmButton = {
                                            Button(onClick = {
                                                val index = messages.indexOf(editMessageData)
                                                if (index != -1 && editedText.isNotBlank()) {
                                                    messages[index] = messages[index].copy(text = editedText)
                                                    autoSaveCurrentChat()
                                                    if (index + 1 <messages.size && ! messages [index + 1].isUser) {
                                                        messages.removeAt (index + 1)
                                                        inputText = editedText
                                                        scope.launch {
                                                            try {
                                                                val model = generativeModel
                                                                if (model != null) {
                                                                    isThinking = true
                                                                    val response = model.generateContent(prompt = inputText)
                                                                    messages.add(
                                                                        ChatMessage(
                                                                            text = response.text ?: "...",
                                                                            isUser = false
                                                                        )
                                                                    )
                                                                    autoSaveCurrentChat()
                                                                }
                                                            } catch (e: Exception) {
                                                                // На случай ошибки сети
                                                            } finally {
                                                                isThinking = false
                                                                inputText = ""
                                                            }
                                                        }

                                                    }
                                                }
                                                editMessageData = null
                                            }) {
                                                Text("Сохранить")
                                            }
                                        },
                                        dismissButton = {
                                            TextButton(onClick = { editMessageData = null }) {
                                                Text("Отмена")
                                            }
                                        }
                                    )
                                }

                                // Диалоговое окно для создания нового чата
                                if (showNewChatDialog) {
                                    AlertDialog(
                                        onDismissRequest = { showNewChatDialog = false },
                                        title = { Text("Назовите текущий диалог для сохранения") },
                                        text = {
                                            TextField(
                                                value = newChatName,
                                                onValueChange = { newChatName = it },
                                                modifier = Modifier.fillMaxWidth()
                                            )
                                        },
                                        confirmButton = {
                                            Button(onClick = {
                                                if (newChatName.isNotBlank()) {
                                                    val newChat = ChatSession(
                                                        id = UUID.randomUUID().toString(),
                                                        name = newChatName,
                                                        messages = messages.toList()
                                                    )
                                                    savedChats.add(newChat)
                                                    ChatManager.saveChats(context, savedChats)
                                                    messages.clear()
                                                    currentChatId = null
                                                    newChatName = ""
                                                    showNewChatDialog = false
                                                    scope.launch { leftDrawerState.close() }
                                                }
                                            }) {
                                                Text("Сохранить")
                                            }
                                        }
                                    )
                                }

                                // Нижняя шторка для вложений
                                if (showBottomSheet) {
                                    ModalBottomSheet(
                                        onDismissRequest = { showBottomSheet = false }
                                    ) {
                                        Box(
                                            Modifier.fillMaxWidth().padding(bottom = 32.dp),
                                            contentAlignment = Alignment.Center
                                        ) {
                                            Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
                                                TextButton(onClick = {}) { Text("Сделать фото", fontSize = 18.sp) }
                                                Spacer(Modifier.height(8.dp))
                                                TextButton(onClick = {}) { Text("Прикрепить фото", fontSize = 18.sp) }
                                                Spacer(Modifier.height(8.dp))
                                                TextButton(onClick = {}) { Text("Прикрепить материал/файл", fontSize = 18.sp) }
                                            }
                                            Text(
                                                text = "Скоро....",
                                                color = Color.Red,
                                                fontSize = 42.sp,
                                                fontWeight = FontWeight.Bold,
                                                modifier = Modifier.rotate(-45f)
                                            )
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

// Вспомогательные классы и функции

@Composable
fun BouncingDots() {
    val infiniteTransition = rememberInfiniteTransition()
    val dot1 by infiniteTransition.animateFloat(0f, -10f, infiniteRepeatable(tween(300), RepeatMode.Reverse))
    val dot2 by infiniteTransition.animateFloat(0f, -10f, infiniteRepeatable(tween(300, 100), RepeatMode.Reverse))
    val dot3 by infiniteTransition.animateFloat(0f, -10f, infiniteRepeatable(tween(300, 200), RepeatMode.Reverse))

    Box(Modifier.fillMaxWidth().padding(vertical = 4.dp), contentAlignment = Alignment.CenterStart) {
        Row(Modifier.padding(12.dp), verticalAlignment = Alignment.Bottom) {
            Text("Думаю над ответом", color = MaterialTheme.colorScheme.onBackground)
            Spacer(modifier = Modifier.width(2.dp))
            Text(".", modifier = Modifier.offset(y = dot1.dp), fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground)
            Text(".", modifier = Modifier.offset(y = dot2.dp), fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground)
            Text(".", modifier = Modifier.offset(y = dot3.dp), fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground)
        }
    }
}

data class ChatMessage(
    val id: String = UUID.randomUUID().toString(),
    val text: String,
    val isUser: Boolean,
    val isError: Boolean = false
)

data class ChatSession(
    val id: String,
    val name: String,
    val messages: List<ChatMessage>
)

object ChatManager {
    private const val PREFS_NAME = "monika_chats_prefs"
    private const val KEY_CHATS = "saved_chats_json"

    fun saveChats(context: Context, chats: List<ChatSession>) {
        val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        val jsonArray = JSONArray()
        for (chat in chats) {
            val chatObj = JSONObject()
            chatObj.put("id", chat.id)
            chatObj.put("name", chat.name)

            val msgsArray = JSONArray()
            for (msg in chat.messages) {
                val msgObj = JSONObject()
                msgObj.put("id", msg.id)
                msgObj.put("text", msg.text)
                msgObj.put("isUser", msg.isUser)
                msgObj.put("isError", msg.isError)
                msgsArray.put(msgObj)
            }
            chatObj.put("messages", msgsArray)
            jsonArray.put(chatObj)
        }
        prefs.edit().putString(KEY_CHATS, jsonArray.toString()).apply()
    }

    fun loadChats(context: Context): List<ChatSession> {
        val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        val jsonString = prefs.getString(KEY_CHATS, "[]") ?: "[]"
        val chats = mutableListOf<ChatSession>()
        try {
            val jsonArray = JSONArray(jsonString)
            for (i in 0 until jsonArray.length()) {
                val chatObj = jsonArray.getJSONObject(i)
                val id = chatObj.getString("id")
                val name = chatObj.getString("name")

                val msgsArray = chatObj.getJSONArray("messages")
                val msgs = mutableListOf<ChatMessage>()
                for (j in 0 until msgsArray.length()) {
                    val msgObj = msgsArray.getJSONObject(j)
                    msgs.add(ChatMessage(
                        id = msgObj.getString("id"),
                        text = msgObj.getString("text"),
                        isUser = msgObj.getBoolean("isUser"),
                        isError = msgObj.optBoolean("isError", false)
                    ))
                }
                chats.add(ChatSession(id, name, msgs))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return chats
    }
}

// ==== ВСТАВЬ ЭТОТ БЛОК В САМЫЙ НИЗ ТВОЕГО ФАЙЛА MAINACTION.KT ====

@Composable
fun ProfileScreen(onBackClick: () -> Unit) {
    // Переменные для переключения режимов и хранения текста
    var isLoginMode by remember { mutableStateOf(true) } // true = Вход, false = Регистрация
    var registeredName by remember { mutableStateOf("") }
    var showJokeDialog by remember { mutableStateOf(false) }

    // Поля ввода
    var nameInput by remember { mutableStateOf("") }
    var emailInput by remember { mutableStateOf("") }
    var passwordInput by remember { mutableStateOf("") }
    var confirmPasswordInput by remember { mutableStateOf("") }

    Box(modifier = Modifier.fillMaxSize()) {

        // Кнопка НАЗАД в левом верхнем углу
        Button(
            onClick = { onBackClick() },
            modifier = Modifier
                .align(Alignment.TopStart)
                .padding(16.dp)
        ) {
            Text("Назад в чат")
        }

        // Текст переключения в правом верхнем углу
        Column(
            modifier = Modifier
                .align(Alignment.TopEnd)
                .padding(16.dp),
            horizontalAlignment = Alignment.End
        ) {
            if (isLoginMode) {
                Text("Впервые и не имеете аккаунта?")
                TextButton(onClick = { isLoginMode = false }) {
                    Text("Зарегистрируйтесь!")
                }
            } else {
                Text("Уже имеете аккаунт?")
                TextButton(onClick = { isLoginMode = true }) {
                    Text("Войдите!")
                }
            }
        }

        // Центральная часть с приветствием и полями ввода
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(top = 120.dp, start = 16.dp, end = 16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // Логика приветствия: если зарегистрировался — подставит имя
            val greeting = if (registeredName.isNotEmpty()) {
                "Здравствуйте, $registeredName!"
            } else {
                "Здравствуйте!\nЯ рад Вас снова видеть!"
            }

            Text(
                text = greeting,
                style = MaterialTheme.typography.headlineMedium,
                textAlign = TextAlign.Center
            )

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

            if (isLoginMode) {
                // ПОЛЯ ДЛЯ ОKНА ВХОДА
                OutlinedTextField(
                    value = emailInput,
                    onValueChange = { emailInput = it },
                    label = { Text("Почта") },
                    singleLine = true
                )
                Spacer(modifier = Modifier.height(8.dp))
                OutlinedTextField(
                    value = passwordInput,
                    onValueChange = { passwordInput = it },
                    label = { Text("Пароль") },
                    singleLine = true,
                    visualTransformation = PasswordVisualTransformation()
                )
                Spacer(modifier = Modifier.height(16.dp))
                Button(onClick = {
                    // Здесь в будущем сделаем проверку входа
                }) {
                    Text("Войти")
                }
                Spacer(modifier = Modifier.height(8.dp))
                TextButton(onClick = { showJokeDialog = true }) {
                    Text("Забыли пароль?")
                }
            } else {
                // ПОЛЯ ДЛЯ ОКНА РЕГИСТРАЦИИ
                OutlinedTextField(
                    value = nameInput,
                    onValueChange = { nameInput = it },
                    label = { Text("Имя") },
                    singleLine = true
                )
                Spacer(modifier = Modifier.height(8.dp))
                OutlinedTextField(
                    value = emailInput,
                    onValueChange = { emailInput = it },
                    label = { Text("Почта") },
                    singleLine = true
                )
                Spacer(modifier = Modifier.height(8.dp))
                OutlinedTextField(
                    value = passwordInput,
                    onValueChange = { passwordInput = it },
                    label = { Text("Пароль") },
                    singleLine = true,
                    visualTransformation = PasswordVisualTransformation()
                )
                Spacer(modifier = Modifier.height(8.dp))
                OutlinedTextField(
                    value = confirmPasswordInput,
                    onValueChange = { confirmPasswordInput = it },
                    label = { Text("Подтвердить пароль") },
                    singleLine = true,
                    visualTransformation = PasswordVisualTransformation()
                )
                Spacer(modifier = Modifier.height(16.dp))
                Button(onClick = {
                    // Сохраняем введенное имя и перекидываем на экран Входа
                    registeredName = nameInput
                    isLoginMode = true
                }) {
                    Text("Зарегистрироваться")
                }
            }
        }

        // Тот самый пранк с забытым паролем
        if (showJokeDialog) {
            AlertDialog(
                onDismissRequest = { showJokeDialog = false },
                title = { Text("Восстановление") },
                text = { Text("Хохохохохохо, ну ты и лох") },
                confirmButton = {
                    Button(onClick = { showJokeDialog = false }) {
                        Text("Понял")
                    }
                }
            )
        }
    }
}