import SwiftUI

public extension View {
    // Original method signature for backward compatibility
    func stableRefreshable(_ action: @MainActor @escaping () async -> Void) -> some View {
        stableRefreshable { _ in await action() }
    }

    // Improved method that tells us when the user initiated the refresh
    func stableRefreshable(_ action: @MainActor @escaping (Bool?) async -> Void) -> some View {
        modifier(RefreshableModifier(action: action))
    }
}

private struct RefreshableModifier: ViewModifier {
    @State private var id: UUID?
    @State private var continuation: CheckedContinuation<Void, Never>?
    let action: (Bool?) async -> Void

    func body(content: Content) -> some View {
        content
            .refreshable {
                guard continuation == nil else { return }
                id = UUID()

                // Required so that the refresh indicator disappears when the task completes
                // If removed, this will cause unwanted visual artifacts
                await withCheckedContinuation { continuation in
                    self.continuation = continuation
                }
            }
            .task(id: id) {
                guard id != nil else { return }
                
                defer {
                    continuation?.resume()
                    continuation = nil
                    id = nil
                }
                
                await action(true)
            }
    }
}
