import SwiftUI

struct ErrorBanner: View {
    let error: BookStackError
    var onRetry: (() -> Void)? = nil

    private var isUnauthorized: Bool {
        if case .unauthorized = error { return true }
        return false
    }

    var body: some View {
        HStack(spacing: 12) {
            Image(systemName: "exclamationmark.triangle.fill")
                .foregroundStyle(.orange)
                .font(.title3)

            Text(error.errorDescription ?? "An unknown error occurred.")
                .font(.callout)
                .foregroundStyle(.primary)
                .fixedSize(horizontal: false, vertical: true)

            Spacer()

            if isUnauthorized {
                Button(L("settings.title")) {
                    AppNavigationState.shared.navigateToSettings = true
                }
                .buttonStyle(.bordered)
                .controlSize(.small)
            } else if let onRetry {
                Button(L("common.retry"), action: onRetry)
                    .buttonStyle(.bordered)
                    .controlSize(.small)
            }
        }
        .padding()
        .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 12))
        .accessibilityElement(children: .combine)
        .accessibilityLabel("Error: \(error.errorDescription ?? "Unknown error")")
    }
}

#Preview {
    VStack(spacing: 16) {
        ErrorBanner(error: .networkUnavailable, onRetry: {})
        ErrorBanner(error: .unauthorized)
        ErrorBanner(error: .timeout, onRetry: {})
    }
    .padding()
}
