DomainDig/ContentView.swift

715 lines · 30953 bytes

  1import MapKit
  2import SwiftUI
  3import UniformTypeIdentifiers
  4
  5enum LookupInputMode: String, CaseIterable, Identifiable {
  6    case single
  7    case bulk
  8
  9    var id: String { rawValue }
 10}
 11
 12enum ResultSection: String, Hashable {
 13    case domain
 14    case intelligence
 15    case ownership
 16    case dns
 17    case web
 18    case email
 19    case network
 20    case subdomains
 21}
 22
 23private enum LookupInputField: Hashable {
 24    case singleDomain
 25    case bulkDomains
 26}
 27
 28private struct WorkflowNavigationTarget: Hashable {
 29    let workflowID: UUID
 30}
 31
 32struct ContentView: View {
 33    @Environment(\.appDensity) private var appDensity
 34    @Bindable var viewModel: DomainViewModel
 35    @State private var navigationPath = NavigationPath()
 36    @FocusState private var focusedInputField: LookupInputField?
 37    @State private var customPortInput = ""
 38    @State private var customPortsExpanded = false
 39    @State private var trackingNoteDraft = ""
 40    @State private var editingTrackedDomain: TrackedDomain?
 41    @State private var inputMode: LookupInputMode = .single
 42    @State private var collapsedSections: Set<ResultSection> = [.network]
 43    @State private var showingCurrentDomainWorkflowSheet = false
 44    @State private var showingBatchWorkflowSheet = false
 45    @State private var showingTimeline = false
 46    @State private var showingAuditTimeline = false
 47    @State private var auditStartInFlight = false
 48
 49    var body: some View {
 50        NavigationStack(path: $navigationPath) {
 51            List {
 52                Section { inputSection }
 53                if !viewModel.batchResults.isEmpty || viewModel.batchLookupRunning {
 54                    Section { batchSection }
 55                }
 56                if viewModel.hasRun {
 57                    Section { actionButtons }
 58                    if !viewModel.resultsLoaded {
 59                        Section { LookupProgressOverviewView(steps: viewModel.activeLoadingLabels) }
 60                    } else if let statusMessage = resultStatusMessage {
 61                        Section {
 62                            LookupStatusBannerView(message: statusMessage, resultSource: viewModel.currentResultSource)
 63                        }
 64                    }
 65                    if viewModel.resultsLoaded {
 66                        Section { SummaryView(fields: viewModel.summaryFields) }
 67                        if let report = viewModel.currentReport {
 68                            Section { RiskSummaryCardView(report: report) }
 69                            Section { InsightsSummaryCardView(insights: report.insights) }
 70                        }
 71                        if let changeSummary = viewModel.currentChangeSummary {
 72                            Section { DomainChangeSummaryView(summary: changeSummary) }
 73                        }
 74                    }
 75                    if let report = viewModel.currentReport {
 76                        Section { intelligenceSection(report: report) }
 77                    }
 78                    Section { domainOverviewSection }
 79                    Section { ownershipSection }
 80                    Section { subdomainsSection }
 81                    if !viewModel.currentDiffSections.isEmpty {
 82                        Section {
 83                            DomainDiffView(
 84                                title: "Latest Changes",
 85                                sections: viewModel.currentDiffSections,
 86                                contextNote: viewModel.currentChangeSummary?.contextNote,
 87                                showsUnchanged: false,
 88                                highlightedSectionID: nil
 89                            )
 90                        }
 91                    }
 92                    Section { dnsSection }
 93                    Section {
 94                        WebSectionView(
 95                            isCollapsed: sectionCollapsedBinding(.web),
 96                            data: viewModel.webSectionData
 97                        )
 98                    }
 99                    Section {
100                        EmailSectionView(
101                            isCollapsed: sectionCollapsedBinding(.email),
102                            rows: viewModel.emailRows,
103                            assessment: viewModel.currentEmailAssessment,
104                            loading: viewModel.emailSecurityLoading,
105                            provenance: viewModel.currentSnapshot.provenanceBySection[.emailSecurity],
106                            confidence: viewModel.currentSnapshot.emailSecurityConfidence,
107                            error: viewModel.emailSecurityError
108                        )
109                    }
110                    Section {
111                        NetworkSectionView(
112                            isCollapsed: sectionCollapsedBinding(.network),
113                            customPortsExpanded: $customPortsExpanded,
114                            customPortInput: $customPortInput,
115                            data: viewModel.networkSectionData,
116                            onScanCustomPorts: runCustomPortScan
117                        )
118                    }
119                } else if !viewModel.recentSearches.isEmpty {
120                    Section { recentSearchesSection }
121                }
122            }
123            .themedListRowBackground(.surface)
124            .environment(\.cardProvidesSurface, false)
125            .scrollContentBackground(.hidden)
126            .background(ThemeToken.background)
127            .navigationTitle("DomainDig")
128            .toolbar {
129                ToolbarItem(placement: .topBarTrailing) {
130                    // While a lookup is in flight the same action is a cancel,
131                    // so it says so rather than leaving an unlabelled glyph to
132                    // stand for both.
133                    if viewModel.singleLookupRunning {
134                        Button("Cancel") {
135                            viewModel.reset()
136                        }
137                        .accessibilityLabel("Cancel lookup")
138                    } else if viewModel.hasRun {
139                        Button {
140                            viewModel.reset()
141                        } label: {
142                            Image(systemName: "xmark.circle")
143                                .foregroundStyle(ThemeToken.textSecondary)
144                        }
145                        .accessibilityLabel("Clear results")
146                    }
147                }
148
149                ToolbarItem(placement: .topBarTrailing) {
150                    NavigationLink {
151                        WorkflowsView(viewModel: viewModel)
152                    } label: {
153                        Label("Workflows", systemImage: "square.stack.3d.up")
154                    }
155                    .accessibilityLabel("Workflows")
156                }
157            }
158            .navigationDestination(for: WorkflowNavigationTarget.self) { target in
159                WorkflowDetailView(viewModel: viewModel, workflowID: target.workflowID)
160            }
161        }
162        .task {
163        }
164        .onChange(of: viewModel.searchedDomain) { _, _ in
165            collapsedSections = defaultCollapsedSections
166        }
167        .onChange(of: viewModel.resultsLoaded) { wasLoaded, isLoaded in
168            // Single-lookup completion has no single view-model moment
169            // (`resultsLoaded` is derived from many loading flags), so the
170            // announcement is posted from the view where the transition is
171            // observable. The batch path announces from the view model directly.
172            guard !wasLoaded, isLoaded, viewModel.hasRun else { return }
173            let summary = AppStatusFactory.availability(viewModel.availabilityResult?.status).title
174            AppAccessibility.announce("Lookup complete for \(viewModel.searchedDomain). \(summary).")
175        }
176        .onChange(of: viewModel.rerunNavigationToken) { _, _ in
177            navigationPath = NavigationPath()
178            focusedInputField = nil
179        }
180        .onChange(of: inputMode) { _, newValue in
181            viewModel.clearPresentedResults()
182            focusedInputField = newValue == .single ? .singleDomain : .bulkDomains
183        }
184        .onChange(of: viewModel.domain) { _, newValue in
185            viewModel.domainInputError = nil
186            guard inputMode == .single else { return }
187            let normalized = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
188            guard normalized != viewModel.searchedDomain else { return }
189            guard viewModel.hasRun || !viewModel.batchResults.isEmpty else { return }
190            viewModel.clearPresentedResults()
191        }
192        .onChange(of: viewModel.bulkInput) { _, newValue in
193            viewModel.bulkInputError = nil
194            guard inputMode == .bulk else { return }
195            let normalized = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
196            guard !normalized.isEmpty || viewModel.hasRun || !viewModel.batchResults.isEmpty else { return }
197            viewModel.clearPresentedResults()
198        }
199        .sheet(item: $editingTrackedDomain) { trackedDomain in
200            NavigationStack {
201                Form {
202                    Section("Tracking Note") {
203                        TextField("Optional note", text: $trackingNoteDraft, axis: .vertical)
204                            .lineLimit(3...6)
205                            .textInputAutocapitalization(.never)
206                            .autocorrectionDisabled()
207                    }
208                }
209                .navigationTitle(trackedDomain.domain)
210                .toolbar {
211                    ToolbarItem(placement: .cancellationAction) {
212                        Button("Cancel") {
213                            editingTrackedDomain = nil
214                        }
215                    }
216                    ToolbarItem(placement: .confirmationAction) {
217                        Button("Save") {
218                            viewModel.updateNote(trackingNoteDraft, for: trackedDomain)
219                            editingTrackedDomain = nil
220                        }
221                    }
222                }
223            }
224        }
225        .sheet(isPresented: $showingCurrentDomainWorkflowSheet) {
226            WorkflowBulkAddSheet(
227                viewModel: viewModel,
228                title: "Add Domain to Workflow",
229                availableDomains: [viewModel.searchedDomain]
230            )
231        }
232        .sheet(isPresented: $showingBatchWorkflowSheet) {
233            WorkflowBulkAddSheet(
234                viewModel: viewModel,
235                title: "Add Batch Domains",
236                availableDomains: viewModel.batchResults.map(\.domain)
237            )
238        }
239        .sheet(item: manualBatchSummaryBinding) { summary in
240            BatchSweepSummaryView(viewModel: viewModel, summary: summary)
241        }
242        .sheet(isPresented: $showingTimeline) {
243            NavigationStack {
244                TimelineView(viewModel: viewModel, domain: viewModel.searchedDomain)
245            }
246        }
247        .sheet(isPresented: $showingAuditTimeline) {
248            NavigationStack {
249                AuditDomainTimelineView(viewModel: viewModel, domain: viewModel.searchedDomain)
250            }
251        }
252    }
253
254    private var manualBatchSummaryBinding: Binding<BatchSweepSummary?> {
255        Binding(
256            get: {
257                guard let summary = viewModel.latestBatchSweepSummary,
258                      summary.source == .manual else {
259                    return nil
260                }
261                return summary
262            },
263            set: { viewModel.latestBatchSweepSummary = $0 }
264        )
265    }
266
267    private var inputSection: some View {
268        VStack(spacing: appDensity.metrics.cardSpacing + 2) {
269            Picker("Mode", selection: $inputMode) {
270                Text("Single").tag(LookupInputMode.single)
271                Text("Bulk").tag(LookupInputMode.bulk)
272            }
273            .pickerStyle(.segmented)
274
275            if inputMode == .single {
276                TextField("e.g. cleberg.net", text: $viewModel.domain)
277                    .font(appDensity.font(.title3, design: .monospaced))
278                    .textInputAutocapitalization(.never)
279                    .autocorrectionDisabled()
280                    .keyboardType(.URL)
281                    .padding(.horizontal, 12)
282                    .padding(.vertical, appDensity.metrics.controlVerticalPadding)
283                    .background(ThemeToken.surfaceElevated)
284                    .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
285                    .focused($focusedInputField, equals: .singleDomain)
286                    .onSubmit {
287                        focusedInputField = nil
288                        viewModel.run()
289                    }
290
291                if let domainInputError = viewModel.domainInputError {
292                    Text(domainInputError)
293                        .font(appDensity.font(.caption))
294                        .foregroundStyle(ThemeToken.critical)
295                        .frame(maxWidth: .infinity, alignment: .leading)
296                }
297
298                Button {
299                    focusedInputField = nil
300                    viewModel.run()
301                } label: {
302                    Text("Run")
303                        .font(appDensity.font(.headline, design: .default, weight: .semibold))
304                        .frame(maxWidth: .infinity)
305                        .frame(minHeight: appDensity.metrics.controlMinHeight)
306                }
307                .buttonStyle(.borderedProminent)
308                .tint(ThemeToken.accent)
309                .disabled(viewModel.trimmedDomain.isEmpty)
310            } else {
311                if FeatureAccessService.hasAccess(to: .batchOperations) {
312                    VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
313                        Text("Paste domains separated by new lines or commas.")
314                            .font(appDensity.font(.caption))
315                            .foregroundStyle(ThemeToken.textSecondary)
316
317                        if let batchAllowanceSummary = FeatureAccessService.batchAllowanceSummary() {
318                            Text(batchAllowanceSummary)
319                                .font(appDensity.font(.caption2))
320                                .foregroundStyle(ThemeToken.textSecondary)
321                        }
322
323                        TextField(
324                            "example.com\napple.com, openai.com",
325                            text: $viewModel.bulkInput,
326                            axis: .vertical
327                        )
328                        .font(appDensity.font(.body))
329                        .textInputAutocapitalization(.never)
330                        .autocorrectionDisabled()
331                        .keyboardType(.URL)
332                        .lineLimit(4...10)
333                        .padding(.horizontal, 12)
334                        .padding(.vertical, appDensity.metrics.controlVerticalPadding)
335                        .background(ThemeToken.surfaceElevated)
336                        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
337                        .focused($focusedInputField, equals: .bulkDomains)
338
339                        if let bulkInputError = viewModel.bulkInputError {
340                            Text(bulkInputError)
341                                .font(appDensity.font(.caption))
342                                .foregroundStyle(ThemeToken.critical)
343                                .frame(maxWidth: .infinity, alignment: .leading)
344                        }
345
346                        Button {
347                            focusedInputField = nil
348                            viewModel.runBulkLookup()
349                        } label: {
350                            Text(viewModel.batchLookupRunning ? "Running Batch…" : "Run Batch")
351                                .font(appDensity.font(.headline, design: .default, weight: .semibold))
352                                .frame(maxWidth: .infinity)
353                                .frame(minHeight: appDensity.metrics.controlMinHeight)
354                        }
355                        .buttonStyle(.borderedProminent)
356                        .tint(ThemeToken.accent)
357                        .disabled(viewModel.bulkInput.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || viewModel.batchLookupRunning)
358                    }
359                } else {
360                    lockedFeatureCard(
361                        title: "Batch Operations",
362                        message: FeatureAccessService.upgradeMessage(for: .batchOperations)
363                    )
364                }
365            }
366        }
367        .padding(.vertical, appDensity.metrics.sectionSpacing)
368    }
369
370    private var domainOverviewSection: some View {
371        let trackedDomain = viewModel.currentTrackedDomain
372        let workflows = viewModel.currentDomainWorkflows
373
374        return DomainSectionView(
375            isCollapsed: sectionCollapsedBinding(.domain),
376            rows: viewModel.domainRows,
377            suggestions: viewModel.suggestionRows,
378            showSuggestions: viewModel.availabilityResult?.status == .registered || viewModel.suggestionsLoading,
379            availabilityLoading: viewModel.availabilityLoading,
380            suggestionsLoading: viewModel.suggestionsLoading,
381            provenance: viewModel.currentSnapshot.provenanceBySection[.availability],
382            confidence: viewModel.currentSnapshot.availabilityConfidence,
383            snapshotNote: viewModel.currentSnapshot.note,
384            trackedDomain: trackedDomain,
385            workflows: workflows,
386            trackingLimitMessage: viewModel.trackingLimitMessage,
387
388            onTrack: {
389                _ = viewModel.trackCurrentDomain()
390            },
391            onTogglePinned: {
392                guard let trackedDomain else { return }
393                viewModel.togglePinned(for: trackedDomain)
394            },
395            onEditNote: {
396                guard let trackedDomain else { return }
397                trackingNoteDraft = trackedDomain.note ?? ""
398                editingTrackedDomain = trackedDomain
399            },
400            onAddToWorkflow: {
401                showingCurrentDomainWorkflowSheet = true
402            },
403            onOpenWorkflow: { workflow in
404                navigationPath.append(WorkflowNavigationTarget(workflowID: workflow.id))
405            },
406            onRunWorkflow: { workflow in
407                viewModel.rerunCurrentDomain(in: workflow)
408            }
409        )
410    }
411
412    private func intelligenceSection(report: DomainReport) -> some View {
413        IntelligenceSectionView(
414            isCollapsed: sectionCollapsedBinding(.intelligence),
415            report: report,
416            showsPlaceholder: !FeatureAccessService.hasAccess(to: .intelligenceDetail)
417        )
418    }
419
420    private var ownershipSection: some View {
421        OwnershipSectionView(
422            isCollapsed: sectionCollapsedBinding(.ownership),
423            rows: viewModel.ownershipRows,
424            loading: viewModel.ownershipLoading,
425            error: viewModel.ownershipError,
426            provenance: viewModel.currentSnapshot.provenanceBySection[.ownership],
427            confidence: viewModel.currentSnapshot.ownershipConfidence,
428            history: viewModel.ownershipHistory,
429            historyLoading: viewModel.ownershipHistoryLoading,
430            historyError: viewModel.ownershipHistoryError,
431            onLoadHistory: {
432                Task {
433                    await viewModel.loadOwnershipHistory()
434                }
435            }
436        )
437    }
438
439    private var subdomainsSection: some View {
440        SubdomainsSectionView(
441            isCollapsed: sectionCollapsedBinding(.subdomains),
442            rows: viewModel.subdomainRows,
443            groups: viewModel.currentSubdomainGroups,
444            loading: viewModel.subdomainsLoading,
445            error: viewModel.subdomainsError,
446            provenance: viewModel.currentSnapshot.provenanceBySection[.subdomains],
447            confidence: viewModel.currentSnapshot.subdomainConfidence,
448            showsExtendedPlaceholder: !FeatureAccessService.hasAccess(to: .extendedSubdomains),
449            extendedCount: viewModel.extendedSubdomains.count,
450            extendedLoading: viewModel.extendedSubdomainsLoading,
451            extendedError: viewModel.extendedSubdomainsError,
452            onLoadExtended: {
453                Task {
454                    await viewModel.loadExtendedSubdomains()
455                }
456            }
457        )
458    }
459
460    private var dnsSection: some View {
461        DNSSectionView(
462            isCollapsed: sectionCollapsedBinding(.dns),
463            dnssecLabel: viewModel.dnssecLabel,
464            patternSummary: viewModel.currentDNSPatterns,
465            sections: viewModel.dnsRows,
466            ptrMessage: viewModel.ptrMessage,
467            loading: viewModel.dnsLoading || viewModel.ptrLoading,
468            dnsProvenance: viewModel.currentSnapshot.provenanceBySection[.dns],
469            ptrProvenance: viewModel.currentSnapshot.provenanceBySection[.ptr],
470            sectionError: viewModel.dnsError,
471            history: viewModel.dnsHistory,
472            historyLoading: viewModel.dnsHistoryLoading,
473            historyError: viewModel.dnsHistoryError,
474            onLoadHistory: {
475                Task {
476                    await viewModel.loadDNSHistory()
477                }
478            }
479        )
480    }
481
482    private var actionButtons: some View {
483        HStack {
484            Spacer()
485            if viewModel.resultsLoaded {
486                Menu {
487                    if !viewModel.isCurrentDomainTracked {
488                        Button("Track this domain") {
489                            _ = viewModel.trackCurrentDomain()
490                        }
491                    }
492                    Button("Add to workflow") {
493                        showingCurrentDomainWorkflowSheet = true
494                    }
495                    Button(auditStartInFlight ? "Starting audit…" : "Start audit") {
496                        Task {
497                            auditStartInFlight = true
498                            if await viewModel.startAudit(for: viewModel.searchedDomain) != nil {
499                                showingAuditTimeline = true
500                            }
501                            auditStartInFlight = false
502                        }
503                    }
504                    .disabled(auditStartInFlight)
505                    if !viewModel.audits(for: viewModel.searchedDomain).isEmpty {
506                        Button("View audits") {
507                            showingAuditTimeline = true
508                        }
509                    }
510                    if !viewModel.historyEntries(for: viewModel.searchedDomain).isEmpty {
511                        Button("Open timeline") {
512                            showingTimeline = true
513                        }
514                    }
515                    if FeatureAccessService.hasAccess(to: .advancedExports) {
516                        Button("Copy report JSON") {
517                            guard let json = viewModel.exportJSONString() else { return }
518                            AppClipboard.copy(json)
519                            AppHaptics.copy()
520                        }
521                    } else {
522                        Button("Copy report JSON") {
523                            viewModel.upgradePrompt = FeatureAccessService.upgradePrompt(for: .advancedExports)
524                        }
525                    }
526                    Button("Export report") {
527                        shareSingleResults(format: .text)
528                    }
529                } label: {
530                    Image(systemName: "bolt.circle")
531                        .font(appDensity.font(.body, design: .default))
532                        .foregroundStyle(ThemeToken.textSecondary)
533                }
534                .accessibilityLabel("Actions")
535                Menu {
536                    ExportFormatButtons(share: shareSingleResults)
537                } label: {
538                    Image(systemName: "square.and.arrow.up")
539                        .font(appDensity.font(.body, design: .default))
540                        .foregroundStyle(ThemeToken.textSecondary)
541                }
542                .accessibilityLabel("Export")
543            }
544        }
545    }
546
547    private var batchSection: some View {
548        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
549            HStack {
550                Spacer()
551                if viewModel.batchLookupRunning {
552                    Button("Cancel") {
553                        viewModel.cancelBatchLookup()
554                    }
555                    .buttonStyle(.bordered)
556                    .font(appDensity.font(.caption))
557                }
558                if !viewModel.currentBatchResultEntries.isEmpty {
559                    Menu {
560                        Button("Add to Workflow") {
561                            showingBatchWorkflowSheet = true
562                        }
563                        Divider()
564                        ExportFormatButtons(share: shareBatchResults, batch: true)
565                    } label: {
566                        Label("Export", systemImage: "square.and.arrow.up")
567                            .font(appDensity.font(.caption))
568                    }
569                    .buttonStyle(.bordered)
570                }
571            }
572
573            BatchResultsView(
574                viewModel: viewModel,
575                title: viewModel.batchLookupSource == .watchlistRefresh ? "Tracked Domain Refresh" : "Batch Results"
576            )
577        }
578    }
579
580    private var recentSearchesSection: some View {
581        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
582            HStack {
583                Text("RECENT")
584                    .font(appDensity.font(.caption2))
585                    .foregroundStyle(ThemeToken.textSecondary)
586                Spacer()
587                Button("Clear") {
588                    viewModel.clearRecentSearches()
589                }
590                .font(appDensity.font(.caption2))
591                .foregroundStyle(ThemeToken.textSecondary)
592                // `.caption2` text alone is around 16pt tall, well under the
593                // WCAG 2.5.8 floor, which is what the audit reports here.
594                .frame(minWidth: AppLayout.minimumTapTarget, minHeight: AppLayout.minimumTapTarget)
595                .contentShape(Rectangle())
596                .buttonStyle(.borderless)
597                .accessibilityLabel("Clear recent searches")
598            }
599
600            ForEach(viewModel.recentSearches, id: \.self) { domain in
601                Button {
602                    viewModel.domain = domain
603                    focusedInputField = nil
604                    viewModel.run()
605                } label: {
606                    Text(domain)
607                        .font(appDensity.font(.callout))
608                        .foregroundStyle(.primary)
609                        .frame(maxWidth: .infinity, alignment: .leading)
610                        .padding(.vertical, 8)
611                        .padding(.horizontal, 10)
612                        .background(ThemeToken.surface)
613                        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
614                }
615                // Every button in this one List row fires on a tap unless it
616                // is borderless.
617                .buttonStyle(.borderless)
618                // A bare domain reads as neither a word nor an action; the
619                // button re-runs the lookup, so say that.
620                .accessibilityLabel("Look up \(domain)")
621            }
622        }
623        .padding(.top, appDensity.metrics.cardSpacing)
624    }
625
626    private func runCustomPortScan() {
627        let ports = parsedCustomPorts(from: customPortInput)
628        Task {
629            await viewModel.runCustomPortScan(ports: ports)
630        }
631    }
632
633    private func lockedFeatureCard(title: String, message: String) -> some View {
634        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
635            Text(title)
636                .font(appDensity.font(.headline, design: .default, weight: .semibold))
637            Text(message)
638                .font(appDensity.font(.callout, design: .default))
639                .foregroundStyle(ThemeToken.textSecondary)
640        }
641        .frame(maxWidth: .infinity, alignment: .leading)
642        .padding(appDensity.metrics.cardPadding)
643        .background(ThemeToken.surfaceElevated)
644        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
645    }
646
647    private func parsedCustomPorts(from input: String) -> [UInt16] {
648        let parts = input.split(separator: ",", omittingEmptySubsequences: true)
649        var seen = Set<UInt16>()
650        var ports: [UInt16] = []
651
652        for part in parts {
653            let trimmed = part.trimmingCharacters(in: .whitespacesAndNewlines)
654            guard let value = UInt16(trimmed), seen.insert(value).inserted else {
655                continue
656            }
657            ports.append(value)
658            if ports.count == 20 {
659                break
660            }
661        }
662
663        return ports
664    }
665
666    private func shareSingleResults(format: DomainExportFormat) {
667        guard let data = viewModel.exportSingleReportData(format: format) else { return }
668        ExportPresenter.share(filename: exportFilename(prefix: "domaindig_single", format: format), data: data)
669    }
670
671    private func shareBatchResults(format: DomainExportFormat) {
672        guard let data = viewModel.exportBatchReportData(format: format) else { return }
673        ExportPresenter.share(filename: exportFilename(prefix: "domaindig_batch", format: format), data: data)
674    }
675
676    private func exportFilename(prefix: String, format: DomainExportFormat) -> String {
677        let formatter = DateFormatter()
678        formatter.dateFormat = "yyyyMMdd_HHmmss"
679        let timestamp = formatter.string(from: Date())
680        return "\(timestamp)_\(prefix).\(format.fileExtension)"
681    }
682
683    private var defaultCollapsedSections: Set<ResultSection> {
684        []
685    }
686
687    private var currentPrimaryIP: String? {
688        viewModel.currentSnapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
689    }
690
691    private var resultStatusMessage: String? {
692        if let currentStatusMessage = viewModel.currentStatusMessage {
693            return currentStatusMessage
694        }
695
696        if viewModel.currentResultSource != .live {
697            return viewModel.currentResultSource.label
698        }
699
700        return nil
701    }
702
703    private func sectionCollapsedBinding(_ section: ResultSection) -> Binding<Bool> {
704        Binding(
705            get: { collapsedSections.contains(section) },
706            set: { isCollapsed in
707                if isCollapsed {
708                    collapsedSections.insert(section)
709                } else {
710                    collapsedSections.remove(section)
711                }
712            }
713        )
714    }
715}