package eu.gaudian.translator.view.dictionary

import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.foundation.BorderStroke
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.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.SuggestionChipDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
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.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.BaselineShift
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import eu.gaudian.translator.R
import eu.gaudian.translator.model.Language
import eu.gaudian.translator.model.grammar.DictionaryEntryData
import eu.gaudian.translator.model.grammar.EtymologyData
import eu.gaudian.translator.model.grammar.GrammaticalFeaturesData
import eu.gaudian.translator.model.grammar.Inflection
import eu.gaudian.translator.model.grammar.LanguageConfig
import eu.gaudian.translator.model.grammar.SenseData
import eu.gaudian.translator.model.grammar.UnifiedMorphology
import eu.gaudian.translator.model.grammar.UnifiedMorphologyParser
import eu.gaudian.translator.utils.dictionary.LocalDictionaryWordInfo
import eu.gaudian.translator.utils.dictionary.PartOfSpeechTranslator
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.view.composable.AutoResizeSingleLineText
import eu.gaudian.translator.viewmodel.DictionaryViewModel
import eu.gaudian.translator.viewmodel.LanguageConfigViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

// Main component that orchestrates all the sections
@Composable
fun RichLocalEntryDisplay(
    word: String,
    langCode: String,
    pos: String?,
    data: DictionaryEntryData,
    localInfo: LocalDictionaryWordInfo? = null,
    onWordClick: ((String, String) -> Unit)? = null,
    dictionaryViewModel: DictionaryViewModel,
    allLanguages: List<Language>,
    expandable: Boolean = true, // Enables whole-entry collapsing
    initiallyExpanded: Boolean = true // Default state
) {
    val activity = LocalContext.current.findActivity()
    val languageConfigViewModel: LanguageConfigViewModel = hiltViewModel(activity)
    val allConfigs by languageConfigViewModel.configs.collectAsState()
    val languageConfig = allConfigs[langCode]

    // State for the whole entry
    var isEntryExpanded by remember { mutableStateOf(initiallyExpanded) }

    // Cache to store which words are clickable (exist in DB)
    val clickableWordsCache = remember { mutableStateMapOf<String, Boolean>() }

    // Asynchronously check related words/translations
    LaunchedEffect(localInfo, data) {
        withContext(Dispatchers.IO) {
            val wordsToCheck = mutableListOf<Pair<String, String>>()
            // 1. Gather Translations
            localInfo?.translations?.forEach { wordsToCheck.add(it.languageCode to it.word) }
                ?: data.translations.forEach { wordsToCheck.add(it.languageCode to it.word) }
            // 2. Gather Relations
            localInfo?.relatedWords?.forEach { wordsToCheck.add(langCode to it.word) }
                ?: data.allRelatedWords.forEach { wordsToCheck.add(langCode to it.word) }
            // 3. Batch Check
            wordsToCheck.distinct().forEach { (lCode, w) ->
                val targetLang = allLanguages.firstOrNull { it.code.equals(lCode, ignoreCase = true) }
                val exists = if (targetLang != null) {
                    dictionaryViewModel.hasWordInDictionary(w, targetLang.code.lowercase())
                } else false
                clickableWordsCache["$lCode:$w"] = exists
            }
        }
    }

    val isWordClickableAsync: (String, String) -> Boolean = { lCode, w ->
        clickableWordsCache["$lCode:$w"] == true
    }

    // Outer Container
    Column(
        verticalArrangement = Arrangement.spacedBy(16.dp),
        modifier = Modifier.animateContentSize(animationSpec = spring(stiffness = Spring.StiffnessMediumLow))
    ) {

        // --- PRIMARY BLOCK: Header + Definitions ---
        Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {

            // Header is always visible. It acts as the toggle if expandable is true.
            LocalEntryHeaderSection(
                word = word,
                pos = pos,
                data = data,
                isExpanded = isEntryExpanded,
                onHeaderClick = if (expandable) { { isEntryExpanded = !isEntryExpanded } } else null,
                // Visual connection logic:
                // If Expanded AND has senses: Flat bottom to connect to senses.
                // Else (Collapsed OR no senses): Rounded bottom (standalone card).
                shape = if (isEntryExpanded && data.senses.isNotEmpty()) RoundedCornerShape(
                    topStart = 24.dp,
                    topEnd = 24.dp,
                    bottomStart = 4.dp,
                    bottomEnd = 4.dp
                ) else RoundedCornerShape(24.dp)
            )

            // Definitions appear only when expanded
            if (isEntryExpanded && data.senses.isNotEmpty()) {
                LocalEntrySensesSection(
                    data = data
                )
            }
        }

        // --- SECONDARY BLOCKS (Metadata) ---
        // These only appear when the entry is expanded
        if (isEntryExpanded) {
            // 1. Grammar / Forms
            if (languageConfig != null) {
                LocalEntryGrammarSection(
                    word = word,
                    langCode = langCode,
                    pos = pos,
                    data = data,
                    languageConfig = languageConfig
                )
            }

            // 2. Etymology
            LocalEntryEtymologySection(data = data)

            // 3. Translations
            LocalEntryTranslationsSection(
                localInfo = localInfo,
                data = data,
                allLanguages = allLanguages,
                isWordClickableAsync = isWordClickableAsync,
                onWordClick = onWordClick
            )

            // 4. Relations
            LocalEntryRelationsSection(
                localInfo = localInfo,
                data = data,
                langCode = langCode,
                allLanguages = allLanguages,
                isWordClickableAsync = isWordClickableAsync,
                onWordClick = onWordClick
            )
        }
    }
}

/**
 * A uniform expandable container for sections like Grammar, Etymology, etc.
 */
@Composable
fun ExpandableSectionCard(
    title: String,
    icon: ImageVector? = null,
    initiallyExpanded: Boolean = false,
    content: @Composable () -> Unit
) {
    var isExpanded by remember { mutableStateOf(initiallyExpanded) }

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .animateContentSize(animationSpec = spring(stiffness = Spring.StiffnessMediumLow)),
        shape = RoundedCornerShape(16.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(1.dp)
        ),
    ) {
        Column {
            // Header Row
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable { isExpanded = !isExpanded }
                    .padding(16.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    if (icon != null) {
                        Icon(
                            imageVector = icon,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.size(20.dp)
                        )
                        Spacer(modifier = Modifier.width(12.dp))
                    }
                    Text(
                        text = title,
                        style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold),
                        color = MaterialTheme.colorScheme.onSurface
                    )
                }

                Icon(
                    imageVector = if (isExpanded) AppIcons.ArrowDropUp else AppIcons.ArrowDropDown,
                    contentDescription = if (isExpanded) stringResource(R.string.label_collapse) else stringResource(R.string.label_expand),
                    tint = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }

            // Content
            if (isExpanded) {
                HorizontalDivider(
                    color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f),
                    modifier = Modifier.padding(horizontal = 16.dp)
                )
                Box(modifier = Modifier.padding(16.dp)) {
                    content()
                }
            }
        }
    }
}

@Composable
fun LocalEntryHeaderSection(
    word: String,
    pos: String?,
    data: DictionaryEntryData,
    shape: Shape = RoundedCornerShape(24.dp),
    isExpanded: Boolean = true,
    onHeaderClick: (() -> Unit)? = null
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .then(
                if (onHeaderClick != null) Modifier.clickable { onHeaderClick() } else Modifier
            ),
        shape = shape,
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(4.dp)
        )
    ) {
        Column(
            modifier = Modifier
                .padding(20.dp)
                .fillMaxWidth()
        ) {
            // Header Row: Word, POS, and Expand Arrow
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.Top // Align top to handle multiline words nicely
            ) {
                // Word and POS Column
                Column(modifier = Modifier.weight(1f)) {
                    AutoResizeSingleLineText(
                        text = word,
                        color = MaterialTheme.colorScheme.onSurface,
                        style = MaterialTheme.typography.displaySmall.copy(
                            fontWeight = FontWeight.Bold,
                            letterSpacing = (-0.5).sp,
                        )
                    )

                    if (!pos.isNullOrBlank()) {
                        Text(
                            text = PartOfSpeechTranslator.translatePos(pos),
                            style = MaterialTheme.typography.titleLarge,
                            fontStyle = FontStyle.Italic,
                            color = MaterialTheme.colorScheme.primary.copy(alpha = 0.9f)
                        )
                    }
                }

                // Expand Arrow (only if clickable)
                if (onHeaderClick != null) {
                    Icon(
                        imageVector = if (isExpanded) AppIcons.ArrowDropUp else AppIcons.ArrowDropDown,
                        contentDescription = if (isExpanded) stringResource(R.string.label_collapse) else stringResource(R.string.label_expand),
                        modifier = Modifier
                            .padding(start = 16.dp)
                            .size(28.dp),
                        tint = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }

            HorizontalDivider(
                modifier = Modifier.padding(vertical = 12.dp),
                thickness = 0.5.dp,
                color = MaterialTheme.colorScheme.outlineVariant
            )

            // Phonetics
            val phonetics = data.phonetics
            if (phonetics != null && (phonetics.ipa.isNotEmpty() || phonetics.variations.isNotEmpty())) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 4.dp),
                    verticalAlignment = Alignment.Top
                ) {
                    Icon(
                        imageVector = AppIcons.Speech,
                        contentDescription = stringResource(R.string.label_pronunciation),
                        modifier = Modifier
                            .padding(top = 6.dp, end = 12.dp)
                            .size(20.dp),
                        tint = MaterialTheme.colorScheme.primary
                    )

                    FlowRow(
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        phonetics.ipa.forEach { ipaString ->
                            PhoneticChip(ipa = ipaString, tags = emptyList())
                        }
                        phonetics.variations.forEach { variation ->
                            PhoneticChip(ipa = variation.ipa, tags = variation.rawTags)
                        }
                    }
                }
            }

            // Hyphenation
            val hyphenation = data.hyphenation
            if (hyphenation.isNotEmpty()) {
                Text(
                    text = buildAnnotatedString {
                        withStyle(SpanStyle(fontWeight = FontWeight.Light)) {
                            append(stringResource(R.string.label_grammar_hyphenation) + "  ")
                        }
                        append(hyphenation.joinToString(" • "))
                    },
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(top = 12.dp)
                )
            }

            // Grammatical Tags
            val tagLabels = data.allTags
            if (tagLabels.isNotEmpty()) {
                FlowRow(
                    modifier = Modifier.padding(top = 16.dp),
                    horizontalArrangement = Arrangement.spacedBy(6.dp),
                    verticalArrangement = Arrangement.spacedBy(6.dp)
                ) {
                    tagLabels.forEach { tag ->
                        SuggestionChip(
                            onClick = { /* No-op */ },
                            label = {
                                Text(
                                    tag,
                                    style = MaterialTheme.typography.labelMedium,
                                    fontWeight = FontWeight.Medium
                                )
                            },
                            shape = CircleShape,
                            border = BorderStroke(
                                1.dp,
                                MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
                            ),
                            colors = SuggestionChipDefaults.suggestionChipColors(
                                containerColor = Color.Transparent
                            ),
                        )
                    }
                }
            }
        }
    }
}

// 2. Senses Section
@Composable
private fun LocalEntrySensesSection(
    data: DictionaryEntryData
) {
    val senses = data.senses
    if (senses.isEmpty()) return

    Card(
        shape = RoundedCornerShape(
            topStart = 4.dp,
            topEnd = 4.dp,
            bottomStart = 24.dp,
            bottomEnd = 24.dp
        ),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(1.dp)
        ),
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(modifier = Modifier.padding(horizontal = 20.dp, vertical = 16.dp)) {
            Text(
                text = stringResource(R.string.label_grammar_meanings),
                style = MaterialTheme.typography.labelLarge,
                color = MaterialTheme.colorScheme.primary,
                modifier = Modifier.padding(bottom = 12.dp)
            )

            senses.forEachIndexed { index, senseData ->
                SenseDisplay(index = index, senseData = senseData)
                if (index < senses.lastIndex) {
                    Spacer(modifier = Modifier.height(16.dp))
                }
            }
        }
    }
}

// 3. Grammar Section
@Composable
fun GenericGridTable(grid: UnifiedMorphology.Grid) {
    if (grid.rowLabels.isEmpty() || grid.colLabels.isEmpty()) return

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .border(
                1.dp,
                MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f),
                RoundedCornerShape(8.dp)
            )
            .clip(RoundedCornerShape(8.dp))
    ) {
        // Header Row
        Row(
            modifier = Modifier
                .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f))
                .padding(8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // Title in the top-left corner
            AutoResizeSingleLineText(
                text = grid.title,
                style = MaterialTheme.typography.labelLarge,
                fontWeight = FontWeight.Medium,
                color = MaterialTheme.colorScheme.secondary,
                // CHANGED: Increased weight from 0.35f to 0.8f to give labels more space
                modifier = Modifier.weight(0.8f)
            )

            grid.colLabels.forEach { colKey ->
                Text(
                    text = colKey.replaceFirstChar { it.uppercase() },
                    style = MaterialTheme.typography.labelMedium,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.weight(1f)
                )
            }
        }

        HorizontalDivider(thickness = 0.5.dp, color = MaterialTheme.colorScheme.outlineVariant)

        // Data Rows
        grid.rowLabels.forEachIndexed { index, rowKey ->
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(
                        if (index % 2 == 1) MaterialTheme.colorScheme.surfaceVariant.copy(
                            alpha = 0.1f
                        ) else Color.Transparent
                    )
                    .padding(8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // Row Label (e.g. Nominative, Genitive)
                AutoResizeSingleLineText(
                    text = rowKey.replaceFirstChar { it.uppercase() },
                    style = MaterialTheme.typography.bodySmall,
                    fontWeight = FontWeight.Medium,
                    color = MaterialTheme.colorScheme.secondary,
                    // CHANGED: Must match the header weight (0.8f) to align columns
                    modifier = Modifier.weight(0.8f)
                )

                // Cells
                val hasSingleColumn = grid.colLabels.size == 1
                grid.colLabels.forEach { colKey ->
                    val cellKey = if (hasSingleColumn) rowKey else "$rowKey|$colKey"
                    AutoResizeSingleLineText(
                        text = grid.cells[cellKey] ?: "—",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurface,
                        modifier = Modifier.weight(1f)
                    )
                }
            }
        }
    }
}

@Composable
private fun LocalEntryGrammarSection(
    word: String,
    langCode: String,
    pos: String?,
    data: DictionaryEntryData,
    languageConfig: LanguageConfig
) {
    val context = LocalContext.current
    val morphology = remember(langCode, pos, data, languageConfig) {
        UnifiedMorphologyParser.parse(
            entry = data,
            lemma = word,
            pos = pos,
            langCode = langCode,
            config = languageConfig,
            context = context
        )
    }

    if (morphology != null) {
        ExpandableSectionCard(
            title = stringResource(R.string.label_grammar_inflections),
            icon = AppIcons.MenuBook
        ) {
            when (morphology) {
                is UnifiedMorphology.Verb -> {
                    val aux = morphology.auxiliary
                    if (aux != null) {
                        Text(
                            text = stringResource(R.string.label_grammar_auxiliary, aux),
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.secondary,
                            modifier = Modifier.padding(bottom = 8.dp)
                        )
                    }
                    UnifiedVerbTable(verbData = morphology)
                }

                is UnifiedMorphology.Grid -> {
                    // FIX: Removed the standalone Text(text = morphology.title)
                    // The title is now handled inside GenericGridTable
                    GenericGridTable(grid = morphology)
                }

                is UnifiedMorphology.ListForms -> {
                    InflectionTable(inflections = morphology.forms)
                }
            }
        }
    }
}

// 4. Etymology Section
@Composable
private fun LocalEntryEtymologySection(
    data: DictionaryEntryData
) {
    val etymologyList = data.etymology.texts

    if (etymologyList.isNotEmpty()) {
        ExpandableSectionCard(
            title = stringResource(R.string.label_etymology),
            icon = AppIcons.History
        ) {
            SelectionContainer {
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    etymologyList.forEach { rawText ->
                        val styledText = rememberEtymologyStyling(rawText)

                        Text(
                            text = styledText,
                            style = MaterialTheme.typography.bodyMedium.copy(
                                fontFamily = FontFamily.Serif,
                                lineHeight = 24.sp,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        )
                    }
                }
            }
        }
    }
}

// 5. Translations Section
@Composable
private fun LocalEntryTranslationsSection(
    localInfo: LocalDictionaryWordInfo?,
    data: DictionaryEntryData,
    allLanguages: List<Language>,
    isWordClickableAsync: (String, String) -> Boolean,
    onWordClick: ((String, String) -> Unit)?
) {
    val hasTranslations = !localInfo?.translations.isNullOrEmpty() || data.translations.isNotEmpty()
    if (!hasTranslations) return

    ExpandableSectionCard(
        title = stringResource(R.string.label_translations),
        icon = AppIcons.Translate
    ) {
        val infoTranslations = localInfo?.translations

        if (!infoTranslations.isNullOrEmpty()) {
            val grouped = infoTranslations.groupBy { it.languageCode }
            Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                grouped.forEach { (lang, list) ->
                    Column {
                        Text(
                            text = getLanguageName(lang, allLanguages),
                            style = MaterialTheme.typography.labelLarge,
                            color = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.padding(bottom = 4.dp)
                        )
                        CollapsibleFlowRow(items = list, maxLinesToShow = 4) { item ->
                            TranslationChip(
                                label = buildString {
                                    append(item.word)
                                    item.sense?.takeIf { it.isNotBlank() }?.let { append(" ($it)") }
                                },
                                isClickable = onWordClick != null && isWordClickableAsync(item.languageCode, item.word),
                                onClick = { onWordClick?.invoke(item.languageCode, item.word) }
                            )
                        }
                    }
                }
            }
        } else {
            // Fallback to data.translations
            val grouped = data.translations.groupBy { it.languageCode }
            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                grouped.forEach { (lang, list) ->
                    Row(verticalAlignment = Alignment.Top) {
                        Text(
                            text = "${getLanguageName(lang, allLanguages)}: ",
                            style = MaterialTheme.typography.bodyMedium,
                            fontWeight = FontWeight.Bold,
                            modifier = Modifier.width(90.dp)
                        )
                        val words = list.joinToString(", ") { item ->
                            val w = item.word
                            val sense = item.sense
                            if (!sense.isNullOrBlank()) "$w ($sense)" else w
                        }

                        SelectionContainer {
                            Text(
                                text = words,
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            }
        }
    }
}

// 6. Relations Section
@Composable
private fun LocalEntryRelationsSection(
    localInfo: LocalDictionaryWordInfo?,
    data: DictionaryEntryData,
    langCode: String,
    allLanguages: List<Language>,
    isWordClickableAsync: (String, String) -> Boolean,
    onWordClick: ((String, String) -> Unit)?
) {
    val hasRelations = !localInfo?.relatedWords.isNullOrEmpty() || data.relations.isNotEmpty()
    if (!hasRelations) return

    ExpandableSectionCard(
        title = stringResource(R.string.label_related_words),
        icon = AppIcons.Share
    ) {
        val relationsInfo = localInfo?.relatedWords
        if (!relationsInfo.isNullOrEmpty()) {
            val grouped = relationsInfo.groupBy { it.relationType }
            Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                grouped.toSortedMap().forEach { (relationType, list) ->
                    Column {
                        Text(
                            text = relationType.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() },
                            style = MaterialTheme.typography.labelLarge,
                            color = MaterialTheme.colorScheme.tertiary,
                            modifier = Modifier.padding(bottom = 4.dp)
                        )
                        CollapsibleFlowRow(items = list, maxLinesToShow = 3) { item ->
                            TranslationChip(
                                label = buildString {
                                    append(item.word)
                                    item.senseIndex?.takeIf { it.isNotBlank() }?.let { append(" ($it)") }
                                },
                                isClickable = onWordClick != null && isWordClickableAsync(langCode, item.word),
                                onClick = { onWordClick?.invoke(langCode, item.word) }
                            )
                        }
                    }
                }
            }
        } else {
            // Fallback for relations from data
            val relations = data.relations
            Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
                relations.entries.sortedBy { it.key }.forEach { (relationType, list) ->
                    if (list.isNotEmpty()) {
                        Row(
                            verticalAlignment = Alignment.Top,
                            modifier = Modifier.padding(vertical = 2.dp)
                        ) {
                            Text(
                                text = "${getLanguageName(relationType, allLanguages)}: ",
                                style = MaterialTheme.typography.bodyMedium,
                                fontWeight = FontWeight.Bold,
                                modifier = Modifier
                                    .width(96.dp)
                                    .padding(end = 4.dp)
                            )
                            val words = list.joinToString(", ") { item ->
                                val w = item.word
                                val senseIndex = item.senseIndex
                                if (!senseIndex.isNullOrBlank()) "$w ($senseIndex)" else w
                            }
                            SelectionContainer {
                                Text(
                                    text = words,
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}


// --- HELPERS AND TABLES ---



@Composable
fun UnifiedVerbTable(verbData: UnifiedMorphology.Verb) {
    Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
        verbData.tenses.forEach { (tenseLabel, forms) ->
            if (forms.isNotEmpty()) {
                Column {
                    Text(
                        text = tenseLabel,
                        style = MaterialTheme.typography.labelLarge,
                        color = MaterialTheme.colorScheme.primary,
                        modifier = Modifier.padding(bottom = 4.dp)
                    )

                    Column(
                        modifier = Modifier
                            .clip(RoundedCornerShape(8.dp))
                            .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.2f))
                    ) {
                        forms.indices.forEach { i ->
                            val pronoun = verbData.pronouns.getOrNull(i) ?: ""
                            val form = forms[i]

                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(horizontal = 12.dp, vertical = 8.dp)
                            ) {
                                Text(
                                    text = pronoun,
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = MaterialTheme.colorScheme.secondary,
                                    modifier = Modifier.width(80.dp)
                                )
                                Text(
                                    text = form,
                                    style = MaterialTheme.typography.bodyMedium,
                                    fontWeight = FontWeight.SemiBold,
                                    color = MaterialTheme.colorScheme.onSurface
                                )
                            }
                            if (i < forms.lastIndex) {
                                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.2f))
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun InflectionTable(inflections: List<Inflection>) {
    val visibleRows = inflections.filter { it.form.isNotBlank() }
    if (visibleRows.isEmpty()) return

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .border(
                1.dp,
                MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f),
                RoundedCornerShape(8.dp)
            )
            .clip(RoundedCornerShape(8.dp))
    ) {
        visibleRows.forEachIndexed { index, item ->
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(
                        if (index % 2 == 1) MaterialTheme.colorScheme.surfaceVariant.copy(
                            alpha = 0.1f
                        ) else Color.Transparent
                    )
                    .padding(8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = item.form,
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.SemiBold,
                    modifier = Modifier.weight(1f)
                )
                Text(
                    text = item.tags.joinToString(", "),
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.weight(2f)
                )
            }
            if (index < visibleRows.lastIndex) {
                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.2f))
            }
        }
    }
}

@Composable
fun SenseDisplay(index: Int, senseData: SenseData) {
    // New feature: Collapsible examples
    // If examples exist, we show a toggle instead of flooding the screen
    val hasExamples = senseData.examples.isNotEmpty()
    var areExamplesExpanded by remember { mutableStateOf(false) }

    Column(modifier = Modifier
        .fillMaxWidth()
        .animateContentSize()) {
        Row(verticalAlignment = Alignment.Top) {
            Text(
                text = "${index + 1}.",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.secondary,
                modifier = Modifier.width(28.dp)
            )

            Column {
                senseData.glosses.forEach { gloss ->
                    SelectionContainer {
                        Text(
                            text = gloss,
                            style = MaterialTheme.typography.bodyLarge,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                    }
                }

                // Tags inline
                if (senseData.tags.isNotEmpty()) {
                    FlowRow(
                        modifier = Modifier.padding(top = 4.dp),
                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                    ) {
                        senseData.tags.forEach { tag ->
                            Text(
                                text = tag.uppercase(),
                                style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
                                color = MaterialTheme.colorScheme.secondary
                            )
                        }
                    }
                }

                // Collapsible Examples Section
                if (hasExamples) {
                    Spacer(modifier = Modifier.height(6.dp))

                    // Toggle Button
                    Row(
                        modifier = Modifier
                            .clickable { areExamplesExpanded = !areExamplesExpanded }
                            .padding(vertical = 4.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = if (areExamplesExpanded) stringResource(R.string.label_hide_examples)
                            else stringResource(R.string.label_show_examples),
                            style = MaterialTheme.typography.labelSmall,
                            color = MaterialTheme.colorScheme.primary,
                            fontWeight = FontWeight.Bold
                        )
                        Icon(
                            imageVector = if (areExamplesExpanded) AppIcons.ArrowDropUp else AppIcons.ArrowDropDown,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.size(16.dp)
                        )
                    }

                    // Actual Examples List
                    if (areExamplesExpanded) {
                        Column {
                            senseData.examples.forEach { ex ->
                                Row(modifier = Modifier.padding(vertical = 2.dp)) {
                                    Box(
                                        modifier = Modifier
                                            .padding(top = 6.dp, end = 8.dp)
                                            .size(4.dp)
                                            .clip(CircleShape)
                                            .background(MaterialTheme.colorScheme.primary.copy(alpha = 0.4f))
                                    )
                                    Text(
                                        text = ex,
                                        style = MaterialTheme.typography.bodyMedium,
                                        fontStyle = FontStyle.Italic,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun TranslationChip(
    label: String,
    isClickable: Boolean,
    onClick: () -> Unit
) {
    Text(
        text = label,
        style = MaterialTheme.typography.bodyMedium,
        color = if (isClickable) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface,
        modifier = Modifier
            .border(
                1.dp,
                if (isClickable) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.outlineVariant,
                RoundedCornerShape(8.dp)
            )
            .background(
                if (isClickable) MaterialTheme.colorScheme.primaryContainer else Color.Transparent,
                RoundedCornerShape(8.dp)
            )
            .padding(horizontal = 8.dp, vertical = 4.dp)
            .then(if (isClickable) Modifier.clickable { onClick() } else Modifier)
    )
}

@Composable
fun <T> CollapsibleFlowRow(
    items: List<T>,
    maxLinesToShow: Int,
    modifier: Modifier = Modifier,
    horizontalArrangement: Arrangement.Horizontal = Arrangement.spacedBy(8.dp),
    verticalArrangement: Arrangement.Vertical = Arrangement.spacedBy(4.dp),
    itemContent: @Composable (T) -> Unit
) {
    var isExpanded by remember { mutableStateOf(false) }
    // Simple heuristic
    val shouldShowCollapseButton = items.size > maxLinesToShow * 3

    Column(modifier = modifier) {
        FlowRow(
            horizontalArrangement = horizontalArrangement,
            verticalArrangement = verticalArrangement
        ) {
            val itemsToShow = if (shouldShowCollapseButton && !isExpanded) {
                items.take(maxLinesToShow * 3)
            } else {
                items
            }
            itemsToShow.forEach { item -> itemContent(item) }
        }

        if (shouldShowCollapseButton) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 4.dp)
                    .clickable { isExpanded = !isExpanded },
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = if (isExpanded) stringResource(R.string.label_show_less) else stringResource(R.string.label_more),
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.primary
                )
            }
        }
    }
}

@Composable
private fun PhoneticChip(
    ipa: String,
    tags: List<String>,
    modifier: Modifier = Modifier
) {
    Surface(
        modifier = modifier,
        shape = RoundedCornerShape(8.dp),
        color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.3f),
        border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.3f))
    ) {
        Row(
            modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            Text(
                text = "[$ipa]",
                style = MaterialTheme.typography.bodyMedium.copy(
                    fontFamily = FontFamily.Monospace,
                    fontWeight = FontWeight.SemiBold
                ),
                color = MaterialTheme.colorScheme.onSecondaryContainer
            )
            if (tags.isNotEmpty()) {
                Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
                    tags.forEach { tag ->
                        Text(
                            text = tag.uppercase(),
                            style = MaterialTheme.typography.labelSmall.copy(fontSize = 9.sp, fontWeight = FontWeight.Bold),
                            color = MaterialTheme.colorScheme.primary,
                            modifier = Modifier
                                .border(
                                    1.dp,
                                    MaterialTheme.colorScheme.primary.copy(alpha = 0.3f),
                                    RoundedCornerShape(4.dp)
                                )
                                .padding(horizontal = 4.dp, vertical = 2.dp)
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun rememberEtymologyStyling(text: String): AnnotatedString {
    val primaryColor = MaterialTheme.colorScheme.primary
    val definitionColor = MaterialTheme.colorScheme.secondary
    return remember(text) {
        buildAnnotatedString {
            @Suppress("HardCodedStringLiteral") val pattern = Regex("(\\^\\(→\\s*\\w+\\))|(‚[^‘]+‘)")
            var lastIndex = 0
            pattern.findAll(text).forEach { match ->
                append(text.substring(lastIndex, match.range.first))
                val value = match.value
                if (value.startsWith("^")) {
                    val code = value.substringAfter("→").substringBefore(")").trim()
                    withStyle(SpanStyle(fontSize = 10.sp, color = primaryColor, fontWeight = FontWeight.Bold, baselineShift = BaselineShift.Superscript)) {
                        append(code.uppercase())
                    }
                } else {
                    withStyle(SpanStyle(fontStyle = FontStyle.Italic, color = definitionColor, fontWeight = FontWeight.Medium)) {
                        append(value)
                    }
                }
                lastIndex = match.range.last + 1
            }
            append(text.substring(lastIndex))
        }
    }
}

private fun getLanguageName(languageCode: String, allLanguages: List<Language>): String {
    return allLanguages.find { it.code.equals(languageCode, ignoreCase = true) }?.name
        ?: languageCode
}

@Suppress("HardCodedStringLiteral")
@Preview(showBackground = true)
@Composable
private fun LocalEntryHeaderSectionPreview() {
    val testData = DictionaryEntryData(
        translations = emptyList(),
        relations = emptyMap(),
        phonetics = null,
        hyphenation = listOf("hel", "lo"),
        etymology = EtymologyData(emptyList()),
        senses = emptyList(),
        grammaticalFeatures = GrammaticalFeaturesData(listOf("noun")),
        grammaticalProperties = null,
        pronunciation = emptyList(),
        inflections = emptyList(),
        forms = emptyList()
    )
    MaterialTheme {
        LocalEntryHeaderSection(word = "hello", pos = "noun", data = testData)
    }
}

// --- PREVIEWS ---

@Suppress("HardCodedStringLiteral")
@Preview(showBackground = true, name = "1. Header & Senses Combo")
@Composable
private fun HeaderAndSensesPreview() {
    val testData = DictionaryEntryData(
        translations = emptyList(),
        relations = emptyMap(),
        phonetics = null,
        hyphenation = listOf("Hund"),
        etymology = EtymologyData(emptyList()),
        senses = listOf(
            SenseData(
                glosses = listOf("Haustier, dessen Vorfahre der Wolf ist"),
                examples = listOf("Der Hund bellt laut.", "Vorsicht vor dem Hund!"),
                tags = listOf("Zoologie"),
                categories = emptyList(),
                topics = emptyList(),
                rawTags = emptyList(),
            ),
            SenseData(
                glosses = listOf("gerissener, gemeiner, hinterhältiger Mensch"),
                examples = emptyList(),
                tags = listOf("pejorative", "figurative"),
                categories = emptyList(),
                topics = emptyList(),
                rawTags = emptyList(),
            )
        ),
        grammaticalFeatures = GrammaticalFeaturesData(listOf("masculine", "singular")),
        grammaticalProperties = null,
        pronunciation = emptyList(),
        inflections = emptyList(),
        forms = emptyList(),
    )

    MaterialTheme {
        Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) {
            LocalEntryHeaderSection(
                word = "Hund",
                pos = "noun",
                data = testData,
                shape = RoundedCornerShape(
                    topStart = 24.dp,
                    topEnd = 24.dp,
                    bottomStart = 4.dp,
                    bottomEnd = 4.dp
                )
            )
            LocalEntrySensesSection(data = testData)
        }
    }
}

@Suppress("HardCodedStringLiteral")
@Preview(showBackground = true, name = "2. Grammar Section (Expanded)")
@Composable
private fun GrammarSectionPreview() {
    // Mocking a Grid for Noun Declension
    val mockGrid = UnifiedMorphology.Grid(
        title = "Declension",
        rowLabels = listOf("nominative", "genitive", "dative", "accusative"),
        colLabels = listOf("singular", "plural"),
        cells = mapOf(
            "nominative|singular" to "der Hund", "nominative|plural" to "die Hunde",
            "genitive|singular" to "des Hundes", "genitive|plural" to "der Hunde",
            "dative|singular" to "dem Hund", "dative|plural" to "den Hunden",
            "accusative|singular" to "den Hund", "accusative|plural" to "die Hunde"
        )
    )

    MaterialTheme {
        Column(modifier = Modifier.padding(16.dp)) {
            ExpandableSectionCard(
                title = "Inflections",
                icon = AppIcons.MenuBook,
                initiallyExpanded = true
            ) {
                GenericGridTable(grid = mockGrid)
            }
        }
    }
}

@Suppress("HardCodedStringLiteral")
@Preview(showBackground = true, name = "3. Etymology Section")
@Composable
private fun EtymologySectionPreview() {
    val rawText = "aus ^(→ gmh) hunt < ^(→ ine) *kwon-, daher auch griechisch κύων (kýōn) (siehe auch zynisch), lateinisch canis (Hund)."

    MaterialTheme {
        Column(modifier = Modifier.padding(16.dp)) {
            ExpandableSectionCard(
                title = "Etymology",
                icon = AppIcons.History,
                initiallyExpanded = true
            ) {
                SelectionContainer {
                    Text(
                        text = rememberEtymologyStyling(rawText),
                        style = MaterialTheme.typography.bodyMedium.copy(
                            fontFamily = FontFamily.Serif,
                            lineHeight = 24.sp,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    )
                }
            }
        }
    }
}

@Suppress("HardCodedStringLiteral")
@Preview(showBackground = true, name = "4. Translations Section")
@Composable
private fun TranslationsSectionPreview() {
    MaterialTheme {
        Column(modifier = Modifier.padding(16.dp)) {
            ExpandableSectionCard(
                title = "Translations",
                icon = AppIcons.Translate, // Ensure this icon exists or use a placeholder
                initiallyExpanded = true
            ) {
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    // English Group
                    Column {
                        Text(
                            text = "English",
                            style = MaterialTheme.typography.labelLarge,
                            color = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.padding(bottom = 4.dp)
                        )
                        FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                            TranslationChip(label = "dog (1)", isClickable = true) {}
                            TranslationChip(label = "hound (1)", isClickable = true) {}
                            TranslationChip(label = "scoundrel (2)", isClickable = false) {}
                        }
                    }

                    // French Group
                    Column {
                        Text(
                            text = "French",
                            style = MaterialTheme.typography.labelLarge,
                            color = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.padding(bottom = 4.dp)
                        )
                        FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                            TranslationChip(label = "chien (1)", isClickable = true) {}
                            TranslationChip(label = "canaille (2)", isClickable = true) {}
                        }
                    }
                }
            }
        }
    }
}