Pith - varnish
package com.vgmlr.varnish

import android.content.Context
import android.graphics.Bitmap
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.ListAlt
import androidx.compose.material.icons.filled.BlurOff
import androidx.compose.material.icons.filled.BlurOn
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.outlined.Block
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.GridView
import androidx.compose.material.icons.outlined.History
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.Share
import androidx.compose.material.icons.outlined.SortByAlpha
import androidx.compose.material.icons.outlined.WarningAmber
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.graphics.scale
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil.compose.AsyncImage
import coil.request.ImageRequest
import coil.size.Size
import coil.transform.Transformation
import java.io.File
import java.util.Locale
import kotlin.math.max
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.withContext

private val THUMB_GAP = 2.dp
private val MARK_ICON = 16.dp
private val MARK_PAD = 6.dp
private val PLAY_ICON = 38.dp
private val TIME_STYLE = TextStyle(
    color = Color.White,
    fontSize = 12.sp,
    fontFamily = FontFamily.Monospace,
    shadow = Shadow(Color.Black.copy(alpha = 0.7f), blurRadius = 4f)
)
private const val STAMP_EASE_MS = 120L
private val LIST_PAD = 2.dp
private val LIST_GAP = 12.dp
private const val LIST_FADE = 0.4f
private val STAR_EDGE = 1.dp
private val STAR_INK = Color.Black.copy(alpha = 0.5f)
private val STAR = floatArrayOf( // 24u viewport
    12f, 17.27f, 18.18f, 21f, 16.54f, 13.97f, 22f, 9.24f, 14.81f, 8.63f,
    12f, 2f, 9.19f, 8.63f, 2f, 9.24f, 7.46f, 13.97f, 5.82f, 21f
)

@Composable
fun FolderScreen(vm: VarnishViewModel, screen: Screen.Folder) {
    val files by vm.folderFiles.collectAsStateWithLifecycle()
    val settings by vm.settings.collectAsStateWithLifecycle()
    val lists by vm.listFolders.collectAsStateWithLifecycle()
    var menu by remember { mutableStateOf(false) }
    val fav = screen.path == VarnishConfig.FAV_PATH
    val locked = remember(screen.path) { fav || vm.repo.isLocked(File(screen.path)) }
    val title = if (fav) VarnishConfig.FAV_NAME else File(screen.path).name
    var local by rememberSaveable(screen.path) { mutableStateOf(false) }
    val list = if (settings.saveView) screen.path in lists else local
    var flash by remember { mutableStateOf<String?>(null) }
    var flashN by remember { mutableIntStateOf(0) }

    fun notify(m: SortMode) {
        flash = m.label
        flashN++
    }

    LaunchedEffect(flashN) {
        if (flash == null) return@LaunchedEffect
        delay(VarnishConfig.TITLE_MS)
        flash = null
    }

    BackHandler(enabled = menu) { menu = false }

    Box(Modifier.fillMaxSize().background(PageBg)) {
        MediaBrowser(vm, files, screen.path, onTouch = { menu = false }, list = list)

        TopBar(
            onBack = { vm.back() },
            trailing = {
                MenuStack(
                    open = menu,
                    onOpenChange = { menu = it },
                    items = listOf(
                        MenuItem(
                            if (list) Icons.Outlined.GridView else Icons.AutoMirrored.Outlined.ListAlt,
                            if (list) "Grid" else "List",
                            keepOpen = true
                        ) {
                            if (settings.saveView) {
                                vm.setListView(screen.path, !list)
                            } else {
                                local = !local
                            }
                        },
                        MenuItem(Icons.Outlined.SortByAlpha, "Sort Name", keepOpen = true) {
                            vm.sortAlpha()
                            notify(settings.sort.byAlpha())
                        },
                        MenuItem(Icons.Outlined.History, "Sort Date", keepOpen = true) {
                            vm.sortDate()
                            notify(settings.sort.byDate())
                        },
                        MenuItem(Icons.Outlined.Settings, "Settings") { vm.open(Screen.Settings) },
                        MenuItem(Icons.Outlined.Block, "Exit", enabled = false) {}
                    )
                )
            }
        ) {
            TitlePlate(
                title = flash ?: title,
                modifier = Modifier.weight(1f),
                editable = !locked && flash == null,
                align = if (flash != null) TextAlign.End else TextAlign.Start,
                onCommit = { vm.renameFolder(screen.path, it) }
            )
        }
    }
}

@Composable
internal fun MediaBrowser(
    vm: VarnishViewModel,
    files: List<MediaFile>,
    folder: String?,
    onTouch: () -> Unit,
    modifier: Modifier = Modifier,
    list: Boolean = false
) {
    val context = LocalContext.current
    val settings by vm.settings.collectAsStateWithLifecycle()
    val blurSet by vm.fileBlur.collectAsStateWithLifecycle()
    val favSet by vm.favorites.collectAsStateWithLifecycle()
    val touch by rememberUpdatedState(onTouch)
    val state = rememberLazyGridState()
    val cols = if (list) 1 else settings.gridCols

    SideEffect {
        val top = vm.topFor
        if (folder != null && top != null && top == files) {
            vm.topFor = null
            state.requestScrollToItem(0)
        }
    }

    var selected by remember { mutableStateOf(emptySet<String>()) }
    var armDel by rememberArmed()

    LaunchedEffect(selected) { armDel = false }

    LaunchedEffect(files) {
        val live = files.mapTo(HashSet()) { it.path }
        if (selected.any { it !in live }) selected = selected.filterTo(HashSet()) { it in live }
    }

    BackHandler(enabled = selected.isNotEmpty()) { selected = emptySet() }

    // footer stamp
    val pastFirst by remember {
        derivedStateOf {
            val n = state.layoutInfo.visibleItemsInfo.size
            n > 0 && state.firstVisibleItemIndex >= n
        }
    }
    val bottomIdx by remember(cols) {
        derivedStateOf {
            val last = state.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
            if (last < 0) -1 else (last / cols) * cols
        }
    }
    var shownIdx by remember { mutableIntStateOf(-1) }
    var bubble by remember { mutableStateOf(false) }

    LaunchedEffect(state, cols) {
        snapshotFlow { bottomIdx }.conflate().collect {
            shownIdx = it
            delay(STAMP_EASE_MS)
        }
    }

    LaunchedEffect(state) {
        snapshotFlow { state.isScrollInProgress to pastFirst }.collectLatest { (scrolling, past) ->
            when {
                scrolling && past -> bubble = true
                scrolling -> bubble = false
                else -> {
                    delay(VarnishConfig.FOOTER_MS)
                    bubble = false
                }
            }
        }
    }

    val top = WindowInsets.statusBars.asPaddingValues().calculateTopPadding() + TOP_BAR_H
    val bottom = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding() +
        BTN + DOCK_PAD * 2

    BoxWithConstraints(modifier.fillMaxSize()) {
        val cell = with(LocalDensity.current) {
            val gap = THUMB_GAP.roundToPx()
            ((constraints.maxWidth - gap * (cols - 1)) / cols).toDp()
        }
        LazyVerticalGrid(
            columns = GridCells.Fixed(cols),
            state = state,
            modifier = Modifier
                .fillMaxSize()
                .pointerInput(Unit) {
                    awaitEachGesture {
                        awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
                        touch()
                    }
                }
                .clickable(
                    interactionSource = remember { MutableInteractionSource() },
                    indication = null,
                    enabled = selected.isNotEmpty()
                ) { selected = emptySet() },
            contentPadding = PaddingValues(top = top, bottom = bottom),
            horizontalArrangement = Arrangement.spacedBy(THUMB_GAP),
            verticalArrangement = Arrangement.spacedBy(if (list) 0.dp else THUMB_GAP)
        ) {
            items(files, key = { it.path }) { f ->
                val open: () -> Unit = {
                    when {
                        selected.isNotEmpty() -> selected = selected.toggle(f.path)
                        f.video -> context.startOr(
                            vm.repo.playIntent(f.path, settings.playerPkg)
                        ) { vm.open(Screen.Settings) }
                        else -> vm.open(Screen.Image(f.path, folder))
                    }
                }
                val mark: () -> Unit = { selected = selected.toggle(f.path) }
                if (list) {
                    ListRow(
                        file = f,
                        img = settings.folderImg.dp,
                        blurred = f.path in blurSet,
                        selected = f.path in selected,
                        onClick = open,
                        onLongClick = mark
                    )
                } else {
                    Thumb(
                        file = f,
                        cell = cell,
                        blurred = f.path in blurSet,
                        favorite = f.path in favSet,
                        selected = f.path in selected,
                        onClick = open,
                        onLongClick = mark
                    )
                }
            }
        }

        if (selected.isNotEmpty()) {
            val allBlur = selected.all { it in blurSet }
            Dock {
                VButton(
                    if (allBlur) Icons.Filled.BlurOff else Icons.Filled.BlurOn,
                    if (allBlur) "Unblur" else "Blur"
                ) { vm.setFileBlur(selected, !allBlur) }
                VButton(Icons.Outlined.Share, "Share") {
                    context.startOr(vm.repo.shareIntent(selected.toList())) {}
                }
                VButton(
                    if (armDel) Icons.Outlined.WarningAmber else Icons.Outlined.Delete,
                    "Delete",
                    iconSize = DEL_ICON,
                    bg = if (armDel) WarnBg else BtnBg
                ) {
                    if (settings.confirmDelete && !armDel) {
                        armDel = true
                    } else {
                        vm.deleteFiles(selected.toList())
                        selected = emptySet()
                    }
                }
            }
        } else if (bubble) {
            files.getOrNull(shownIdx)?.let { f ->
                Dock { FooterBubble(VarnishClock.stamp(f.modified)) }
            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun Thumb(
    file: MediaFile,
    cell: Dp,
    blurred: Boolean,
    favorite: Boolean,
    selected: Boolean,
    onClick: () -> Unit,
    onLongClick: () -> Unit
) {
    val context = LocalContext.current
    val haptic = LocalHapticFeedback.current
    val request = remember(file.path, file.modified, blurred) {
        thumbRequest(context, file, blurred)
    }
    val runtime by produceState<String?>(null, file.path, file.modified) {
        if (!file.video) return@produceState
        value = withContext(Dispatchers.IO) {
            VarnishCodec.runtime(file.path, file.modified)
        }?.let(::runtimeLabel)
    }

    Box(
        Modifier
            .fillMaxWidth()
            .height(cell)
            .background(FieldBg)
            .combinedClickable(
                onClick = onClick,
                onLongClick = {
                    haptic.performHapticFeedback(HapticFeedbackType.LongPress)
                    onLongClick()
                }
            )
    ) {
        AsyncImage(
            model = request,
            contentDescription = null,
            contentScale = ContentScale.Crop,
            modifier = Modifier.fillMaxSize()
        )
        if (file.video) {
            Icon(
                Icons.Filled.PlayArrow,
                contentDescription = null,
                tint = Color.White.copy(alpha = 0.9f),
                modifier = Modifier
                    .align(Alignment.Center)
                    .size(PLAY_ICON)
            )
        }
        runtime?.let {
            Text(
                it,
                style = TIME_STYLE,
                modifier = Modifier
                    .align(Alignment.BottomEnd)
                    .padding(MARK_PAD)
            )
        }
        if (favorite) {
            Spacer(
                Modifier
                    .align(Alignment.BottomEnd)
                    .padding(MARK_PAD)
                    .size(MARK_ICON)
                    .drawWithCache {
                        val k = size.width / 24f
                        val star = Path().apply {
                            moveTo(STAR[0] * k, STAR[1] * k)
                            for (i in 2 until STAR.size step 2) lineTo(STAR[i] * k, STAR[i + 1] * k)
                            close()
                        }
                        val edge = Stroke(STAR_EDGE.toPx() * 2, join = StrokeJoin.Round)
                        onDrawBehind {
                            drawPath(star, STAR_INK, style = edge)
                            drawPath(star, Color.White)
                        }
                    }
            )
        }
        if (selected) {
            Box(
                Modifier
                    .matchParentSize()
                    .border(3.dp, SelectBorder)
            )
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun ListRow(
    file: MediaFile,
    img: Dp,
    blurred: Boolean,
    selected: Boolean,
    onClick: () -> Unit,
    onLongClick: () -> Unit
) {
    val context = LocalContext.current
    val haptic = LocalHapticFeedback.current
    val request = remember(file.path, file.modified, blurred) {
        thumbRequest(context, file, blurred)
    }
    val runtime by produceState<String?>(null, file.path, file.modified) {
        if (!file.video) return@produceState
        value = withContext(Dispatchers.IO) {
            VarnishCodec.runtime(file.path, file.modified)
        }?.let(::runtimeLabel)
    }

    Row(
        Modifier
            .fillMaxWidth()
            .combinedClickable(
                onClick = onClick,
                onLongClick = {
                    haptic.performHapticFeedback(HapticFeedbackType.LongPress)
                    onLongClick()
                }
            )
            .padding(horizontal = EDGE, vertical = LIST_PAD),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Box(
            Modifier
                .size(img)
                .clip(RoundedCornerShape(BTN_RADIUS))
                .background(FieldBg)
                .then(
                    if (selected) Modifier.border(3.dp, SelectBorder, RoundedCornerShape(BTN_RADIUS))
                    else Modifier
                ),
            contentAlignment = Alignment.Center
        ) {
            AsyncImage(
                model = request,
                contentDescription = null,
                contentScale = ContentScale.Crop,
                modifier = Modifier.fillMaxSize()
            )
            if (file.video) {
                Icon(
                    Icons.Filled.PlayArrow,
                    contentDescription = null,
                    tint = Color.White.copy(alpha = 0.9f),
                    modifier = Modifier.size(img * 0.4f)
                )
            }
            runtime?.let {
                Text(
                    it,
                    style = TIME_STYLE,
                    modifier = Modifier
                        .align(Alignment.BottomEnd)
                        .padding(MARK_PAD)
                )
            }
        }
        Spacer(Modifier.width(LIST_GAP))
        Column(Modifier.weight(1f)) {
            Text(
                file.name,
                color = PageText,
                fontSize = 16.sp,
                lineHeight = 20.sp,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                sizeLabel(file.size),
                color = PageText.copy(alpha = LIST_FADE),
                fontSize = 12.sp,
                lineHeight = 18.sp,
                maxLines = 1
            )
        }
    }
}

internal fun thumbRequest(context: Context, f: MediaFile, blurred: Boolean): ImageRequest =
    ImageRequest.Builder(context)
        .data(if (f.video) VideoThumb(f.path, f.modified) else File(f.path))
        .setParameter("m", f.modified)
        .apply { if (blurred) transformations(SoftBlur) }
        .build()

internal object SoftBlur : Transformation {
    override val cacheKey = "varnish.blur"

    override suspend fun transform(input: Bitmap, size: Size): Bitmap {
        val w = input.width
        val h = input.height
        val a = input.scale(max(1, w / 8), max(1, h / 8))
        val b = a.scale(max(1, w / 32), max(1, h / 32))
        val c = b.scale(max(1, w / 8), max(1, h / 8))
        val out = c.scale(w, h)
        listOf(a, b, c).forEach { if (it !== input && it !== out) it.recycle() }
        return out
    }
}

private fun runtimeLabel(ms: Long): String {
    val t = ms / 1000
    val h = t / 3600
    val m = t % 3600 / 60
    val s = t % 60
    return if (h > 0) String.format(Locale.ROOT, "%d:%02d:%02d", h, m, s)
    else String.format(Locale.ROOT, "%d:%02d", m, s)
}

private fun Set<String>.toggle(p: String): Set<String> = if (p in this) this - p else this + p