import SwiftUI

struct DiagnosticReportSheet: View {
    @Environment(\.dismiss) private var dismiss
    let reportText: String
    @State private var didCopy = false

    var body: some View {
        NavigationStack {
            ScrollView {
                if reportText.isEmpty {
                    ContentUnavailableView("No diagnostics available", systemImage: "doc.text.magnifyingglass")
                        .padding(24)
                } else {
                    LazyVStack(alignment: .leading, spacing: 0) {
                        ForEach(Array(Self.textChunks(reportText).enumerated()), id: \.offset) { _, chunk in
                            Text(chunk)
                                .font(.system(.caption, design: .monospaced))
                                .foregroundStyle(.primary)
                                .textSelection(.enabled)
                                .frame(maxWidth: .infinity, alignment: .leading)
                        }
                    }
                    .padding(16)
                }
            }
            .background(Color(.systemGroupedBackground))
            .navigationTitle("Diagnostics")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Done") {
                        dismiss()
                    }
                }
                ToolbarItem(placement: .primaryAction) {
                    Button {
                        copyDiagnostics()
                    } label: {
                        Label(didCopy ? "Copied" : "Copy", systemImage: didCopy ? "checkmark" : "doc.on.doc")
                    }
                    .accessibilityLabel(didCopy ? "Diagnostics copied" : "Copy diagnostics")
                }
            }
        }
        .presentationDetents([.large])
        .presentationDragIndicator(.visible)
    }

    private func copyDiagnostics() {
        UIPasteboard.general.string = reportText
        withAnimation(.snappy) {
            didCopy = true
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
            withAnimation(.snappy) {
                didCopy = false
            }
        }
    }

    private static func textChunks(_ text: String, chunkSize: Int = 4_000) -> [String] {
        guard !text.isEmpty else { return [] }
        var chunks: [String] = []
        chunks.reserveCapacity(max(1, text.count / chunkSize))
        var start = text.startIndex
        while start < text.endIndex {
            let end = text.index(start, offsetBy: chunkSize, limitedBy: text.endIndex) ?? text.endIndex
            chunks.append(String(text[start..<end]))
            start = end
        }
        return chunks
    }
}
