package com.placeholder.sherpai2.util

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * Debouncer - Delays execution until a pause in rapid calls
 *
 * Used by RollingScanViewModel to avoid re-scanning on every selection change
 *
 * EXAMPLE:
 * User selects photos rapidly:
 * - Select photo 1 → Debouncer starts 300ms timer
 * - Select photo 2 (100ms later) → Timer resets to 300ms
 * - Select photo 3 (100ms later) → Timer resets to 300ms
 * - Wait 300ms → Scan executes ONCE
 *
 * RESULT: 3 selections = 1 scan (instead of 3 scans!)
 */
class Debouncer(
    private val delayMs: Long = 300L,
    private val scope: CoroutineScope = CoroutineScope(Dispatchers.Main)
) {

    private var debounceJob: Job? = null

    /**
     * Debounce an action
     *
     * Cancels any pending action and schedules a new one
     *
     * @param action Suspend function to execute after delay
     */
    fun debounce(action: suspend () -> Unit) {
        // Cancel previous job
        debounceJob?.cancel()

        // Schedule new job
        debounceJob = scope.launch {
            delay(delayMs)
            action()
        }
    }

    /**
     * Cancel any pending debounced action
     */
    fun cancel() {
        debounceJob?.cancel()
        debounceJob = null
    }

    /**
     * Check if debouncer has a pending action
     */
    val isPending: Boolean
        get() = debounceJob?.isActive == true
}