package cy.hexor.furumi.ui.player

import android.content.Intent
import android.graphics.Bitmap
import androidx.activity.compose.BackHandler
import androidx.compose.animation.core.Animatable
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import cy.hexor.furumi.domain.model.ArtistCard
import cy.hexor.furumi.domain.model.ConnectedDevice
import cy.hexor.furumi.domain.model.PlaylistCard
import cy.hexor.furumi.domain.model.ReleaseCard
import cy.hexor.furumi.domain.model.TrackCard
import cy.hexor.furumi.domain.model.ListeningHistoryItem
import cy.hexor.furumi.playback.AudioPlaybackState
import cy.hexor.furumi.ui.theme.FurumiBlack
import cy.hexor.furumi.ui.theme.FurumiElectricCyan
import cy.hexor.furumi.ui.theme.FurumiHotOrange
import cy.hexor.furumi.ui.theme.FurumiLine
import cy.hexor.furumi.ui.theme.FurumiNeonPink
import cy.hexor.furumi.ui.theme.FurumiNeonViolet
import cy.hexor.furumi.ui.theme.FurumiSurface
import cy.hexor.furumi.ui.theme.FurumiSurfaceHigh
import cy.hexor.furumi.ui.theme.FurumiTextMuted
import java.text.DateFormat
import java.util.Date
import java.util.Locale
import kotlin.math.roundToInt

@Composable
internal fun PlayerHeader(
    title: String,
    subtitle: String,
    onProfileClick: () -> Unit
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Column {
            Text(
                text = title,
                style = MaterialTheme.typography.headlineMedium,
                color = MaterialTheme.colorScheme.onBackground
            )
            Text(
                text = subtitle,
                style = MaterialTheme.typography.bodyMedium,
                color = FurumiTextMuted
            )
        }

        Row(
            modifier = Modifier
                .height(38.dp)
                .clip(CircleShape)
                .background(FurumiSurfaceHigh)
                .border(1.dp, FurumiLine, CircleShape)
                .clickable(onClick = onProfileClick)
                .padding(start = 5.dp, end = 12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Box(
                modifier = Modifier
                    .size(28.dp)
                    .clip(CircleShape)
                    .background(FurumiNeonPink),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "F",
                    style = MaterialTheme.typography.labelSmall,
                    color = FurumiBlack,
                    fontWeight = FontWeight.ExtraBold
                )
            }
            Spacer(modifier = Modifier.width(8.dp))
            Text(
                text = "Profile",
                style = MaterialTheme.typography.labelSmall,
                color = MaterialTheme.colorScheme.onBackground
            )
        }
    }
}

@Composable
internal fun ProfileMenu(
    uiState: PlayerUiState,
    onHistoryClick: () -> Unit,
    onDeviceClick: (String) -> Unit,
    onOfflineModeChange: (Boolean) -> Unit,
    onSaveListenedChange: (Boolean) -> Unit,
    onStorageLimitChange: (Long) -> Unit,
    onSyncOffline: () -> Unit,
    onClearOfflineCache: () -> Unit,
    onLogout: () -> Unit,
    modifier: Modifier = Modifier
) {
    Surface(
        modifier = modifier
            .fillMaxWidth()
            .widthIn(max = 430.dp)
            .heightIn(max = 640.dp),
        shape = RoundedCornerShape(12.dp),
        color = FurumiSurfaceHigh,
        border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine),
        shadowElevation = 8.dp
    ) {
        Column(
            modifier = Modifier
                .verticalScroll(rememberScrollState())
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(14.dp)
        ) {
            ProfileSummary(uiState)
            ConnectedDevicesSection(
                uiState = uiState,
                onDeviceClick = onDeviceClick
            )
            OfflineControlsSection(
                uiState = uiState,
                onOfflineModeChange = onOfflineModeChange,
                onSaveListenedChange = onSaveListenedChange,
                onStorageLimitChange = onStorageLimitChange,
                onSyncOffline = onSyncOffline,
                onClearOfflineCache = onClearOfflineCache
            )
            OutlinedButton(
                onClick = onHistoryClick,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(46.dp),
                shape = CircleShape,
                border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine),
                colors = ButtonDefaults.outlinedButtonColors(
                    contentColor = MaterialTheme.colorScheme.onBackground,
                    disabledContentColor = FurumiTextMuted
                )
            ) {
                Text("Listening history")
            }
            Button(
                onClick = onLogout,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(48.dp),
                enabled = !uiState.isLoggingOut,
                shape = CircleShape,
                colors = ButtonDefaults.buttonColors(
                    containerColor = FurumiNeonPink,
                    contentColor = FurumiBlack,
                    disabledContainerColor = FurumiSurface,
                    disabledContentColor = FurumiTextMuted
                )
            ) {
                if (uiState.isLoggingOut) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(20.dp),
                        color = FurumiBlack,
                        strokeWidth = 2.dp
                    )
                } else {
                    Text("Log out")
                }
            }
        }
    }
}

@Composable
private fun ProfileSummary(uiState: PlayerUiState) {
    Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
        Text(
            text = "Profile",
            style = MaterialTheme.typography.titleMedium,
            color = MaterialTheme.colorScheme.onBackground
        )
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            Box(
                modifier = Modifier
                    .size(34.dp)
                    .clip(CircleShape)
                    .background(FurumiNeonPink),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = uiState.userName.firstOrNull()?.uppercaseChar()?.toString() ?: "F",
                    style = MaterialTheme.typography.labelLarge,
                    color = FurumiBlack,
                    fontWeight = FontWeight.ExtraBold
                )
            }
            Text(
                text = uiState.userName,
                style = MaterialTheme.typography.labelLarge,
                color = MaterialTheme.colorScheme.onBackground,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier.weight(1f)
            )
            if (uiState.appVersion.isNotBlank()) {
                Surface(
                    color = FurumiSurface,
                    shape = RoundedCornerShape(4.dp),
                    border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine)
                ) {
                    Text(
                        text = "v${uiState.appVersion}",
                        modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
                        style = MaterialTheme.typography.labelSmall,
                        color = FurumiTextMuted
                    )
                }
            }
        }
        Text(
            text = uiState.serverUrl.ifBlank { "No server selected" },
            style = MaterialTheme.typography.bodyMedium,
            color = FurumiTextMuted,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }
}

@Composable
private fun OfflineControlsSection(
    uiState: PlayerUiState,
    onOfflineModeChange: (Boolean) -> Unit,
    onSaveListenedChange: (Boolean) -> Unit,
    onStorageLimitChange: (Long) -> Unit,
    onSyncOffline: () -> Unit,
    onClearOfflineCache: () -> Unit
) {
    val offlineState = uiState.offlineState
    val settings = offlineState.settings
    val storageProgress = if (settings.storageLimitBytes > 0L) {
        (offlineState.storageUsedBytes.toFloat() / settings.storageLimitBytes.toFloat()).coerceIn(0f, 1f)
    } else {
        0f
    }

    Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
        Text(
            text = "Offline",
            style = MaterialTheme.typography.labelMedium,
            color = MaterialTheme.colorScheme.onBackground
        )
        ProfileSwitchRow(
            title = "Offline mode",
            subtitle = if (offlineState.isUsingNetworkFallback) "Fallback active" else "Local library",
            checked = settings.offlineModeEnabled,
            onCheckedChange = onOfflineModeChange
        )
        ProfileSwitchRow(
            title = "Save listened tracks",
            subtitle = "${offlineState.cachedTrackCount} cached",
            checked = settings.saveListenedTracksEnabled,
            onCheckedChange = onSaveListenedChange
        )
        Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Text(
                    text = "Storage",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onBackground,
                    modifier = Modifier.weight(1f)
                )
                Text(
                    text = "${formatStorageBytes(offlineState.storageUsedBytes)} / ${formatStorageBytes(settings.storageLimitBytes)}",
                    style = MaterialTheme.typography.labelSmall,
                    color = FurumiTextMuted
                )
            }
            LinearProgressIndicator(
                progress = { storageProgress },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(4.dp)
                    .clip(CircleShape),
                color = FurumiNeonPink,
                trackColor = FurumiLine
            )
            Row(
                modifier = Modifier.horizontalScroll(rememberScrollState()),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                offlineStorageLimitOptions.forEach { limit ->
                    OfflineLimitChip(
                        label = formatStorageBytes(limit),
                        selected = settings.storageLimitBytes == limit,
                        onClick = { onStorageLimitChange(limit) }
                    )
                }
            }
        }
        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
            OutlinedButton(
                onClick = onSyncOffline,
                modifier = Modifier.weight(1f),
                enabled = !offlineState.isSyncing,
                shape = CircleShape,
                border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine),
                colors = ButtonDefaults.outlinedButtonColors(
                    contentColor = MaterialTheme.colorScheme.onBackground,
                    disabledContentColor = FurumiTextMuted
                )
            ) {
                if (offlineState.isSyncing) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(18.dp),
                        color = FurumiTextMuted,
                        strokeWidth = 2.dp
                    )
                } else {
                    Text("Sync now")
                }
            }
            OutlinedButton(
                onClick = onClearOfflineCache,
                modifier = Modifier.weight(1f),
                enabled = offlineState.storageUsedBytes > 0L && !offlineState.isSyncing,
                shape = CircleShape,
                border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine),
                colors = ButtonDefaults.outlinedButtonColors(
                    contentColor = MaterialTheme.colorScheme.onBackground,
                    disabledContentColor = FurumiTextMuted
                )
            ) {
                Text("Clear downloads")
            }
        }
        Text(
            text = formatOfflineSyncStatus(offlineState.lastSyncedAtMs),
            style = MaterialTheme.typography.bodySmall,
            color = FurumiTextMuted,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
        offlineState.lastError?.let { error ->
            Text(
                text = error,
                style = MaterialTheme.typography.bodySmall,
                color = FurumiHotOrange,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}

@Composable
private fun ProfileSwitchRow(
    title: String,
    subtitle: String,
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = title,
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onBackground
            )
            Text(
                text = subtitle,
                style = MaterialTheme.typography.bodySmall,
                color = FurumiTextMuted,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
        Switch(
            checked = checked,
            onCheckedChange = onCheckedChange,
            colors = SwitchDefaults.colors(
                checkedThumbColor = FurumiBlack,
                checkedTrackColor = FurumiNeonPink,
                uncheckedThumbColor = FurumiTextMuted,
                uncheckedTrackColor = FurumiSurface,
                uncheckedBorderColor = FurumiLine
            )
        )
    }
}

@Composable
private fun OfflineLimitChip(
    label: String,
    selected: Boolean,
    onClick: () -> Unit
) {
    Surface(
        modifier = Modifier
            .height(32.dp)
            .clip(CircleShape)
            .clickable(onClick = onClick),
        shape = CircleShape,
        color = if (selected) FurumiNeonPink else FurumiSurface,
        border = if (selected) null else androidx.compose.foundation.BorderStroke(1.dp, FurumiLine)
    ) {
        Box(
            modifier = Modifier.padding(horizontal = 12.dp),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = label,
                style = MaterialTheme.typography.labelSmall,
                color = if (selected) FurumiBlack else MaterialTheme.colorScheme.onBackground
            )
        }
    }
}

@Composable
internal fun OfflineStatusBadge(
    offlineState: cy.hexor.furumi.domain.model.OfflineState,
    modifier: Modifier = Modifier
) {
    Surface(
        modifier = modifier,
        shape = CircleShape,
        color = if (offlineState.settings.offlineModeEnabled) FurumiNeonPink else FurumiHotOrange,
        shadowElevation = 4.dp
    ) {
        Text(
            text = if (offlineState.settings.offlineModeEnabled) "Offline mode" else "Offline fallback",
            modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
            style = MaterialTheme.typography.labelSmall,
            color = FurumiBlack,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }
}

@Composable
private fun ConnectedDevicesSection(
    uiState: PlayerUiState,
    onDeviceClick: (String) -> Unit
) {
    val devices = uiState.connectedDevicesState?.devices.orEmpty()

    Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
        Text(
            text = "Devices",
            style = MaterialTheme.typography.labelMedium,
            color = MaterialTheme.colorScheme.onBackground
        )
        val statusText = when {
            uiState.offlineState.settings.offlineModeEnabled -> "Offline mode"
            uiState.connectedDevicesError != null -> uiState.connectedDevicesError
            devices.isEmpty() -> "No connected devices"
            else -> null
        }
        statusText?.let { status ->
            Text(
                text = status,
                style = MaterialTheme.typography.bodySmall,
                color = if (uiState.connectedDevicesError != null) FurumiHotOrange else FurumiTextMuted,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
        devices.forEach { device ->
            ConnectedDeviceRow(
                device = device,
                onClick = { onDeviceClick(device.id) }
            )
        }
    }
}

@Composable
private fun ConnectedDeviceRow(
    device: ConnectedDevice,
    onClick: () -> Unit
) {
    Surface(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(6.dp))
            .clickable(onClick = onClick),
        shape = RoundedCornerShape(6.dp),
        color = if (device.isActive) FurumiSurface else Color.Transparent,
        border = if (device.isActive) androidx.compose.foundation.BorderStroke(1.dp, FurumiNeonPink) else null
    ) {
        Row(
            modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Box(
                modifier = Modifier
                    .size(8.dp)
                    .clip(CircleShape)
                    .background(if (device.isActive) FurumiNeonPink else FurumiLine)
            )
            Spacer(modifier = Modifier.width(10.dp))
            Text(
                text = device.name,
                style = MaterialTheme.typography.bodyMedium,
                color = if (device.isActive) MaterialTheme.colorScheme.onBackground else FurumiTextMuted,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier.weight(1f)
            )
            if (device.isCurrent) {
                Text(
                    text = "this",
                    style = MaterialTheme.typography.labelSmall,
                    color = FurumiTextMuted.copy(alpha = 0.7f)
                )
            }
        }
    }
}

@Composable
internal fun SectionTitle(title: String) {
    Text(
        text = title,
        style = MaterialTheme.typography.titleMedium,
        color = MaterialTheme.colorScheme.onBackground
    )
}

@Composable
internal fun FilterChips(filters: List<String>) {
    Row(
        modifier = Modifier.horizontalScroll(rememberScrollState()),
        horizontalArrangement = Arrangement.spacedBy(10.dp)
    ) {
        filters.forEachIndexed { index, filter ->
            Surface(
                shape = CircleShape,
                color = if (index == 0) FurumiNeonPink else FurumiSurface,
                border = if (index == 0) null else androidx.compose.foundation.BorderStroke(1.dp, FurumiLine)
            ) {
                Text(
                    text = filter,
                    modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp),
                    style = MaterialTheme.typography.labelSmall,
                    color = if (index == 0) FurumiBlack else MaterialTheme.colorScheme.onBackground
                )
            }
        }
    }
}

@Composable
internal fun PillAction(
    label: String,
    selected: Boolean,
    modifier: Modifier = Modifier,
    onClick: () -> Unit
) {
    Surface(
        modifier = modifier
            .height(48.dp)
            .clip(CircleShape)
            .clickable(onClick = onClick),
        shape = CircleShape,
        color = if (selected) FurumiNeonPink else FurumiSurface,
        border = if (selected) null else androidx.compose.foundation.BorderStroke(1.dp, FurumiLine)
    ) {
        Box(contentAlignment = Alignment.Center) {
            Text(
                text = label,
                style = MaterialTheme.typography.labelLarge,
                color = if (selected) FurumiBlack else MaterialTheme.colorScheme.onBackground
            )
        }
    }
}

@Composable
internal fun NowPlayingBar(
    playback: AudioPlaybackState,
    coverBitmap: Bitmap?,
    isLiked: Boolean,
    onMediaImageNeeded: (String?) -> Unit,
    onClick: () -> Unit,
    onPlayPause: () -> Unit,
    onPrevious: () -> Unit,
    onNext: () -> Unit,
    onToggleShuffle: () -> Unit,
    onCycleRepeatMode: () -> Unit,
    onToggleLike: () -> Unit
) {
    val track = playback.currentTrack ?: return

    LaunchedEffect(track.coverUrl) {
        onMediaImageNeeded(track.coverUrl)
    }

    Surface(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 10.dp, vertical = 6.dp)
            .clip(RoundedCornerShape(8.dp))
            .clickable(onClick = onClick),
        shape = RoundedCornerShape(8.dp),
        color = FurumiSurfaceHigh,
        border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine)
    ) {
        Column {
            Row(
                modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                MediaArtwork(
                    title = track.title,
                    seedId = track.id,
                    bitmap = coverBitmap,
                    modifier = Modifier.size(42.dp),
                    cornerRadius = 6
                )
                Spacer(modifier = Modifier.width(10.dp))
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = track.title,
                        style = MaterialTheme.typography.labelLarge,
                        color = MaterialTheme.colorScheme.onBackground,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                    Text(
                        text = playback.errorMessage ?: trackSubtitle(track),
                        style = MaterialTheme.typography.bodyMedium,
                        color = if (playback.errorMessage == null) FurumiTextMuted else FurumiHotOrange,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }
                Spacer(modifier = Modifier.width(6.dp))
                MiniPlayerIconButton(size = 30, onClick = onToggleShuffle) {
                    ShuffleGlyph(
                        modifier = Modifier.size(16.dp),
                        color = if (playback.shuffle) FurumiNeonPink else MaterialTheme.colorScheme.onBackground
                    )
                }
                MiniPlayerIconButton(onClick = onPrevious) {
                    PreviousGlyph(Modifier.size(16.dp), MaterialTheme.colorScheme.onBackground)
                }
                MiniPlayerIconButton(
                    size = 38,
                    background = FurumiNeonPink,
                    onClick = onPlayPause
                ) {
                    PlaybackGlyph(
                        playback = playback,
                        playSize = 16,
                        pauseSize = 16
                    )
                }
                MiniPlayerIconButton(onClick = onNext) {
                    NextGlyph(Modifier.size(16.dp), MaterialTheme.colorScheme.onBackground)
                }
                MiniPlayerIconButton(size = 30, onClick = onCycleRepeatMode) {
                    RepeatGlyph(
                        modifier = Modifier.size(18.dp),
                        color = if (playback.repeatMode.equals("off", ignoreCase = true)) {
                            MaterialTheme.colorScheme.onBackground
                        } else {
                            FurumiNeonPink
                        },
                        repeatMode = playback.repeatMode
                    )
                }
                MiniPlayerIconButton(onClick = onToggleLike) {
                    HeartGlyph(
                        isLiked = isLiked,
                        modifier = Modifier.size(18.dp)
                    )
                }
            }
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(3.dp)
                    .background(FurumiLine)
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth(playback.progress)
                        .fillMaxHeight()
                        .background(FurumiNeonPink)
                )
            }
        }
    }
}

@Composable
private fun MiniPlayerIconButton(
    size: Int = 34,
    background: Color = Color.Transparent,
    onClick: () -> Unit,
    content: @Composable BoxScope.() -> Unit
) {
    Box(
        modifier = Modifier
            .size(size.dp)
            .clip(CircleShape)
            .background(background)
            .clickable(onClick = onClick),
        contentAlignment = Alignment.Center,
        content = content
    )
}

@Composable
internal fun BottomPlayerNav(
    selectedTab: PlayerTab,
    onTabSelected: (PlayerTab) -> Unit
) {
    Surface(
        color = FurumiBlack
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(66.dp)
                .padding(horizontal = 14.dp),
            horizontalArrangement = Arrangement.SpaceAround,
            verticalAlignment = Alignment.CenterVertically
        ) {
            PlayerTab.entries.forEach { tab ->
                BottomNavItem(
                    tab = tab,
                    selected = tab == selectedTab,
                    onClick = { onTabSelected(tab) }
                )
            }
        }
    }
}

@Composable
internal fun BottomNavItem(
    tab: PlayerTab,
    selected: Boolean,
    onClick: () -> Unit
) {
    val color = if (selected) FurumiNeonPink else FurumiTextMuted
    Column(
        modifier = Modifier
            .width(86.dp)
            .clip(RoundedCornerShape(8.dp))
            .clickable(onClick = onClick)
            .padding(vertical = 6.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        when (tab) {
            PlayerTab.Global -> GlobalGlyph(Modifier.size(22.dp), color)
            PlayerTab.Search -> SearchGlyph(Modifier.size(22.dp), color)
            PlayerTab.Library -> LibraryGlyph(Modifier.size(22.dp), color)
        }
        Spacer(modifier = Modifier.height(4.dp))
        Text(
            text = tab.label,
            style = MaterialTheme.typography.labelSmall,
            color = color
        )
    }
}

private val offlineStorageLimitOptions = listOf(
    512L * 1024L * 1024L,
    1L * 1024L * 1024L * 1024L,
    2L * 1024L * 1024L * 1024L,
    5L * 1024L * 1024L * 1024L,
    10L * 1024L * 1024L * 1024L
)

private fun formatStorageBytes(bytes: Long): String {
    val safeBytes = bytes.coerceAtLeast(0L)
    val megabytes = safeBytes / (1024.0 * 1024.0)
    return if (megabytes >= 1024.0) {
        String.format(Locale.US, "%.1f GB", megabytes / 1024.0)
    } else {
        String.format(Locale.US, "%.0f MB", megabytes)
    }
}

private fun formatOfflineSyncStatus(timestampMs: Long): String {
    if (timestampMs <= 0L) return "Never synced"
    val formatted = DateFormat
        .getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
        .format(Date(timestampMs))
    return "Synced $formatted"
}
