import SwiftUI

/// A view modifier that shows error alerts with retry/cancel options
struct ErrorAlertModifier: ViewModifier {
    let error: ErrorAlertInfo?
    let onRetry: () -> Void
    let onDismiss: () -> Void

    func body(content: Content) -> some View {
        content
            .alert(
                error?.title ?? "Network Error",
                isPresented: Binding(
                    get: { error != nil },
                    set: { if !$0 { onDismiss() } }
                )
            ) {
                Button("Try Again", role: .none) {
                    onRetry()
                }
                Button("Cancel", role: .cancel) {
                    onDismiss()
                }
            } message: {
                if let error = error {
                    Text(error.message)
                }
            }
    }
}

/// Information about an error to display in an alert
struct ErrorAlertInfo: Identifiable {
    let id = UUID()
    let title: String
    let message: String

    init(title: String = "Network Error", message: String) {
        self.title = title
        self.message = message
    }
}

extension View {
    /// Shows an error alert with retry and cancel buttons
    ///
    /// - Parameters:
    ///   - error: The error to display, or nil to hide the alert
    ///   - onRetry: Closure called when user taps "Try Again"
    ///   - onDismiss: Closure called when user taps "Cancel" or dismisses alert
    func errorAlert(
        error: ErrorAlertInfo?,
        onRetry: @escaping () -> Void,
        onDismiss: @escaping () -> Void
    ) -> some View {
        modifier(ErrorAlertModifier(error: error, onRetry: onRetry, onDismiss: onDismiss))
    }
}
