// Copyright (C) 2026 Jason M. Schwefel. All Rights Reserved.
package com.coldboreballisticsllc.scopedope.ui.screens.settings

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.LocationManager
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.hilt.navigation.compose.hiltViewModel
import kotlin.math.absoluteValue
import com.coldboreballisticsllc.scopedope.data.prefs.StoredPrinterEntry
import com.coldboreballisticsllc.scopedope.label.renderer.ElevationSymbol
import com.coldboreballisticsllc.scopedope.ui.components.InstrumentPanel
import com.coldboreballisticsllc.scopedope.ui.components.SectionDivider
import com.coldboreballisticsllc.scopedope.ui.session.*
import com.coldboreballisticsllc.scopedope.ui.session.PrinterViewModel
import com.coldboreballisticsllc.scopedope.ui.session.SensorViewModel
import com.coldboreballisticsllc.scopedope.ui.theme.*

internal fun captureCoarseLatitude(context: Context): Double? {
    val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    return try {
        listOf(
            LocationManager.NETWORK_PROVIDER,
            LocationManager.GPS_PROVIDER,
            LocationManager.PASSIVE_PROVIDER,
        ).firstNotNullOfOrNull { p ->
            runCatching { lm.getLastKnownLocation(p) }.getOrNull()?.latitude
        }
    } catch (_: SecurityException) { null }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AdvancedSettingsScreen(
    onBack:    () -> Unit,
    sessionVm: SessionViewModel = hiltViewModel(),
    printerVm: PrinterViewModel = hiltViewModel(),
    sensorVm:  SensorViewModel  = hiltViewModel(),
) {
    val state          by sessionVm.state.collectAsState()
    val printerUiState by printerVm.uiState.collectAsState()
    val sensorUiState  by sensorVm.uiState.collectAsState()
    val sensorDriverId by sensorVm.sensorDriverId.collectAsState()
    val context        = LocalContext.current

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Advanced Settings", style = MaterialTheme.typography.titleLarge) },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor    = ColorBackground,
                    titleContentColor = ColorTextPrimary,
                ),
            )
        },
        containerColor = ColorBackground,
    ) { padding ->
        Column(
            modifier = Modifier
                .padding(padding)
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            // ── Ballistics engine ─────────────────────────────────────────────
            val realDopeEnabled = state.dopeEntries.size >= 3
            InstrumentPanel(label = "Ballistics Engine") {
                Row(
                    modifier          = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween,
                ) {
                    Column(Modifier.weight(1f)) {
                        Text(
                            text  = "Use Real DOPE Data",
                            style = SettingsBodyStyle,
                            color = ColorTextPrimary,
                        )
                        Text(
                            text  = when {
                                !realDopeEnabled && !state.useRealDope ->
                                    "Requires at least 3 confirmed impacts"
                                state.useRealDope ->
                                    "Blending your confirmed range data with physics"
                                else ->
                                    "Pure ballistics physics — DOPE entries ignored"
                            },
                            style = SettingsBodySubStyle,
                            color = when {
                                !realDopeEnabled && !state.useRealDope -> ColorTextMuted
                                state.useRealDope -> ColorAmber
                                else -> ColorTextMuted
                            },
                        )
                    }
                    Switch(
                        checked         = state.useRealDope,
                        onCheckedChange = sessionVm::setUseRealDope,
                        enabled         = realDopeEnabled || state.useRealDope,
                        colors          = SwitchDefaults.colors(
                            checkedThumbColor  = ColorBackground,
                            checkedTrackColor  = ColorAmber,
                        ),
                    )
                }
            }

            // ── Corrections ───────────────────────────────────────────────────
            val coriolisEnabled = state.useCoriolis
            val capturedLat     = state.coriolisLatitudeDeg

            val locationLauncher = rememberLauncherForActivityResult(
                ActivityResultContracts.RequestPermission()
            ) { granted ->
                if (granted) {
                    val lat = captureCoarseLatitude(context)
                    if (lat != null) sessionVm.setCoriolisLatitude(lat)
                    sessionVm.setUseCoriolis(true)
                }
            }

            InstrumentPanel(label = "Corrections") {
                Row(
                    modifier              = Modifier.fillMaxWidth(),
                    verticalAlignment     = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween,
                ) {
                    Column(Modifier.weight(1f)) {
                        Text(
                            text  = "Coriolis Effect",
                            style = SettingsBodyStyle,
                            color = ColorTextPrimary,
                        )
                        Text(
                            text  = "Earth-rotation correction for elevation and windage",
                            style = SettingsBodySubStyle,
                            color = ColorTextMuted,
                        )
                    }
                    Switch(
                        checked         = coriolisEnabled,
                        onCheckedChange = { enable ->
                            if (enable) {
                                val hasPerm = ContextCompat.checkSelfPermission(
                                    context, Manifest.permission.ACCESS_COARSE_LOCATION
                                ) == PackageManager.PERMISSION_GRANTED
                                if (hasPerm) {
                                    val lat = captureCoarseLatitude(context)
                                    if (lat != null) sessionVm.setCoriolisLatitude(lat)
                                    sessionVm.setUseCoriolis(true)
                                } else {
                                    locationLauncher.launch(Manifest.permission.ACCESS_COARSE_LOCATION)
                                }
                            } else {
                                sessionVm.setUseCoriolis(false)
                            }
                        },
                        colors = SwitchDefaults.colors(
                            checkedThumbColor = ColorBackground,
                            checkedTrackColor = ColorAmber,
                        ),
                    )
                }

                SectionDivider(Modifier.padding(vertical = 6.dp))

                Text(
                    text  = "Latitude is captured from this device's location services for the " +
                            "spin-of-the-Earth calculation only. It is never stored remotely, " +
                            "transmitted over the internet, or used for any other purpose.",
                    style = SettingsBodySubStyle,
                    color = ColorTextMuted,
                )

                if (coriolisEnabled) {
                    Spacer(Modifier.height(4.dp))
                    val latStr = if (capturedLat == 0.0) {
                        "Latitude unavailable — toggle off and on to retry"
                    } else {
                        val dir = if (capturedLat >= 0) "N" else "S"
                        "Latitude: ${"%.2f".format(capturedLat.absoluteValue)}° $dir"
                    }
                    Text(
                        text  = latStr,
                        style = SettingsBodySubStyle,
                        color = if (capturedLat == 0.0) ColorTextMuted else ColorAmber,
                    )
                }
            }

            // ── Measurement units ─────────────────────────────────────────────
            InstrumentPanel(label = "Measurement Units") {
                Text(
                    text  = "Overrides the per-field unit regardless of the Measurement System setting. " +
                            "Changing Measurement System in Settings resets all fields to system defaults.",
                    style = SettingsBodySubStyle,
                    color = ColorTextMuted,
                )

                SectionDivider(Modifier.padding(vertical = 8.dp))

                // Altitude
                Text("Altitude", style = SettingsBodyStyle, color = ColorTextPrimary)
                AltitudeUnit.entries.forEach { unit ->
                    Row(
                        modifier          = Modifier
                            .fillMaxWidth()
                            .clickable { sessionVm.setAltitudeUnit(unit) }
                            .padding(vertical = 2.dp),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        RadioButton(
                            selected = state.conditionUnits.altitude == unit,
                            onClick  = { sessionVm.setAltitudeUnit(unit) },
                            colors   = RadioButtonDefaults.colors(selectedColor = ColorAmber),
                        )
                        Spacer(Modifier.width(8.dp))
                        Text(unit.suffix, style = SettingsBodyStyle, color = ColorTextPrimary)
                    }
                }

                SectionDivider(Modifier.padding(vertical = 8.dp))

                // Temperature
                Text("Temperature", style = SettingsBodyStyle, color = ColorTextPrimary)
                TempUnit.entries.forEach { unit ->
                    Row(
                        modifier          = Modifier
                            .fillMaxWidth()
                            .clickable { sessionVm.setTempUnit(unit) }
                            .padding(vertical = 2.dp),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        RadioButton(
                            selected = state.conditionUnits.temp == unit,
                            onClick  = { sessionVm.setTempUnit(unit) },
                            colors   = RadioButtonDefaults.colors(selectedColor = ColorAmber),
                        )
                        Spacer(Modifier.width(8.dp))
                        Column {
                            Text(unit.suffix, style = SettingsBodyStyle, color = ColorTextPrimary)
                            if (unit == TempUnit.K) {
                                Text("Kelvin — absolute temperature scale", style = SettingsBodySubStyle, color = ColorTextMuted)
                            }
                        }
                    }
                }

                SectionDivider(Modifier.padding(vertical = 8.dp))

                // Pressure
                Text("Pressure", style = SettingsBodyStyle, color = ColorTextPrimary)
                val pressureDescriptions = mapOf(
                    PressureUnit.INHG to "Inches of mercury — US standard",
                    PressureUnit.HPA  to "Hectopascal — international meteorology standard",
                    PressureUnit.MBAR to "Millibar — same value as hPa, older convention",
                    PressureUnit.MMHG to "Millimeters of mercury — used in some instruments",
                    PressureUnit.KPA  to "Kilopascal — SI unit",
                )
                PressureUnit.entries.forEach { unit ->
                    Row(
                        modifier          = Modifier
                            .fillMaxWidth()
                            .clickable { sessionVm.setPressureUnit(unit) }
                            .padding(vertical = 2.dp),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        RadioButton(
                            selected = state.conditionUnits.pressure == unit,
                            onClick  = { sessionVm.setPressureUnit(unit) },
                            colors   = RadioButtonDefaults.colors(selectedColor = ColorAmber),
                        )
                        Spacer(Modifier.width(8.dp))
                        Column {
                            Text(unit.suffix, style = SettingsBodyStyle, color = ColorTextPrimary)
                            pressureDescriptions[unit]?.let {
                                Text(it, style = SettingsBodySubStyle, color = ColorTextMuted)
                            }
                        }
                    }
                }

                SectionDivider(Modifier.padding(vertical = 8.dp))

                // Wind speed
                Text("Wind Speed", style = SettingsBodyStyle, color = ColorTextPrimary)
                val windDescriptions = mapOf(
                    WindSpeedUnit.MPH to "Miles per hour — US standard",
                    WindSpeedUnit.KPH to "Kilometers per hour — metric standard",
                    WindSpeedUnit.MPS to "Meters per second — scientific / ballistics",
                    WindSpeedUnit.KTS to "Knots — aviation and marine",
                )
                WindSpeedUnit.entries.forEach { unit ->
                    Row(
                        modifier          = Modifier
                            .fillMaxWidth()
                            .clickable { sessionVm.setWindSpeedUnit(unit) }
                            .padding(vertical = 2.dp),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        RadioButton(
                            selected = state.conditionUnits.windSpeed == unit,
                            onClick  = { sessionVm.setWindSpeedUnit(unit) },
                            colors   = RadioButtonDefaults.colors(selectedColor = ColorAmber),
                        )
                        Spacer(Modifier.width(8.dp))
                        Column {
                            Text(unit.suffix, style = SettingsBodyStyle, color = ColorTextPrimary)
                            windDescriptions[unit]?.let {
                                Text(it, style = SettingsBodySubStyle, color = ColorTextMuted)
                            }
                        }
                    }
                }
            }

            // ── Label appearance ──────────────────────────────────────────────
            InstrumentPanel(label = "Label Appearance") {
                // Gridlines
                Row(
                    modifier          = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween,
                ) {
                    Column(Modifier.weight(1f)) {
                        Text(
                            text  = "Gridlines",
                            style = SettingsBodyStyle,
                            color = ColorTextPrimary,
                        )
                        Text(
                            text  = if (printerUiState.showGridlines) "Row separators and column divider visible"
                                    else "Clean label — no grid lines",
                            style = SettingsBodySubStyle,
                            color = ColorTextMuted,
                        )
                    }
                    Switch(
                        checked         = printerUiState.showGridlines,
                        onCheckedChange = printerVm::setShowGridlines,
                        colors          = SwitchDefaults.colors(
                            checkedThumbColor = ColorBackground,
                            checkedTrackColor = ColorAmber,
                        ),
                    )
                }

                SectionDivider(Modifier.padding(vertical = 6.dp))

                // Color mode
                Row(
                    modifier          = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween,
                ) {
                    Column(Modifier.weight(1f)) {
                        Text(
                            text  = "Color Mode",
                            style = SettingsBodyStyle,
                            color = ColorTextPrimary,
                        )
                        Text(
                            text  = if (printerUiState.useSemanticColors)
                                "Semantic: blue distances, green/red elevation, amber windage"
                            else
                                "Monochrome: black and white (default)",
                            style = SettingsBodySubStyle,
                            color = ColorTextMuted,
                        )
                    }
                    Switch(
                        checked         = printerUiState.useSemanticColors,
                        onCheckedChange = printerVm::setUseSemanticColors,
                        colors          = SwitchDefaults.colors(
                            checkedThumbColor = ColorBackground,
                            checkedTrackColor = ColorAmber,
                        ),
                    )
                }

                SectionDivider(Modifier.padding(vertical = 6.dp))

                // Elevation symbol
                Text(
                    text  = "Elevation Symbol",
                    style = SettingsBodyStyle,
                    color = ColorTextPrimary,
                )
                ElevationSymbol.entries.forEach { sym ->
                    Row(
                        modifier          = Modifier
                            .fillMaxWidth()
                            .clickable { printerVm.setElevationSymbol(sym) }
                            .padding(vertical = 4.dp),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        RadioButton(
                            selected = printerUiState.elevationSymbol == sym,
                            onClick  = { printerVm.setElevationSymbol(sym) },
                            colors   = RadioButtonDefaults.colors(selectedColor = ColorAmber),
                        )
                        Spacer(Modifier.width(8.dp))
                        Text(
                            text  = when (sym) {
                                ElevationSymbol.PLUS_MINUS -> "+3.5 / -3.5  (default)"
                                ElevationSymbol.ARROWS     -> "↑3.5 / ↓3.5"
                            },
                            style = SettingsBodyStyle,
                            color = ColorTextPrimary,
                        )
                    }
                }

                SectionDivider(Modifier.padding(vertical = 6.dp))

                // Column fill order
                Text(
                    text  = "Column Fill Order",
                    style = SettingsBodyStyle,
                    color = ColorTextPrimary,
                )
                Text(
                    text  = "Controls how entries are distributed across multi-column labels",
                    style = SettingsBodySubStyle,
                    color = ColorTextMuted,
                )
                Spacer(Modifier.height(2.dp))
                listOf(true, false).forEach { interleaved ->
                    Row(
                        modifier          = Modifier
                            .fillMaxWidth()
                            .clickable { printerVm.setColumnFillInterleaved(interleaved) }
                            .padding(vertical = 4.dp),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        RadioButton(
                            selected = printerUiState.columnFillInterleaved == interleaved,
                            onClick  = { printerVm.setColumnFillInterleaved(interleaved) },
                            colors   = RadioButtonDefaults.colors(selectedColor = ColorAmber),
                        )
                        Spacer(Modifier.width(8.dp))
                        Column {
                            Text(
                                text  = if (interleaved) "Interleaved (default)" else "Fill column first",
                                style = SettingsBodyStyle,
                                color = ColorTextPrimary,
                            )
                            Text(
                                text  = if (interleaved) "Pairs per row: entries 1+2, 3+4, 5+6, 7+8"
                                        else "Column 1 full before column 2: entries 1-4, then 5-8",
                                style = SettingsBodySubStyle,
                                color = ColorTextMuted,
                            )
                        }
                    }
                }
            }

            // ── Printer ───────────────────────────────────────────────────────
            var renamingPrinter by remember { mutableStateOf<StoredPrinterEntry?>(null) }

            renamingPrinter?.let { target ->
                var draft by remember(target.mac) { mutableStateOf(target.friendlyName) }
                AlertDialog(
                    onDismissRequest = { renamingPrinter = null },
                    title   = { Text("Rename Printer", color = ColorTextPrimary) },
                    text    = {
                        OutlinedTextField(
                            value         = draft,
                            onValueChange = { draft = it },
                            label         = { Text("Friendly name") },
                            placeholder   = { Text(target.btName) },
                            singleLine    = true,
                            colors        = OutlinedTextFieldDefaults.colors(
                                focusedBorderColor   = ColorAmber,
                                unfocusedBorderColor = ColorBorder,
                                focusedLabelColor    = ColorAmber,
                                unfocusedLabelColor  = ColorTextMuted,
                                focusedTextColor     = ColorTextPrimary,
                                unfocusedTextColor   = ColorTextPrimary,
                                cursorColor          = ColorAmber,
                            ),
                        )
                    },
                    confirmButton = {
                        TextButton(onClick = {
                            printerVm.renamePrinter(target.mac, target.btName, draft)
                            renamingPrinter = null
                        }) { Text("Save", color = ColorAmber) }
                    },
                    dismissButton = {
                        TextButton(onClick = { renamingPrinter = null }) {
                            Text("Cancel", color = ColorTextMuted)
                        }
                    },
                    containerColor = ColorBackground,
                )
            }

            InstrumentPanel(label = "Printer") {
                // Shared mode toggle
                Row(
                    modifier              = Modifier.fillMaxWidth(),
                    verticalAlignment     = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween,
                ) {
                    Column(Modifier.weight(1f)) {
                        Text(
                            text  = "Shared Mode",
                            style = SettingsBodyStyle,
                            color = ColorTextPrimary,
                        )
                        Text(
                            text  = if (printerUiState.printerSharedMode)
                                "Prints then auto-disconnects — ready for the next user"
                            else
                                "Stays connected after printing",
                            style = SettingsBodySubStyle,
                            color = ColorTextMuted,
                        )
                    }
                    Switch(
                        checked         = printerUiState.printerSharedMode,
                        onCheckedChange = printerVm::setPrinterSharedMode,
                        colors          = SwitchDefaults.colors(
                            checkedThumbColor = ColorBackground,
                            checkedTrackColor = ColorAmber,
                        ),
                    )
                }

                // Known printers list
                if (printerUiState.storedPrinters.isNotEmpty()) {
                    SectionDivider(Modifier.padding(vertical = 6.dp))
                    Text(
                        text  = "Known Printers",
                        style = SettingsBodyStyle,
                        color = ColorTextPrimary,
                    )
                    Spacer(Modifier.height(2.dp))
                    printerUiState.storedPrinters.forEach { printer ->
                        Row(
                            modifier          = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 2.dp),
                            verticalAlignment = Alignment.CenterVertically,
                        ) {
                            Column(Modifier.weight(1f)) {
                                Text(
                                    text  = printer.friendlyName,
                                    style = SettingsBodySubStyle,
                                    color = ColorTextPrimary,
                                )
                                if (printer.friendlyName != printer.btName) {
                                    Text(
                                        text  = printer.btName,
                                        style = MaterialTheme.typography.labelSmall,
                                        color = ColorTextMuted,
                                    )
                                }
                            }
                            IconButton(onClick = { renamingPrinter = printer }) {
                                Icon(Icons.Default.Edit, contentDescription = "Rename", tint = ColorTextMuted)
                            }
                            IconButton(onClick = { printerVm.removeStoredPrinter(printer.mac) }) {
                                Icon(Icons.Default.Delete, contentDescription = "Remove", tint = ColorTextMuted)
                            }
                        }
                    }
                }

                // Print ID Label (only when connected)
                if (printerUiState.connectedPrinterMac != null) {
                    SectionDivider(Modifier.padding(vertical = 6.dp))
                    val displayName = printerUiState.connectedPrinterName ?: printerUiState.connectedPrinterBtName ?: ""
                    Text(
                        text  = "Connected: $displayName",
                        style = SettingsBodySubStyle,
                        color = ColorAmber,
                    )
                    Spacer(Modifier.height(6.dp))
                    OutlinedButton(
                        onClick  = { printerVm.printDeviceIdLabel(state.labelFormat) },
                        modifier = Modifier.fillMaxWidth(),
                        border   = BorderStroke(1.dp, ColorAmber),
                        colors   = ButtonDefaults.outlinedButtonColors(contentColor = ColorAmber),
                    ) {
                        Text("Print ID Label", style = SettingsBodySubStyle)
                    }
                    Spacer(Modifier.height(2.dp))
                    Text(
                        text  = "Prints BT name + friendly name — stick on the printer for easy identification",
                        style = SettingsBodySubStyle,
                        color = ColorTextMuted,
                    )
                }
            }

            // ── Weather sensor ────────────────────────────────────────────────
            InstrumentPanel(label = "Weather Sensor") {
                data class SensorOption(val id: String, val name: String, val description: String, val recommended: Boolean = false)
                val sensorOptions = listOf(
                    SensorOption(
                        id          = "weatherflow_tactical",
                        name        = "WeatherFlow Tactical",
                        description = "Bluetooth — wind speed, temperature, humidity, and pressure",
                        recommended = true,
                    ),
                    SensorOption(
                        id          = "btmeter_bt100",
                        name        = "BTMETER BT-100",
                        description = "Bluetooth anemometer — wind speed + temperature",
                    ),
                )
                sensorOptions.forEach { option ->
                    Row(
                        modifier          = Modifier
                            .fillMaxWidth()
                            .clickable { sensorVm.setSensorDriverId(option.id) }
                            .padding(vertical = 4.dp),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        RadioButton(
                            selected = sensorDriverId == option.id,
                            onClick  = { sensorVm.setSensorDriverId(option.id) },
                            colors   = RadioButtonDefaults.colors(selectedColor = ColorAmber),
                        )
                        Spacer(Modifier.width(8.dp))
                        Column {
                            Row(verticalAlignment = Alignment.CenterVertically) {
                                Text(
                                    text  = option.name,
                                    style = SettingsBodyStyle,
                                    color = ColorTextPrimary,
                                )
                                if (option.recommended) {
                                    Spacer(Modifier.width(6.dp))
                                    Surface(
                                        shape = MaterialTheme.shapes.small,
                                        color = ColorAmber.copy(alpha = 0.15f),
                                    ) {
                                        Text(
                                            text     = "Recommended",
                                            modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
                                            style    = MaterialTheme.typography.labelSmall,
                                            color    = ColorAmber,
                                        )
                                    }
                                }
                            }
                            Text(
                                text  = option.description,
                                style = SettingsBodySubStyle,
                                color = ColorTextMuted,
                            )
                        }
                    }
                }
                if (sensorDriverId == "weatherflow_tactical") {
                    SectionDivider(Modifier.padding(vertical = 6.dp))
                    Text(
                        text  = "Enable Bluetooth and tap Connect on the Conditions screen. " +
                                "The WeatherFlow Tactical connects directly via Bluetooth — no WiFi or hotspot required.",
                        style = SettingsBodySubStyle,
                        color = ColorTextMuted,
                    )
                    SectionDivider(Modifier.padding(vertical = 6.dp))
                    Row(
                        modifier              = Modifier.fillMaxWidth(),
                        verticalAlignment     = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween,
                    ) {
                        Column(Modifier.weight(1f)) {
                            Text(
                                text  = "Use Phone Compass for Wind Direction",
                                style = SettingsBodyStyle,
                                color = ColorTextPrimary,
                            )
                            Text(
                                text  = if (sensorUiState.usePhoneCompassWind)
                                    "Phone compass supplies wind bearing while sensor is connected"
                                else
                                    "Enter wind direction manually on the Conditions screen",
                                style = SettingsBodySubStyle,
                                color = ColorTextMuted,
                            )
                        }
                        Switch(
                            checked         = sensorUiState.usePhoneCompassWind,
                            onCheckedChange = sensorVm::setUsePhoneCompassWind,
                            colors          = SwitchDefaults.colors(
                                checkedThumbColor = ColorBackground,
                                checkedTrackColor = ColorAmber,
                            ),
                        )
                    }
                }

                // ── Sensor name ───────────────────────────────────────────────
                SectionDivider(Modifier.padding(vertical = 6.dp))
                Text("Sensor Name", style = SettingsBodyStyle, color = ColorTextPrimary)
                Text(
                    text  = "Optional label shown in the Conditions panel instead of the driver name",
                    style = SettingsBodySubStyle,
                    color = ColorTextMuted,
                )
                Spacer(Modifier.height(4.dp))
                var sensorNameDraft by remember(sensorDriverId) { mutableStateOf(sensorUiState.sensorFriendlyName ?: "") }
                Row(
                    modifier              = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment     = Alignment.CenterVertically,
                ) {
                    OutlinedTextField(
                        value         = sensorNameDraft,
                        onValueChange = { sensorNameDraft = it },
                        label         = { Text("Friendly name") },
                        placeholder   = {
                            Text(
                                if (sensorDriverId == "weatherflow_tactical") "WeatherFlow Tactical"
                                else "BTMETER BT-100 Anemometer"
                            )
                        },
                        singleLine = true,
                        modifier   = Modifier.weight(1f),
                        colors     = OutlinedTextFieldDefaults.colors(
                            focusedBorderColor   = ColorAmber,
                            unfocusedBorderColor = ColorBorder,
                            focusedLabelColor    = ColorAmber,
                            unfocusedLabelColor  = ColorTextMuted,
                            focusedTextColor     = ColorTextPrimary,
                            unfocusedTextColor   = ColorTextPrimary,
                            cursorColor          = ColorAmber,
                        ),
                    )
                    OutlinedButton(
                        onClick = { sensorVm.saveSensorFriendlyName(sensorNameDraft) },
                        border  = BorderStroke(1.dp, ColorAmber),
                        colors  = ButtonDefaults.outlinedButtonColors(contentColor = ColorAmber),
                    ) {
                        Text("Save", style = SettingsBodySubStyle)
                    }
                }

                // ── Sensor shared mode ────────────────────────────────────────
                SectionDivider(Modifier.padding(vertical = 6.dp))
                Row(
                    modifier              = Modifier.fillMaxWidth(),
                    verticalAlignment     = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween,
                ) {
                    Column(Modifier.weight(1f)) {
                        Text("Shared Mode", style = SettingsBodyStyle, color = ColorTextPrimary)
                        Text(
                            text  = "Auto-disconnect after capturing conditions",
                            style = SettingsBodySubStyle,
                            color = ColorTextMuted,
                        )
                    }
                    Switch(
                        checked         = sensorUiState.sensorSharedMode,
                        onCheckedChange = sensorVm::setSensorSharedMode,
                        colors          = SwitchDefaults.colors(
                            checkedThumbColor = ColorBackground,
                            checkedTrackColor = ColorAmber,
                        ),
                    )
                }

                if (sensorUiState.sensorSharedMode) {
                    Spacer(Modifier.height(6.dp))
                    data class SubModeOption(
                        val mode:        com.coldboreballisticsllc.scopedope.ui.session.SensorSharedSubMode,
                        val label:       String,
                        val description: String,
                    )
                    val subModes = listOf(
                        SubModeOption(
                            com.coldboreballisticsllc.scopedope.ui.session.SensorSharedSubMode.READ_ONCE,
                            "Read Once",
                            "Connect → receive one reading → disconnect",
                        ),
                        SubModeOption(
                            com.coldboreballisticsllc.scopedope.ui.session.SensorSharedSubMode.FREEZE_DISCONNECT,
                            "Freeze & Disconnect",
                            "Connect → receive reading → freeze conditions → disconnect",
                        ),
                        SubModeOption(
                            com.coldboreballisticsllc.scopedope.ui.session.SensorSharedSubMode.TIMED_WINDOW,
                            "Timed Window",
                            "Connect for a fixed number of seconds, then freeze and disconnect",
                        ),
                    )
                    subModes.forEach { option ->
                        Row(
                            modifier          = Modifier
                                .fillMaxWidth()
                                .clickable { sensorVm.setSensorSharedSubMode(option.mode) }
                                .padding(vertical = 4.dp),
                            verticalAlignment = Alignment.CenterVertically,
                        ) {
                            RadioButton(
                                selected = sensorUiState.sensorSharedSubMode == option.mode,
                                onClick  = { sensorVm.setSensorSharedSubMode(option.mode) },
                                colors   = RadioButtonDefaults.colors(selectedColor = ColorAmber),
                            )
                            Spacer(Modifier.width(8.dp))
                            Column {
                                Text(option.label, style = SettingsBodyStyle, color = ColorTextPrimary)
                                Text(option.description, style = SettingsBodySubStyle, color = ColorTextMuted)
                            }
                        }
                    }

                    if (sensorUiState.sensorSharedSubMode == com.coldboreballisticsllc.scopedope.ui.session.SensorSharedSubMode.TIMED_WINDOW) {
                        Spacer(Modifier.height(4.dp))
                        var windowSecsStr by remember(sensorUiState.sensorSharedWindowSecs) {
                            mutableStateOf(sensorUiState.sensorSharedWindowSecs.toString())
                        }
                        Row(
                            modifier          = Modifier.fillMaxWidth(),
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(8.dp),
                        ) {
                            OutlinedTextField(
                                value         = windowSecsStr,
                                onValueChange = { windowSecsStr = it },
                                label         = { Text("Window duration") },
                                suffix        = { Text("sec") },
                                singleLine    = true,
                                modifier      = Modifier.weight(1f),
                                colors        = OutlinedTextFieldDefaults.colors(
                                    focusedBorderColor   = ColorAmber,
                                    unfocusedBorderColor = ColorBorder,
                                    focusedLabelColor    = ColorAmber,
                                    unfocusedLabelColor  = ColorTextMuted,
                                    focusedTextColor     = ColorTextPrimary,
                                    unfocusedTextColor   = ColorTextPrimary,
                                    cursorColor          = ColorAmber,
                                ),
                            )
                            OutlinedButton(
                                onClick = {
                                    windowSecsStr.toIntOrNull()?.let { sensorVm.setSensorSharedWindowSeconds(it) }
                                },
                                border = BorderStroke(1.dp, ColorAmber),
                                colors = ButtonDefaults.outlinedButtonColors(contentColor = ColorAmber),
                            ) {
                                Text("Set", style = SettingsBodySubStyle)
                            }
                        }
                    }
                }
            }
        }
    }
}
