package com.ponzischeme89.memby.ui

internal enum class RowFocusDirection {
    UP,
    DOWN,
}

internal data class RowFocusRequest(
    val rowId: String,
    val itemIndex: Int,
    val requestId: Int,
)

/**
 * Finds the next row that can actually receive card focus. Loading and empty rows are
 * deliberately skipped so one D-pad press always produces visible movement.
 */
internal fun adjacentFocusableRowIndex(
    itemCounts: List<Int>,
    currentIndex: Int,
    direction: RowFocusDirection,
): Int? {
    if (currentIndex !in itemCounts.indices) return null
    val step = if (direction == RowFocusDirection.DOWN) 1 else -1
    var candidate = currentIndex + step
    while (candidate in itemCounts.indices) {
        if (itemCounts[candidate] > 0) return candidate
        candidate += step
    }
    return null
}

/**
 * Returning to a row restores the card last used there. On a first visit, preserve the
 * viewer's horizontal position as far as the shorter destination row permits.
 */
internal fun rowEntryItemIndex(
    sourceIndex: Int,
    destinationItemCount: Int,
    rememberedDestinationIndex: Int?,
): Int {
    if (destinationItemCount <= 0) return 0
    return (rememberedDestinationIndex ?: sourceIndex).coerceIn(0, destinationItemCount - 1)
}
