package com.hermes.app.core.gestures

import androidx.compose.foundation.gestures.detectVerticalDragGestures
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput

internal class HermesSwipeDownDetector(
    private val threshold: Float = 32f,
) {
    private var totalDrag = 0f
    private var triggered = false

    fun onDrag(dragAmount: Float): Boolean {
        if (triggered) {
            return false
        }

        totalDrag = (totalDrag + dragAmount).coerceAtLeast(0f)
        if (totalDrag >= threshold) {
            triggered = true
            return true
        }

        return false
    }

    fun reset() {
        totalDrag = 0f
        triggered = false
    }
}

fun Modifier.hermesSwipeDown(onSwipeDown: () -> Unit): Modifier = pointerInput(onSwipeDown) {
    val detector = HermesSwipeDownDetector()
    detectVerticalDragGestures(
        onDragStart = { detector.reset() },
        onDragEnd = { detector.reset() },
        onDragCancel = { detector.reset() },
    ) { _, dragAmount ->
        if (detector.onDrag(dragAmount)) {
            onSwipeDown()
        }
    }
}
