import SwiftUI

struct ErrorAlertModifier: ViewModifier {
    @Binding var errorMessage: String?
    @Binding var isPresented: Bool
    var title: String = "Error"

    func body(content: Content) -> some View {
        content
            .onChange(of: isPresented) {
                if isPresented, isCancellationMessage(errorMessage) {
                    isPresented = false
                    errorMessage = nil
                }
            }
            .alert(title, isPresented: $isPresented) {
                Button("OK", role: .cancel) {}
            } message: {
                Text(errorMessage ?? "An unknown error occurred")
            }
    }

    private func isCancellationMessage(_ message: String?) -> Bool {
        guard let message = message?.lowercased() else { return false }
        return message.contains("cancelled")
            || message.contains("canceled")
            || message.contains("nsurlerrordomain error -999")
    }
}

extension View {
    func errorAlert(_ title: String = "Error", message: Binding<String?>, isPresented: Binding<Bool>) -> some View {
        modifier(ErrorAlertModifier(errorMessage: message, isPresented: isPresented, title: title))
    }
}
