package com.optix.android.ui.screens.ai

import android.app.Activity
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Palette
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.optix.android.domain.model.AiMessage
import com.optix.android.domain.model.MessageRole
import com.optix.android.ui.components.HexGrid
import com.optix.android.ui.components.RadarPulse
import com.optix.android.ui.components.neonTextFieldColors
import com.optix.android.ui.navigation.Screen
import com.optix.android.ui.screens.settings.SettingsSheet
import com.optix.android.ui.screens.settings.ThemePickerSheet
import com.optix.android.ui.theme.T

@OptIn(ExperimentalMaterial3Api::class, ExperimentalAnimationApi::class, ExperimentalLayoutApi::class)
@Composable
fun AiScreen(
    viewModel: AiViewModel = hiltViewModel(),
    settingsRepository: com.optix.android.data.repository.SettingsRepositoryImpl? = null,
    currentScreen: Screen = Screen.Chat,
    runningByRoute: Map<String, Boolean> = emptyMap(),
    onNavigate: (Screen) -> Unit = {},
) {
    val state by viewModel.uiState.collectAsState()
    val config by viewModel.providerConfig.collectAsState()
    val listState = rememberLazyListState()
    var inputText by remember { mutableStateOf("") }
    var showSettings by remember { mutableStateOf(false) }
    var showThemePicker by remember { mutableStateOf(false) }
    var showCommands by remember { mutableStateOf(false) }
    val settingsSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    val themeSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    val commandsSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    val runningBorder = T.warning.copy(alpha = 0.45f)

    LaunchedEffect(state.messages.size) {
        if (state.messages.isNotEmpty()) listState.animateScrollToItem(state.messages.lastIndex)
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(T.background),
    ) {
        HexGrid(modifier = Modifier.fillMaxSize(), color = T.accent.copy(alpha = 0.04f))

        Column(
            modifier = Modifier
                .fillMaxSize()
                .imePadding(),
        ) {
            BrainTopBar(
                providerName = config.provider.displayName,
                isStreaming = state.isStreaming,
                currentScreen = currentScreen,
                runningByRoute = runningByRoute,
                onNavigate = onNavigate,
                onSettingsClick = { showSettings = true },
                onThemeClick = { showThemePicker = true },
            )

            AnimatedVisibility(visible = state.activeToolCall != null) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(T.surface.copy(alpha = 0.82f))
                        .drawBehind {
                            drawLine(runningBorder, Offset(0f, size.height), Offset(size.width, size.height), 1f)
                        }
                        .padding(horizontal = 12.dp, vertical = 7.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                ) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(11.dp),
                        color = T.warning,
                        strokeWidth = 1.8.dp,
                    )
                    Text("RUNNING", color = T.onSurfaceMid, style = MaterialTheme.typography.labelSmall)
                    Box(
                        modifier = Modifier
                            .background(T.warning.copy(alpha = 0.12f), RoundedCornerShape(4.dp))
                            .border(1.dp, T.warning.copy(alpha = 0.35f), RoundedCornerShape(4.dp))
                            .padding(horizontal = 7.dp, vertical = 2.dp),
                    ) {
                        Text(
                            state.activeToolCall ?: "",
                            color = T.warning,
                            style = MaterialTheme.typography.labelSmall,
                        )
                    }
                }
            }

            LazyColumn(
                state = listState,
                modifier = Modifier.weight(1f),
                contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                if (state.messages.isEmpty()) {
                    item { BrainEmptyState(onChipTap = viewModel::sendMessage) }
                }
                item {
                    AnimatedVisibility(visible = state.pendingChain != null) {
                        state.pendingChain?.let { chain ->
                            BrainChainCard(
                                chain = chain,
                                skippedSteps = state.chainSkippedSteps,
                                onSend = {
                                    viewModel.sendChainToNetwork()
                                    onNavigate(Screen.Network)
                                },
                                onDismiss = viewModel::clearPendingChain,
                            )
                        }
                    }
                }
                items(state.messages, key = { it.id }) { message ->
                    NeonChatBubble(
                        message = message,
                        isStreaming = message.id == state.streamingMessageId,
                    )
                }
            }

            AiStatusStrip(viewModel, onShowCommands = { showCommands = true })

            NeonInputBar(
                text = inputText,
                onTextChange = { inputText = it },
                isStreaming = state.isStreaming,
                onSend = {
                    if (inputText.isNotBlank()) {
                        viewModel.sendMessage(inputText)
                        inputText = ""
                    }
                },
                onStop = viewModel::cancelStreaming,
            )
        }
    }

    if (showSettings) {
        ModalBottomSheet(
            onDismissRequest = { showSettings = false },
            sheetState = settingsSheetState,
            containerColor = T.surface,
        ) {
            SettingsSheet(onDismiss = { showSettings = false })
        }
    }
    if (showThemePicker) {
        ModalBottomSheet(
            onDismissRequest = { showThemePicker = false },
            sheetState = themeSheetState,
            containerColor = T.surface,
        ) {
            settingsRepository?.let { ThemePickerSheet(it) }
        }
    }
    if (showCommands) {
        ModalBottomSheet(
            onDismissRequest = { showCommands = false },
            sheetState = commandsSheetState,
            containerColor = T.surface,
        ) {
            CommandsSheet(onDismiss = { showCommands = false })
        }
    }
}

@Composable
private fun BrainTopBar(
    providerName: String,
    isStreaming: Boolean,
    currentScreen: Screen,
    runningByRoute: Map<String, Boolean>,
    onNavigate: (Screen) -> Unit,
    onSettingsClick: () -> Unit,
    onThemeClick: () -> Unit,
) {
    val pulseAlpha by rememberInfiniteTransition(label = "brain-top").animateFloat(
        initialValue = 0.4f,
        targetValue = 1f,
        animationSpec = infiniteRepeatable(tween(1000, easing = FastOutSlowInEasing), RepeatMode.Reverse),
        label = "brain-top-pulse",
    )
    val activity = LocalContext.current as? Activity
    val headerBorder = T.accent.copy(alpha = 0.5f)

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(T.surface)
            .drawBehind {
                drawLine(headerBorder, Offset(0f, size.height), Offset(size.width, size.height), 1f)
            }
            .padding(horizontal = 12.dp, vertical = 8.dp),
        verticalArrangement = Arrangement.spacedBy(6.dp),
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(10.dp),
            ) {
                Box(contentAlignment = Alignment.Center, modifier = Modifier.size(34.dp)) {
                    RadarPulse(modifier = Modifier.size(34.dp), color = T.graphics, rings = 2)
                }
                Column {
                    Text(
                        "OPTIX BRAIN",
                        color = T.accent.copy(alpha = if (isStreaming) pulseAlpha else 1f),
                        style = MaterialTheme.typography.titleSmall,
                    )
                }
            }

            HeaderTabs(
                currentScreen = currentScreen,
                runningByRoute = runningByRoute,
                onNavigate = onNavigate,
            )

            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(2.dp),
            ) {
                IconButton(onClick = onThemeClick, modifier = Modifier.size(28.dp)) {
                    Icon(Icons.Default.Palette, contentDescription = "Theme", tint = T.onSurfaceMid, modifier = Modifier.size(15.dp))
                }
                IconButton(onClick = onSettingsClick, modifier = Modifier.size(28.dp)) {
                    Icon(Icons.Default.Settings, contentDescription = "Settings", tint = T.onSurfaceMid, modifier = Modifier.size(15.dp))
                }
                IconButton(onClick = { activity?.finish() }, modifier = Modifier.size(28.dp)) {
                    Icon(Icons.Default.Close, contentDescription = "Close", tint = T.onSurfaceMid.copy(alpha = 0.75f), modifier = Modifier.size(15.dp))
                }
            }
        }

        Text(
            if (isStreaming) "[ $providerName ] LIVE" else "[ $providerName ] READY",
            color = if (isStreaming) T.success.copy(alpha = pulseAlpha) else T.onSurfaceMid,
            style = MaterialTheme.typography.labelSmall,
        )
    }
}

@Composable
private fun HeaderTabs(
    currentScreen: Screen,
    runningByRoute: Map<String, Boolean>,
    onNavigate: (Screen) -> Unit,
) {
    Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
        listOf(Screen.Chat, Screen.Network).forEach { screen ->
            val selected = currentScreen.route == screen.route
            val isRunning = runningByRoute[screen.route] == true
            val pulseAlpha by rememberInfiniteTransition(label = "hdr-tab-${screen.route}").animateFloat(
                0.4f,
                1f,
                animationSpec = infiniteRepeatable(tween(700), RepeatMode.Reverse),
                label = "hdr-tab-pulse-${screen.route}",
            )
            Row(
                modifier = Modifier
                    .clip(RoundedCornerShape(999.dp))
                    .background(if (selected) T.accent.copy(alpha = 0.16f) else T.surfaceVar.copy(alpha = 0.95f))
                    .border(
                        1.dp,
                        if (selected) T.accent.copy(alpha = 0.5f) else T.border.copy(alpha = 0.55f),
                        RoundedCornerShape(999.dp),
                    )
                    .clickable { onNavigate(screen) }
                    .padding(horizontal = 10.dp, vertical = 6.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(6.dp),
            ) {
                Icon(
                    screen.icon,
                    contentDescription = screen.label,
                    tint = if (selected) T.accent else T.onSurfaceMid,
                    modifier = Modifier.size(14.dp),
                )
                Text(
                    screen.label,
                    color = if (selected) T.accent else T.onSurface,
                    style = MaterialTheme.typography.labelSmall,
                )
                if (isRunning) {
                    Box(Modifier.size(6.dp).background(T.success.copy(alpha = pulseAlpha), CircleShape))
                }
            }
        }
    }
}

@Composable
private fun BrainChainCard(
    chain: com.optix.android.domain.model.ToolChain,
    skippedSteps: List<String>,
    onSend: () -> Unit,
    onDismiss: () -> Unit,
) {
    val chainCardBorder = T.accent.copy(alpha = 0.5f)
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(T.surface.copy(alpha = 0.6f))
            .border(1.dp, chainCardBorder, RoundedCornerShape(10.dp))
            .padding(12.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp),
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text(
                "⛓ AI WORKFLOW CHAIN",
                color = T.accent,
                style = MaterialTheme.typography.labelMedium,
            )
            Text(
                "${chain.steps.size} steps",
                color = T.onSurfaceMid,
                style = MaterialTheme.typography.labelSmall,
            )
        }

        Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
            chain.steps.forEachIndexed { i, step ->
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                ) {
                    Box(
                        modifier = Modifier
                            .size(18.dp)
                            .background(T.accent.copy(alpha = 0.15f), CircleShape),
                        contentAlignment = Alignment.Center,
                    ) {
                        Text("${i + 1}", color = T.accent, style = MaterialTheme.typography.labelSmall)
                    }
                    Text(
                        step.toolSlug,
                        color = T.textAccent,
                        style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp),
                    )
                }
            }
        }

        if (skippedSteps.isNotEmpty()) {
            Text(
                "⚠ Skipped unknown tool(s): ${skippedSteps.joinToString(", ")}",
                color = T.warning,
                style = MaterialTheme.typography.labelSmall,
            )
        }

        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
        ) {
            Box(
                modifier = Modifier
                    .weight(1f)
                    .clip(RoundedCornerShape(7.dp))
                    .background(T.accent)
                    .clickable { onSend() }
                    .padding(vertical = 9.dp),
                contentAlignment = Alignment.Center,
            ) {
                Text(
                    "▶ SEND TO NETWORK",
                    color = if (T.isDark) Color.Black else Color.White,
                    style = MaterialTheme.typography.labelMedium,
                )
            }
            Box(
                modifier = Modifier
                    .clip(RoundedCornerShape(7.dp))
                    .background(T.surfaceVar)
                    .border(1.dp, T.border, RoundedCornerShape(7.dp))
                    .clickable { onDismiss() }
                    .padding(vertical = 9.dp, horizontal = 14.dp),
                contentAlignment = Alignment.Center,
            ) {
                Text("DISMISS", color = T.onSurfaceMid, style = MaterialTheme.typography.labelMedium)
            }
        }
    }
}

@Composable
private fun NeonChatBubble(message: AiMessage, isStreaming: Boolean) {
    val isUser = message.role == MessageRole.USER
    val isToolResult = message.role == MessageRole.TOOL_RESULT

    val accentColor = when {
        isUser -> T.accentGlow
        isToolResult -> T.warning
        else -> T.accent
    }

    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start,
    ) {
        if (!isUser) {
            Box(
                modifier = Modifier
                    .padding(top = 4.dp, end = 6.dp)
                    .size(7.dp)
                    .background(accentColor, CircleShape),
            )
        }

        Box(
            modifier = Modifier
                .widthIn(max = 340.dp)
                .clip(
                    RoundedCornerShape(
                        topStart = if (isUser) 16.dp else 4.dp,
                        topEnd = if (isUser) 4.dp else 16.dp,
                        bottomStart = 16.dp,
                        bottomEnd = 16.dp,
                    )
                )
                .background(
                    Brush.verticalGradient(
                        listOf(accentColor.copy(alpha = 0.11f), T.surface.copy(alpha = 0.52f))
                    )
                )
                .border(
                    1.dp,
                    accentColor.copy(alpha = 0.35f),
                    RoundedCornerShape(
                        topStart = if (isUser) 16.dp else 4.dp,
                        topEnd = if (isUser) 4.dp else 16.dp,
                        bottomStart = 16.dp,
                        bottomEnd = 16.dp,
                    ),
                )
                .padding(horizontal = 12.dp, vertical = 8.dp),
        ) {
            Column {
                if (isToolResult) {
                    Text(
                        "TOOL ${message.toolName}",
                        color = T.warning,
                        style = MaterialTheme.typography.labelSmall,
                    )
                    Spacer(Modifier.height(3.dp))
                }
                Text(
                    text = message.content + if (isStreaming) " |" else "",
                    color = if (isUser) T.onSurface else T.textAccent,
                    style = MaterialTheme.typography.bodyMedium.copy(fontSize = 13.sp, lineHeight = 18.sp),
                )
            }
        }
    }
}

@Composable
private fun NeonInputBar(
    text: String,
    onTextChange: (String) -> Unit,
    isStreaming: Boolean,
    onSend: () -> Unit,
    onStop: () -> Unit,
) {
    val inputBorder = T.accent.copy(alpha = 0.35f)
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(T.surface)
            .drawBehind {
                drawLine(inputBorder, Offset(0f, 0f), Offset(size.width, 0f), 1f)
            }
            .padding(horizontal = 10.dp, vertical = 8.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(8.dp),
    ) {
        OutlinedTextField(
            value = text,
            onValueChange = onTextChange,
            placeholder = { Text("Ask the Brain...", color = T.onSurfaceMid, style = MaterialTheme.typography.bodySmall) },
            modifier = Modifier.weight(1f),
            colors = neonTextFieldColors(),
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
            keyboardActions = KeyboardActions(onSend = { onSend() }),
            maxLines = 4,
            shape = RoundedCornerShape(9.dp),
            textStyle = MaterialTheme.typography.bodyMedium.copy(color = T.onSurface, fontSize = 13.sp),
        )
        Box(
            modifier = Modifier
                .size(42.dp)
                .clip(RoundedCornerShape(8.dp))
                .background(if (isStreaming) T.warning.copy(alpha = 0.2f) else T.accent)
                .border(1.dp, if (isStreaming) T.warning else T.accent, RoundedCornerShape(8.dp))
                .clickable { if (isStreaming) onStop() else onSend() },
            contentAlignment = Alignment.Center,
        ) {
            Icon(
                imageVector = if (isStreaming) Icons.Default.Stop else Icons.AutoMirrored.Filled.Send,
                contentDescription = null,
                tint = if (isStreaming) T.warning else if (T.isDark) Color.Black else Color.White,
                modifier = Modifier.size(18.dp),
            )
        }
    }
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun BrainEmptyState(onChipTap: (String) -> Unit) {
    val chips = listOf(
        "Subnet Recon",
        "Port Scan 192.168.1.1",
        "Traceroute 8.8.8.8",
        "SSL/TLS Inspector",
        "DNS Enumeration",
        "HTTP Headers Audit",
        "Termux Nmap Scan",
        "Tool Inventory",
    )

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 18.dp, start = 6.dp, end = 6.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(16.dp),
    ) {
        RadarPulse(modifier = Modifier.size(108.dp), color = T.graphics, rings = 3)

        Column(horizontalAlignment = Alignment.CenterHorizontally) {
            Text("OPTIX BRAIN", color = T.accent, style = MaterialTheme.typography.titleLarge)
            Spacer(Modifier.height(2.dp))
            Text(
                "AI Security Strategist & Recon Assistant",
                color = T.onSurfaceMid,
                style = MaterialTheme.typography.labelSmall,
            )
        }

        FlowRow(
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp),
            modifier = Modifier.fillMaxWidth(),
        ) {
            chips.forEach { label ->
                Box(
                    modifier = Modifier
                        .border(1.dp, T.accent.copy(alpha = 0.35f), RoundedCornerShape(18.dp))
                        .background(T.accent.copy(alpha = 0.08f), RoundedCornerShape(18.dp))
                        .clickable { onChipTap(label) }
                        .padding(horizontal = 12.dp, vertical = 7.dp),
                ) {
                    Text(label, color = T.onSurface, style = MaterialTheme.typography.bodySmall)
                }
            }
        }
    }
}

@Composable
private fun AiStatusStrip(
    viewModel: AiViewModel,
    onShowCommands: () -> Unit
) {
    val config by viewModel.providerConfig.collectAsState()
    val isConnected = config.provider != com.optix.android.domain.model.AiProviderType.OFFLINE
    
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(T.surfaceVar.copy(alpha = 0.5f))
            .border(1.dp, T.border.copy(alpha = 0.3f))
            .padding(horizontal = 12.dp, vertical = 6.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
            Box(Modifier.size(6.dp).background(if (isConnected) T.success else T.warning, CircleShape))
            Text(config.model.ifEmpty { "Mock" }, color = T.onSurfaceMid, style = MaterialTheme.typography.labelSmall)
        }
        
        Text("▾ CMDS", color = T.accent, style = MaterialTheme.typography.labelSmall, modifier = Modifier.clickable { onShowCommands() })
    }
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun CommandsSheet(onDismiss: () -> Unit) {
    val commandCategories = listOf(
        "Scanning" to listOf("network_scanner", "port_scanner", "lan_scanner", "netbios_scanner", "wifi_scanner", "traceroute", "packet_sniffer", "rping3_termux", "nmap_termux", "masscan_termux", "arp_scan", "ssh_audit", "legion_termux", "network_topology"),
        "DNS & Web" to listOf("dns_recon", "subdomain_enum", "http_inspector", "directory_fuzzer", "sqli_tester", "xss_scanner", "nikto_termux", "sqlmap_termux", "cors_checker", "security_headers", "jwt_analyzer"),
        "Exploits" to listOf("brute_force", "arp_spoofer", "hydra_termux", "metasploit_termux", "msfvenom_termux", "evil_twin", "deauth_attack"),
        "Utilities" to listOf("payload_generator", "reverse_shell_gen", "hash_cracker", "password_generator", "encoder_tool", "subnet_calculator", "hash_generator", "cipher_tool", "regex_tester")
    )
    Column(modifier = Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
        Text("AVAILABLE AI COMMANDS", color = T.accent, style = MaterialTheme.typography.titleMedium)
        LazyColumn(verticalArrangement = Arrangement.spacedBy(12.dp)) {
            items(commandCategories) { (category, tools) ->
                Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
                    Text(category.uppercase(), color = T.onSurfaceMid, style = MaterialTheme.typography.labelSmall)
                    FlowRow(
                        horizontalArrangement = Arrangement.spacedBy(6.dp),
                        verticalArrangement = Arrangement.spacedBy(6.dp)
                    ) {
                        tools.forEach { tool ->
                            Box(
                                modifier = Modifier
                                    .background(T.surfaceVar, RoundedCornerShape(4.dp))
                                    .border(1.dp, T.border, RoundedCornerShape(4.dp))
                                    .padding(horizontal = 6.dp, vertical = 2.dp)
                            ) {
                                Text(tool, color = T.onSurface, style = MaterialTheme.typography.bodySmall.copy(fontSize = 11.sp))
                            }
                        }
                    }
                }
            }
        }
        Spacer(Modifier.height(16.dp))
    }
}
