DomainDig/ContentView.swift

1562 lines · 65448 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            ScrollView(.vertical) {
  52                VStack(spacing: 0) {
  53                    inputSection
  54                    if !viewModel.batchResults.isEmpty || viewModel.batchLookupRunning {
  55                        batchSection
  56                            .padding(.top, appDensity.metrics.cardSpacing)
  57                    }
  58                    if viewModel.hasRun {
  59                        actionButtons
  60                        if !viewModel.resultsLoaded {
  61                            LookupProgressOverviewView(steps: viewModel.activeLoadingLabels)
  62                                .padding(.top, appDensity.metrics.cardSpacing)
  63                        } else if let statusMessage = resultStatusMessage {
  64                            LookupStatusBannerView(message: statusMessage, resultSource: viewModel.currentResultSource)
  65                                .padding(.top, appDensity.metrics.cardSpacing)
  66                        }
  67                        if viewModel.resultsLoaded {
  68                            SummaryView(fields: viewModel.summaryFields)
  69                                .padding(.top, appDensity.metrics.cardSpacing)
  70                            if let report = viewModel.currentReport {
  71                                RiskSummaryCardView(report: report)
  72                                    .padding(.top, appDensity.metrics.cardSpacing)
  73                                InsightsSummaryCardView(insights: report.insights)
  74                                    .padding(.top, appDensity.metrics.cardSpacing)
  75                            }
  76                            if let changeSummary = viewModel.currentChangeSummary {
  77                                DomainChangeSummaryView(summary: changeSummary)
  78                                    .padding(.top, appDensity.metrics.cardSpacing)
  79                            }
  80                        }
  81                        if let report = viewModel.currentReport {
  82                            intelligenceSection(report: report)
  83                                .padding(.top, appDensity.metrics.sectionSpacing)
  84                        }
  85                        domainOverviewSection
  86                            .padding(.top, appDensity.metrics.sectionSpacing)
  87                        ownershipSection
  88                        .padding(.top, appDensity.metrics.sectionSpacing)
  89                        subdomainsSection
  90                        .padding(.top, appDensity.metrics.sectionSpacing)
  91                        if !viewModel.currentDiffSections.isEmpty {
  92                            DomainDiffView(
  93                                title: "Latest Changes",
  94                                sections: viewModel.currentDiffSections,
  95                                contextNote: viewModel.currentChangeSummary?.contextNote,
  96                                showsUnchanged: false,
  97                                highlightedSectionID: nil
  98                            )
  99                            .padding(.top, appDensity.metrics.sectionSpacing)
 100                        }
 101                        dnsSection
 102                        .padding(.top, appDensity.metrics.sectionSpacing)
 103                        WebSectionView(
 104                            isCollapsed: sectionCollapsedBinding(.web),
 105                            certificateRows: viewModel.webCertificateRows,
 106                            sslInfo: viewModel.sslInfo,
 107                            tlsSummary: viewModel.currentTLSSummary,
 108                            sslLoading: viewModel.sslLoading || viewModel.hstsLoading,
 109                            sslError: viewModel.sslError,
 110                            tlsProvenance: viewModel.currentSnapshot.provenanceBySection[.ssl],
 111                            responseRows: viewModel.webResponseRows,
 112                            headers: viewModel.httpHeaders,
 113                            headersLoading: viewModel.httpHeadersLoading,
 114                            headersError: viewModel.httpHeadersError,
 115                            httpProvenance: viewModel.currentSnapshot.provenanceBySection[.httpHeaders],
 116                            redirects: viewModel.redirectRows,
 117                            redirectLoading: viewModel.redirectChainLoading,
 118                            redirectError: viewModel.redirectChainError,
 119                            redirectProvenance: viewModel.currentSnapshot.provenanceBySection[.redirectChain],
 120                            finalURL: viewModel.currentSnapshot.redirectChain.last?.url
 121                        )
 122                        .padding(.top, appDensity.metrics.sectionSpacing)
 123                        EmailSectionView(
 124                            isCollapsed: sectionCollapsedBinding(.email),
 125                            rows: viewModel.emailRows,
 126                            assessment: viewModel.currentEmailAssessment,
 127                            loading: viewModel.emailSecurityLoading,
 128                            provenance: viewModel.currentSnapshot.provenanceBySection[.emailSecurity],
 129                            confidence: viewModel.currentSnapshot.emailSecurityConfidence,
 130                            error: viewModel.emailSecurityError
 131                        )
 132                        .padding(.top, appDensity.metrics.sectionSpacing)
 133                        NetworkSectionView(
 134                            isCollapsed: sectionCollapsedBinding(.network),
 135                            reachabilityRows: viewModel.reachabilityRows,
 136                            reachabilityLoading: viewModel.reachabilityLoading,
 137                            reachabilityError: viewModel.reachabilityError,
 138                            reachabilityProvenance: viewModel.currentSnapshot.provenanceBySection[.reachability],
 139                            locationRows: viewModel.locationRows,
 140                            geolocation: viewModel.ipGeolocation,
 141                            geolocationLoading: viewModel.ipGeolocationLoading,
 142                            geolocationError: viewModel.ipGeolocationError,
 143                            geolocationProvenance: viewModel.currentSnapshot.provenanceBySection[.ipGeolocation],
 144                            geolocationConfidence: viewModel.currentSnapshot.geolocationConfidence,
 145                            standardPortRows: viewModel.standardPortRows,
 146                            customPortRows: viewModel.customPortRows,
 147                            portScanLoading: viewModel.portScanLoading,
 148                            portScanError: viewModel.portScanError,
 149                            portScanProvenance: viewModel.currentSnapshot.provenanceBySection[.portScan],
 150                            customPortScanLoading: viewModel.customPortScanLoading,
 151                            customPortScanError: viewModel.customPortScanError,
 152                            isCloudflareProxied: viewModel.isCloudflareProxied,
 153                            customPortsExpanded: $customPortsExpanded,
 154                            customPortInput: $customPortInput,
 155                            onScanCustomPorts: runCustomPortScan
 156                        )
 157                        .padding(.top, appDensity.metrics.sectionSpacing)
 158                    } else if !viewModel.recentSearches.isEmpty {
 159                        recentSearchesSection
 160                    }
 161                }
 162                .padding(.horizontal)
 163                .padding(.bottom, 32)
 164            }
 165            .background(
 166                LinearGradient(
 167                    colors: [Color(.appBackground), Color(.appSurface)],
 168                    startPoint: .top,
 169                    endPoint: .bottom
 170                )
 171            )
 172            .navigationTitle("DomainDig")
 173            .toolbar {
 174                ToolbarItem(placement: .topBarTrailing) {
 175                    if viewModel.hasRun {
 176                        Button {
 177                            viewModel.reset()
 178                        } label: {
 179                            Image(systemName: "xmark.circle")
 180                                .foregroundStyle(Color(.appTextSecondary))
 181                        }
 182                        .accessibilityLabel("Clear results")
 183                    }
 184                }
 185            }
 186            .navigationDestination(for: WorkflowNavigationTarget.self) { target in
 187                WorkflowDetailView(viewModel: viewModel, workflowID: target.workflowID)
 188            }
 189        }
 190        .task {
 191        }
 192        .onChange(of: viewModel.searchedDomain) { _, _ in
 193            collapsedSections = defaultCollapsedSections
 194        }
 195        .onChange(of: viewModel.resultsLoaded) { wasLoaded, isLoaded in
 196            // Single-lookup completion has no single view-model moment
 197            // (`resultsLoaded` is derived from many loading flags), so the
 198            // announcement is posted from the view where the transition is
 199            // observable. The batch path announces from the view model directly.
 200            guard !wasLoaded, isLoaded, viewModel.hasRun else { return }
 201            let summary = AppStatusFactory.availability(viewModel.availabilityResult?.status).title
 202            AppAccessibility.announce("Lookup complete for \(viewModel.searchedDomain). \(summary).")
 203        }
 204        .onChange(of: viewModel.rerunNavigationToken) { _, _ in
 205            navigationPath = NavigationPath()
 206            focusedInputField = nil
 207        }
 208        .onChange(of: inputMode) { _, newValue in
 209            viewModel.clearPresentedResults()
 210            focusedInputField = newValue == .single ? .singleDomain : .bulkDomains
 211        }
 212        .onChange(of: viewModel.domain) { _, newValue in
 213            viewModel.domainInputError = nil
 214            guard inputMode == .single else { return }
 215            let normalized = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
 216            guard normalized != viewModel.searchedDomain else { return }
 217            guard viewModel.hasRun || !viewModel.batchResults.isEmpty else { return }
 218            viewModel.clearPresentedResults()
 219        }
 220        .onChange(of: viewModel.bulkInput) { _, newValue in
 221            guard inputMode == .bulk else { return }
 222            let normalized = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
 223            guard !normalized.isEmpty || viewModel.hasRun || !viewModel.batchResults.isEmpty else { return }
 224            viewModel.clearPresentedResults()
 225        }
 226        .sheet(item: $editingTrackedDomain) { trackedDomain in
 227            NavigationStack {
 228                Form {
 229                    Section("Tracking Note") {
 230                        TextField("Optional note", text: $trackingNoteDraft, axis: .vertical)
 231                            .lineLimit(3...6)
 232                            .textInputAutocapitalization(.never)
 233                            .autocorrectionDisabled()
 234                    }
 235                }
 236                .navigationTitle(trackedDomain.domain)
 237                .toolbar {
 238                    ToolbarItem(placement: .cancellationAction) {
 239                        Button("Cancel") {
 240                            editingTrackedDomain = nil
 241                        }
 242                    }
 243                    ToolbarItem(placement: .confirmationAction) {
 244                        Button("Save") {
 245                            viewModel.updateNote(trackingNoteDraft, for: trackedDomain)
 246                            editingTrackedDomain = nil
 247                        }
 248                    }
 249                }
 250            }
 251        }
 252        .sheet(isPresented: $showingCurrentDomainWorkflowSheet) {
 253            WorkflowBulkAddSheet(
 254                viewModel: viewModel,
 255                title: "Add Domain to Workflow",
 256                availableDomains: [viewModel.searchedDomain]
 257            )
 258        }
 259        .sheet(isPresented: $showingBatchWorkflowSheet) {
 260            WorkflowBulkAddSheet(
 261                viewModel: viewModel,
 262                title: "Add Batch Domains",
 263                availableDomains: viewModel.batchResults.map(\.domain)
 264            )
 265        }
 266        .sheet(item: manualBatchSummaryBinding) { summary in
 267            BatchSweepSummaryView(viewModel: viewModel, summary: summary)
 268        }
 269        .sheet(isPresented: $showingTimeline) {
 270            NavigationStack {
 271                TimelineView(viewModel: viewModel, domain: viewModel.searchedDomain)
 272            }
 273        }
 274        .sheet(isPresented: $showingAuditTimeline) {
 275            NavigationStack {
 276                AuditDomainTimelineView(viewModel: viewModel, domain: viewModel.searchedDomain)
 277            }
 278        }
 279    }
 280
 281    private var manualBatchSummaryBinding: Binding<BatchSweepSummary?> {
 282        Binding(
 283            get: {
 284                guard let summary = viewModel.latestBatchSweepSummary,
 285                      summary.source == .manual else {
 286                    return nil
 287                }
 288                return summary
 289            },
 290            set: { viewModel.latestBatchSweepSummary = $0 }
 291        )
 292    }
 293
 294    private var inputSection: some View {
 295        VStack(spacing: appDensity.metrics.cardSpacing + 2) {
 296            Picker("Mode", selection: $inputMode) {
 297                Text("Single").tag(LookupInputMode.single)
 298                Text("Bulk").tag(LookupInputMode.bulk)
 299            }
 300            .pickerStyle(.segmented)
 301
 302            if inputMode == .single {
 303                TextField("e.g. cleberg.net", text: $viewModel.domain)
 304                    .font(appDensity.font(.title3, design: .monospaced))
 305                    .textInputAutocapitalization(.never)
 306                    .autocorrectionDisabled()
 307                    .keyboardType(.URL)
 308                    .padding(.horizontal, 12)
 309                    .padding(.vertical, appDensity.metrics.controlVerticalPadding)
 310                    .background(Color(.appSurfaceElevated))
 311                    .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
 312                    .focused($focusedInputField, equals: .singleDomain)
 313                    .onSubmit {
 314                        focusedInputField = nil
 315                        viewModel.run()
 316                    }
 317
 318                if let domainInputError = viewModel.domainInputError {
 319                    Text(domainInputError)
 320                        .font(appDensity.font(.caption))
 321                        .foregroundStyle(Color(.statusCritical))
 322                        .frame(maxWidth: .infinity, alignment: .leading)
 323                }
 324
 325                Button {
 326                    focusedInputField = nil
 327                    viewModel.run()
 328                } label: {
 329                    Text("Run")
 330                        .font(appDensity.font(.headline, design: .default, weight: .semibold))
 331                        .frame(maxWidth: .infinity)
 332                        .frame(minHeight: appDensity.metrics.controlMinHeight)
 333                }
 334                .buttonStyle(.borderedProminent)
 335                .tint(Color(.accentFill))
 336                .disabled(viewModel.trimmedDomain.isEmpty)
 337            } else {
 338                if FeatureAccessService.hasAccess(to: .batchOperations) {
 339                    VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 340                        Text("Paste domains separated by new lines or commas.")
 341                            .font(appDensity.font(.caption))
 342                            .foregroundStyle(Color(.appTextSecondary))
 343
 344                        if let batchAllowanceSummary = FeatureAccessService.batchAllowanceSummary() {
 345                            Text(batchAllowanceSummary)
 346                                .font(appDensity.font(.caption2))
 347                                .foregroundStyle(Color(.appTextSecondary))
 348                        }
 349
 350                        TextField(
 351                            "example.com\napple.com, openai.com",
 352                            text: $viewModel.bulkInput,
 353                            axis: .vertical
 354                        )
 355                        .font(appDensity.font(.body))
 356                        .textInputAutocapitalization(.never)
 357                        .autocorrectionDisabled()
 358                        .keyboardType(.URL)
 359                        .lineLimit(4...10)
 360                        .padding(.horizontal, 12)
 361                        .padding(.vertical, appDensity.metrics.controlVerticalPadding)
 362                        .background(Color(.appSurfaceElevated))
 363                        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
 364                        .focused($focusedInputField, equals: .bulkDomains)
 365
 366                        Button {
 367                            focusedInputField = nil
 368                            viewModel.runBulkLookup()
 369                        } label: {
 370                            Text(viewModel.batchLookupRunning ? "Running Batch…" : "Run Batch")
 371                                .font(appDensity.font(.headline, design: .default, weight: .semibold))
 372                                .frame(maxWidth: .infinity)
 373                                .frame(minHeight: appDensity.metrics.controlMinHeight)
 374                        }
 375                        .buttonStyle(.borderedProminent)
 376                        .tint(Color(.accentFill))
 377                        .disabled(viewModel.bulkInput.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || viewModel.batchLookupRunning)
 378                    }
 379                } else {
 380                    lockedFeatureCard(
 381                        title: "Batch Operations",
 382                        message: FeatureAccessService.upgradeMessage(for: .batchOperations)
 383                    )
 384                }
 385            }
 386        }
 387        .padding(.vertical, appDensity.metrics.sectionSpacing)
 388    }
 389
 390    private var domainOverviewSection: some View {
 391        let trackedDomain = viewModel.currentTrackedDomain
 392        let workflows = viewModel.currentDomainWorkflows
 393
 394        return DomainSectionView(
 395            isCollapsed: sectionCollapsedBinding(.domain),
 396            rows: viewModel.domainRows,
 397            suggestions: viewModel.suggestionRows,
 398            showSuggestions: viewModel.availabilityResult?.status == .registered || viewModel.suggestionsLoading,
 399            availabilityLoading: viewModel.availabilityLoading,
 400            suggestionsLoading: viewModel.suggestionsLoading,
 401            provenance: viewModel.currentSnapshot.provenanceBySection[.availability],
 402            confidence: viewModel.currentSnapshot.availabilityConfidence,
 403            snapshotNote: viewModel.currentSnapshot.note,
 404            trackedDomain: trackedDomain,
 405            workflows: workflows,
 406            trackingLimitMessage: viewModel.trackingLimitMessage,
 407
 408            onTrack: {
 409                _ = viewModel.trackCurrentDomain()
 410            },
 411            onTogglePinned: {
 412                guard let trackedDomain else { return }
 413                viewModel.togglePinned(for: trackedDomain)
 414            },
 415            onEditNote: {
 416                guard let trackedDomain else { return }
 417                trackingNoteDraft = trackedDomain.note ?? ""
 418                editingTrackedDomain = trackedDomain
 419            },
 420            onAddToWorkflow: {
 421                showingCurrentDomainWorkflowSheet = true
 422            },
 423            onOpenWorkflow: { workflow in
 424                navigationPath.append(WorkflowNavigationTarget(workflowID: workflow.id))
 425            },
 426            onRunWorkflow: { workflow in
 427                viewModel.rerunCurrentDomain(in: workflow)
 428            }
 429        )
 430    }
 431
 432    private func intelligenceSection(report: DomainReport) -> some View {
 433        IntelligenceSectionView(
 434            isCollapsed: sectionCollapsedBinding(.intelligence),
 435            report: report,
 436            showsPlaceholder: !FeatureAccessService.hasAccess(to: .intelligenceDetail)
 437        )
 438    }
 439
 440    private var ownershipSection: some View {
 441        OwnershipSectionView(
 442            isCollapsed: sectionCollapsedBinding(.ownership),
 443            rows: viewModel.ownershipRows,
 444            loading: viewModel.ownershipLoading,
 445            error: viewModel.ownershipError,
 446            provenance: viewModel.currentSnapshot.provenanceBySection[.ownership],
 447            confidence: viewModel.currentSnapshot.ownershipConfidence,
 448            history: viewModel.ownershipHistory,
 449            historyLoading: viewModel.ownershipHistoryLoading,
 450            historyError: viewModel.ownershipHistoryError,
 451            onLoadHistory: {
 452                Task {
 453                    await viewModel.loadOwnershipHistory()
 454                }
 455            }
 456        )
 457    }
 458
 459    private var subdomainsSection: some View {
 460        SubdomainsSectionView(
 461            isCollapsed: sectionCollapsedBinding(.subdomains),
 462            rows: viewModel.subdomainRows,
 463            groups: viewModel.currentSubdomainGroups,
 464            loading: viewModel.subdomainsLoading,
 465            error: viewModel.subdomainsError,
 466            provenance: viewModel.currentSnapshot.provenanceBySection[.subdomains],
 467            confidence: viewModel.currentSnapshot.subdomainConfidence,
 468            showsExtendedPlaceholder: !FeatureAccessService.hasAccess(to: .extendedSubdomains),
 469            extendedCount: viewModel.extendedSubdomains.count,
 470            extendedLoading: viewModel.extendedSubdomainsLoading,
 471            extendedError: viewModel.extendedSubdomainsError,
 472            onLoadExtended: {
 473                Task {
 474                    await viewModel.loadExtendedSubdomains()
 475                }
 476            }
 477        )
 478    }
 479
 480    private var dnsSection: some View {
 481        DNSSectionView(
 482            isCollapsed: sectionCollapsedBinding(.dns),
 483            dnssecLabel: viewModel.dnssecLabel,
 484            patternSummary: viewModel.currentDNSPatterns,
 485            sections: viewModel.dnsRows,
 486            ptrMessage: viewModel.ptrMessage,
 487            loading: viewModel.dnsLoading || viewModel.ptrLoading,
 488            dnsProvenance: viewModel.currentSnapshot.provenanceBySection[.dns],
 489            ptrProvenance: viewModel.currentSnapshot.provenanceBySection[.ptr],
 490            sectionError: viewModel.dnsError,
 491            history: viewModel.dnsHistory,
 492            historyLoading: viewModel.dnsHistoryLoading,
 493            historyError: viewModel.dnsHistoryError,
 494            onLoadHistory: {
 495                Task {
 496                    await viewModel.loadDNSHistory()
 497                }
 498            }
 499        )
 500    }
 501
 502    private var actionButtons: some View {
 503        HStack {
 504            Spacer()
 505            if viewModel.resultsLoaded {
 506                Menu {
 507                    if !viewModel.isCurrentDomainTracked {
 508                        Button("Track this domain") {
 509                            _ = viewModel.trackCurrentDomain()
 510                        }
 511                    }
 512                    Button("Add to workflow") {
 513                        showingCurrentDomainWorkflowSheet = true
 514                    }
 515                    Button(auditStartInFlight ? "Starting audit…" : "Start audit") {
 516                        Task {
 517                            auditStartInFlight = true
 518                            if await viewModel.startAudit(for: viewModel.searchedDomain) != nil {
 519                                showingAuditTimeline = true
 520                            }
 521                            auditStartInFlight = false
 522                        }
 523                    }
 524                    .disabled(auditStartInFlight)
 525                    if !viewModel.audits(for: viewModel.searchedDomain).isEmpty {
 526                        Button("View audits") {
 527                            showingAuditTimeline = true
 528                        }
 529                    }
 530                    if !viewModel.historyEntries(for: viewModel.searchedDomain).isEmpty {
 531                        Button("Open timeline") {
 532                            showingTimeline = true
 533                        }
 534                    }
 535                    if FeatureAccessService.hasAccess(to: .advancedExports) {
 536                        Button("Copy report JSON") {
 537                            guard let json = viewModel.exportJSONString() else { return }
 538                            AppClipboard.copy(json)
 539                            AppHaptics.copy()
 540                        }
 541                    } else {
 542                        Button("Copy report JSON") {
 543                            viewModel.upgradePrompt = FeatureAccessService.upgradePrompt(for: .advancedExports)
 544                        }
 545                    }
 546                    Button("Export report") {
 547                        shareSingleResults(format: .text)
 548                    }
 549                } label: {
 550                    Image(systemName: "bolt.circle")
 551                        .font(appDensity.font(.body, design: .default))
 552                        .foregroundStyle(Color(.appTextSecondary))
 553                }
 554                .accessibilityLabel("Actions")
 555                Menu {
 556                    ExportFormatButtons(share: shareSingleResults)
 557                } label: {
 558                    Image(systemName: "square.and.arrow.up")
 559                        .font(appDensity.font(.body, design: .default))
 560                        .foregroundStyle(Color(.appTextSecondary))
 561                }
 562                .accessibilityLabel("Export")
 563            }
 564        }
 565    }
 566
 567    private var batchSection: some View {
 568        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 569            HStack {
 570                Spacer()
 571                if viewModel.batchLookupRunning {
 572                    Button("Cancel") {
 573                        viewModel.cancelBatchLookup()
 574                    }
 575                    .buttonStyle(.bordered)
 576                    .font(appDensity.font(.caption))
 577                }
 578                if !viewModel.currentBatchResultEntries.isEmpty {
 579                    Menu {
 580                        Button("Add to Workflow") {
 581                            showingBatchWorkflowSheet = true
 582                        }
 583                        Divider()
 584                        ExportFormatButtons(share: shareBatchResults, batch: true)
 585                    } label: {
 586                        Label("Export", systemImage: "square.and.arrow.up")
 587                            .font(appDensity.font(.caption))
 588                    }
 589                    .buttonStyle(.bordered)
 590                }
 591            }
 592
 593            BatchResultsView(
 594                viewModel: viewModel,
 595                title: viewModel.batchLookupSource == .watchlistRefresh ? "Tracked Domain Refresh" : "Batch Results"
 596            )
 597        }
 598    }
 599
 600    private var recentSearchesSection: some View {
 601        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 602            HStack {
 603                Text("RECENT")
 604                    .font(appDensity.font(.caption2))
 605                    .foregroundStyle(Color(.appTextSecondary))
 606                Spacer()
 607                Button("Clear") {
 608                    viewModel.clearRecentSearches()
 609                }
 610                .font(appDensity.font(.caption2))
 611                .foregroundStyle(Color(.appTextSecondary))
 612            }
 613
 614            ForEach(viewModel.recentSearches, id: \.self) { domain in
 615                Button {
 616                    viewModel.domain = domain
 617                    focusedInputField = nil
 618                    viewModel.run()
 619                } label: {
 620                    Text(domain)
 621                        .font(appDensity.font(.callout))
 622                        .foregroundStyle(.primary)
 623                        .frame(maxWidth: .infinity, alignment: .leading)
 624                        .padding(.vertical, 8)
 625                        .padding(.horizontal, 10)
 626                        .background(Color(.appSurface))
 627                        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
 628                }
 629            }
 630        }
 631        .padding(.top, appDensity.metrics.cardSpacing)
 632    }
 633
 634    private func runCustomPortScan() {
 635        let ports = parsedCustomPorts(from: customPortInput)
 636        Task {
 637            await viewModel.runCustomPortScan(ports: ports)
 638        }
 639    }
 640
 641    private func lockedFeatureCard(title: String, message: String) -> some View {
 642        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 643            Text(title)
 644                .font(appDensity.font(.headline, design: .default, weight: .semibold))
 645            Text(message)
 646                .font(appDensity.font(.callout, design: .default))
 647                .foregroundStyle(Color(.appTextSecondary))
 648        }
 649        .frame(maxWidth: .infinity, alignment: .leading)
 650        .padding(appDensity.metrics.cardPadding)
 651        .background(Color(.appSurfaceElevated))
 652        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
 653    }
 654
 655    private func parsedCustomPorts(from input: String) -> [UInt16] {
 656        let parts = input.split(separator: ",", omittingEmptySubsequences: true)
 657        var seen = Set<UInt16>()
 658        var ports: [UInt16] = []
 659
 660        for part in parts {
 661            let trimmed = part.trimmingCharacters(in: .whitespacesAndNewlines)
 662            guard let value = UInt16(trimmed), seen.insert(value).inserted else {
 663                continue
 664            }
 665            ports.append(value)
 666            if ports.count == 20 {
 667                break
 668            }
 669        }
 670
 671        return ports
 672    }
 673
 674    private func shareSingleResults(format: DomainExportFormat) {
 675        guard let data = viewModel.exportSingleReportData(format: format) else { return }
 676        ExportPresenter.share(filename: exportFilename(prefix: "domaindig_single", format: format), data: data)
 677    }
 678
 679    private func shareBatchResults(format: DomainExportFormat) {
 680        guard let data = viewModel.exportBatchReportData(format: format) else { return }
 681        ExportPresenter.share(filename: exportFilename(prefix: "domaindig_batch", format: format), data: data)
 682    }
 683
 684    private func exportFilename(prefix: String, format: DomainExportFormat) -> String {
 685        let formatter = DateFormatter()
 686        formatter.dateFormat = "yyyyMMdd_HHmmss"
 687        let timestamp = formatter.string(from: Date())
 688        return "\(timestamp)_\(prefix).\(format.fileExtension)"
 689    }
 690
 691    private var defaultCollapsedSections: Set<ResultSection> {
 692        []
 693    }
 694
 695    private var currentPrimaryIP: String? {
 696        viewModel.currentSnapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
 697    }
 698
 699    private var resultStatusMessage: String? {
 700        if let currentStatusMessage = viewModel.currentStatusMessage {
 701            return currentStatusMessage
 702        }
 703
 704        if viewModel.currentResultSource != .live {
 705            return viewModel.currentResultSource.label
 706        }
 707
 708        return nil
 709    }
 710
 711    private func sectionCollapsedBinding(_ section: ResultSection) -> Binding<Bool> {
 712        Binding(
 713            get: { collapsedSections.contains(section) },
 714            set: { isCollapsed in
 715                if isCollapsed {
 716                    collapsedSections.insert(section)
 717                } else {
 718                    collapsedSections.remove(section)
 719                }
 720            }
 721        )
 722    }
 723}
 724
 725struct SummaryView: View {
 726    @Environment(\.appDensity) private var appDensity
 727    let fields: [SummaryFieldViewData]
 728
 729    var body: some View {
 730        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 731            SectionTitleView(title: "Summary")
 732            LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: appDensity.metrics.cardSpacing) {
 733                ForEach(fields) { field in
 734                    VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing) {
 735                        Text(field.label)
 736                            .font(appDensity.font(.caption2))
 737                            .foregroundStyle(Color(.appTextSecondary))
 738                        Text(field.value)
 739                            .font(appDensity.font(.caption))
 740                            .foregroundStyle(ResultColors.color(for: field.tone))
 741                            .lineLimit(2)
 742                            .textSelection(.enabled)
 743                    }
 744                    .frame(minHeight: appDensity.metrics.rowMinHeight + 12, alignment: .topLeading)
 745                    .frame(maxWidth: .infinity, alignment: .leading)
 746                    .padding(appDensity.metrics.cardPadding)
 747                    .background(Color(.appSurface))
 748                    .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
 749                }
 750            }
 751        }
 752    }
 753}
 754
 755struct RiskSummaryCardView: View {
 756    @Environment(\.appDensity) private var appDensity
 757    let report: DomainReport
 758
 759    private var topFactors: [RiskFactor] {
 760        Array(report.riskAssessment.factors.prefix(3))
 761    }
 762
 763    var body: some View {
 764        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 765            SectionTitleView(title: "Risk")
 766            CardView(allowsHorizontalScroll: false) {
 767                HStack(alignment: .firstTextBaseline) {
 768                    VStack(alignment: .leading, spacing: 4) {
 769                        Text("\(report.riskAssessment.score)")
 770                            .font(appDensity.font(.largeTitle, weight: .bold))
 771                            .foregroundStyle(levelColor)
 772                        Text(report.riskAssessment.level.title)
 773                            .font(appDensity.font(.caption))
 774                            .foregroundStyle(levelColor)
 775                    }
 776                    Spacer()
 777                    Text("Deterministic")
 778                        .font(appDensity.font(.caption2))
 779                        .foregroundStyle(Color(.appTextSecondary))
 780                }
 781
 782                if topFactors.isEmpty {
 783                    Text("No major risk factors identified")
 784                        .font(appDensity.font(.caption))
 785                        .foregroundStyle(Color(.appTextSecondary))
 786                } else {
 787                    ForEach(Array(topFactors.enumerated()), id: \.offset) { _, factor in
 788                        HStack(alignment: .top, spacing: 8) {
 789                            Circle()
 790                                .fill(factorColor(factor.impact))
 791                                .frame(width: 8, height: 8)
 792                                .padding(.top, 5)
 793                            Text(factor.description)
 794                                .font(appDensity.font(.caption))
 795                                .foregroundStyle(.primary)
 796                        }
 797                    }
 798                }
 799            }
 800        }
 801    }
 802
 803    private var levelColor: Color {
 804        switch report.riskAssessment.level {
 805        case .low:
 806            return Color(.statusPositive)
 807        case .medium:
 808            return Color(.statusWarning)
 809        case .high:
 810            return Color(.statusCritical)
 811        }
 812    }
 813
 814    private func factorColor(_ impact: RiskImpact) -> Color {
 815        switch impact {
 816        case .positive:
 817            return Color(.statusPositive)
 818        case .neutral:
 819            return .secondary
 820        case .negative:
 821            return Color(.statusCritical)
 822        }
 823    }
 824}
 825
 826struct InsightsSummaryCardView: View {
 827    @Environment(\.appDensity) private var appDensity
 828    let insights: [String]
 829
 830    var body: some View {
 831        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 832            SectionTitleView(title: "Insights")
 833            CardView(allowsHorizontalScroll: false) {
 834                if insights.isEmpty {
 835                    Text("No deterministic insights triggered")
 836                        .font(appDensity.font(.caption))
 837                        .foregroundStyle(Color(.appTextSecondary))
 838                } else {
 839                    ForEach(Array(insights.enumerated()), id: \.offset) { _, insight in
 840                        HStack(alignment: .top, spacing: 8) {
 841                            Image(systemName: "chart.line.uptrend.xyaxis")
 842                                .font(appDensity.font(.caption2))
 843                                .foregroundStyle(Color(.statusInfo))
 844                                .padding(.top, 2)
 845                            Text(insight)
 846                                .font(appDensity.font(.caption))
 847                                .foregroundStyle(.primary)
 848                        }
 849                    }
 850                }
 851            }
 852        }
 853    }
 854}
 855
 856struct StickyLookupSummaryView: View {
 857    @Environment(\.appDensity) private var appDensity
 858
 859    let domain: String
 860    let availability: DomainAvailabilityStatus?
 861    let primaryIP: String?
 862    let sslInfo: SSLCertificateInfo?
 863    let sslError: String?
 864    let emailSecurity: EmailSecurityResult?
 865    let emailError: String?
 866    let changeSummary: DomainChangeSummary?
 867
 868    var body: some View {
 869        CardView(allowsHorizontalScroll: false) {
 870            VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 871                HStack(alignment: .center, spacing: 10) {
 872                    Text(domain)
 873                        .font(appDensity.font(.headline, weight: .semibold))
 874                        .foregroundStyle(.primary)
 875                        .lineLimit(1)
 876                    Spacer(minLength: 6)
 877                    AppCopyButton(value: domain, label: "Copy domain")
 878                }
 879
 880                ScrollView(.horizontal, showsIndicators: false) {
 881                    HStack(spacing: 8) {
 882                        AppStatusBadgeView(model: AppStatusFactory.availability(availability))
 883                        AppStatusBadgeView(model: AppStatusFactory.tls(sslInfo: sslInfo, error: sslError))
 884                        AppStatusBadgeView(model: AppStatusFactory.email(emailSecurity, error: emailError))
 885                        AppStatusBadgeView(model: AppStatusFactory.change(changeSummary))
 886                    }
 887                }
 888
 889                if let primaryIP {
 890                    HStack(spacing: 8) {
 891                        Label(primaryIP, systemImage: "network")
 892                            .font(appDensity.font(.caption))
 893                            .foregroundStyle(Color(.appTextSecondary))
 894                        Spacer(minLength: 6)
 895                        AppCopyButton(value: primaryIP, label: "Copy IP")
 896                    }
 897                }
 898            }
 899        }
 900        .shadow(color: .black.opacity(0.12), radius: 14, y: 6)
 901    }
 902}
 903
 904struct LookupProgressOverviewView: View {
 905    @Environment(\.appDensity) private var appDensity
 906    let steps: [String]
 907
 908    var body: some View {
 909        CardView(allowsHorizontalScroll: false) {
 910            HStack(spacing: 8) {
 911                ProgressView()
 912                    .controlSize(.small)
 913                VStack(alignment: .leading, spacing: 4) {
 914                    Text("Running lookup…")
 915                        .font(appDensity.font(.caption))
 916                        .foregroundStyle(.primary)
 917                    Text(steps.isEmpty ? "Preparing requests" : steps.joined(separator: " • "))
 918                        .font(appDensity.font(.caption2))
 919                        .foregroundStyle(Color(.appTextSecondary))
 920                }
 921                Spacer()
 922            }
 923        }
 924    }
 925}
 926
 927struct LookupStatusBannerView: View {
 928    @Environment(\.appDensity) private var appDensity
 929    let message: String
 930    let resultSource: LookupResultSource
 931
 932    var body: some View {
 933        HStack(spacing: 8) {
 934            Image(systemName: iconName)
 935                .font(.caption)
 936            Text(message)
 937                .font(appDensity.font(.caption))
 938            Spacer()
 939        }
 940        .foregroundStyle(color)
 941        .padding(appDensity.metrics.cardPadding - 2)
 942        .frame(maxWidth: .infinity, alignment: .leading)
 943        .background(color.opacity(0.12))
 944        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
 945    }
 946
 947    private var color: Color {
 948        switch resultSource {
 949        case .live:
 950            return Color(.statusPositive)
 951        case .cached:
 952            return .secondary
 953        case .mixed:
 954            return Color(.statusWarning)
 955        case .snapshot:
 956            return Color(.statusWarning)
 957        }
 958    }
 959
 960    private var iconName: String {
 961        switch resultSource {
 962        case .live:
 963            return "bolt.horizontal"
 964        case .cached:
 965            return "clock.arrow.trianglehead.counterclockwise.rotate.90"
 966        case .mixed:
 967            return "arrow.triangle.branch"
 968        case .snapshot:
 969            return "archivebox"
 970        }
 971    }
 972}
 973
 974struct DomainChangeSummaryView: View {
 975    @Environment(\.appDensity) private var appDensity
 976    let summary: DomainChangeSummary
 977    @State private var showsDetails = false
 978
 979    var body: some View {
 980        CardView(allowsHorizontalScroll: false) {
 981            HStack {
 982                Label(summary.hasChanges ? "Changed" : "Stable", systemImage: summary.hasChanges ? "arrow.triangle.2.circlepath" : "checkmark.circle")
 983                    .font(appDensity.font(.caption))
 984                    .foregroundStyle(summary.hasChanges ? severityTone(summary.severity).foreground : Color(.statusPositive))
 985                Spacer()
 986                Text(summary.severity.title.uppercased())
 987                    .font(appDensity.font(.caption2))
 988                    .foregroundStyle(summary.hasChanges ? severityTone(summary.severity).foreground : Color(.appTextSecondary))
 989                    .padding(.horizontal, 8)
 990                    .padding(.vertical, 4)
 991                    .background((summary.hasChanges ? severityTone(summary.severity) : AppStatusTone.neutral).surface)
 992                    .clipShape(Capsule())
 993                Text(summary.impactClassification.title.uppercased())
 994                    .font(appDensity.font(.caption2))
 995                    .foregroundStyle(summary.impactClassification.tone.foreground)
 996                    .padding(.horizontal, 8)
 997                    .padding(.vertical, 4)
 998                    .background(summary.impactClassification.tone.surface)
 999                    .clipShape(Capsule())
1000                Text(summary.generatedAt, style: .time)
1001                    .font(appDensity.font(.caption2))
1002                    .foregroundStyle(Color(.appTextSecondary))
1003            }
1004
1005            VStack(alignment: .leading, spacing: 4) {
1006                Text("Inference")
1007                    .font(appDensity.font(.caption2))
1008                    .foregroundStyle(Color(.appTextSecondary))
1009                Text(summary.message)
1010                    .font(appDensity.font(.caption))
1011                    .foregroundStyle(.primary)
1012                    .lineLimit(2)
1013            }
1014
1015            if !summary.observedFacts.isEmpty || summary.contextNote != nil {
1016                DisclosureGroup(showsDetails ? "Hide Details" : "Show Details", isExpanded: $showsDetails) {
1017                    VStack(alignment: .leading, spacing: 8) {
1018                        if !summary.observedFacts.isEmpty {
1019                            VStack(alignment: .leading, spacing: 4) {
1020                                Text("Observed")
1021                                    .font(appDensity.font(.caption2))
1022                                    .foregroundStyle(Color(.appTextSecondary))
1023                                ForEach(Array(summary.observedFacts.enumerated()), id: \.offset) { _, fact in
1024                                    Text(fact)
1025                                        .font(appDensity.font(.caption))
1026                                        .foregroundStyle(.primary)
1027                                }
1028                            }
1029                        }
1030
1031                        if let riskScoreDelta = summary.riskScoreDelta {
1032                            Text("Risk delta: \(riskScoreDelta >= 0 ? "+" : "")\(riskScoreDelta)")
1033                                .font(appDensity.font(.caption2))
1034                                .foregroundStyle(riskScoreDelta > 0 ? Color(.statusWarning) : .secondary)
1035                        }
1036
1037                        if let contextNote = summary.contextNote {
1038                            Text(contextNote)
1039                                .font(appDensity.font(.caption2))
1040                                .foregroundStyle(Color(.statusWarning))
1041                        }
1042                    }
1043                    .padding(.top, 4)
1044                }
1045                .font(appDensity.font(.caption))
1046                .tint(.secondary)
1047            }
1048        }
1049    }
1050
1051    private func severityTone(_ severity: ChangeSeverity) -> AppStatusTone {
1052        switch severity {
1053        case .low:
1054            return .neutral
1055        case .medium:
1056            return .warning
1057        case .high:
1058            return .critical
1059        }
1060    }
1061
1062}
1063
1064struct DomainDiffView: View {
1065    let title: String
1066    let sections: [DomainDiffSection]
1067    let contextNote: String?
1068    let showsUnchanged: Bool
1069    let highlightedSectionID: String?
1070
1071    @State private var collapsedSections = Set<String>()
1072    @State private var showsLowSeverity = false
1073
1074    private var filteredSections: [DomainDiffSection] {
1075        sections
1076            .map { section in
1077                let items = section.items.filter { item in
1078                    if !showsUnchanged, !item.hasChanges {
1079                        return false
1080                    }
1081                    if showsLowSeverity {
1082                        return true
1083                    }
1084                    return item.severity >= .medium || (showsUnchanged && item.changeType == .unchanged)
1085                }
1086                return DomainDiffSection(id: section.id, title: section.title, items: items)
1087            }
1088            .filter { !$0.items.isEmpty }
1089    }
1090
1091    private var hasLowSeverityChanges: Bool {
1092        sections.flatMap(\.items).contains { $0.hasChanges && $0.severity == .low }
1093    }
1094
1095    var body: some View {
1096        VStack(alignment: .leading, spacing: 12) {
1097            HStack {
1098                SectionTitleView(title: title)
1099                Spacer()
1100                if hasLowSeverityChanges {
1101                    Button(showsLowSeverity ? "Hide Low" : "Show Low") {
1102                        showsLowSeverity.toggle()
1103                    }
1104                    .buttonStyle(.bordered)
1105                    .font(.system(.caption, design: .monospaced))
1106                }
1107            }
1108            if let contextNote {
1109                MessageCardView(text: contextNote, isError: false)
1110            }
1111            if filteredSections.isEmpty {
1112                MessageCardView(text: "No comparison data available", isError: false)
1113            } else {
1114                ForEach(filteredSections) { section in
1115                    CardView(allowsHorizontalScroll: false) {
1116                        DisclosureGroup(isExpanded: binding(for: section)) {
1117                            let visibleItems = showsUnchanged ? section.items : section.items.filter(\.hasChanges)
1118
1119                            ForEach(visibleItems) { item in
1120                                VStack(alignment: .leading, spacing: 6) {
1121                                    HStack {
1122                                        Text(item.label)
1123                                            .font(.system(.caption, design: .monospaced))
1124                                            .foregroundStyle(Color(.appTextSecondary))
1125                                        Spacer()
1126                                        Text("\(item.changeType.marker) \(item.severity.title) • \(changeLabel(for: item.changeType))")
1127                                            .font(.system(.caption2, design: .monospaced))
1128                                            .foregroundStyle(changeTone(for: item).foreground)
1129                                            .padding(.horizontal, 8)
1130                                            .padding(.vertical, 4)
1131                                            .background(changeTone(for: item).surface)
1132                                            .clipShape(Capsule())
1133                                    }
1134
1135                                    if let oldValue = item.oldValue {
1136                                        VStack(alignment: .leading, spacing: 2) {
1137                                            Text("Old")
1138                                                .font(.system(.caption2, design: .monospaced))
1139                                                .foregroundStyle(Color(.appTextSecondary))
1140                                            Text(oldValue)
1141                                                .font(.system(.caption2, design: .monospaced))
1142                                                .foregroundStyle(Color(.appTextSecondary))
1143                                                .textSelection(.enabled)
1144                                        }
1145                                    }
1146
1147                                    if let newValue = item.newValue {
1148                                        VStack(alignment: .leading, spacing: 2) {
1149                                            Text("New")
1150                                                .font(.system(.caption2, design: .monospaced))
1151                                                .foregroundStyle(Color(.appTextSecondary))
1152                                            Text(newValue)
1153                                                .font(.system(.caption, design: .monospaced))
1154                                                .foregroundStyle(item.hasChanges ? .primary : .secondary)
1155                                                .textSelection(.enabled)
1156                                        }
1157                                    }
1158                                }
1159                                .padding(10)
1160                                .background(item.hasChanges ? changeTone(for: item).surface : Color(.appSurface))
1161                                .cornerRadius(8)
1162                            }
1163                        } label: {
1164                            HStack {
1165                                Text(section.title)
1166                                    .font(.system(.subheadline, design: .monospaced))
1167                                    .fontWeight(.semibold)
1168                                    .foregroundStyle(sectionColor(section))
1169                                Spacer()
1170                                Text(section.severity.title)
1171                                    .font(.system(.caption2, design: .monospaced))
1172                                    .foregroundStyle(sectionColor(section))
1173                            }
1174                        }
1175                    }
1176                    .id(section.id)
1177                    .overlay {
1178                        if highlightedSectionID == section.id {
1179                            RoundedRectangle(cornerRadius: 12)
1180                                .stroke(Color(.statusInfo).opacity(0.55), lineWidth: 1)
1181                        }
1182                    }
1183                }
1184            }
1185        }
1186        .onAppear {
1187            collapsedSections = Set(sections.filter { !showsUnchanged && !$0.hasChanges }.map(\.id))
1188        }
1189    }
1190
1191    private func changeLabel(for changeType: DiffChangeType) -> String {
1192        switch changeType {
1193        case .added:
1194            return "Added"
1195        case .removed:
1196            return "Removed"
1197        case .changed:
1198            return "Changed"
1199        case .unchanged:
1200            return "Unchanged"
1201        }
1202    }
1203
1204    private func changeTone(for item: DomainDiffItem) -> AppStatusTone {
1205        if item.changeType == .unchanged {
1206            return .neutral
1207        }
1208
1209        switch item.severity {
1210        case .low:
1211            return .info
1212        case .medium:
1213            return .warning
1214        case .high:
1215            return .critical
1216        }
1217    }
1218
1219    private func sectionColor(_ section: DomainDiffSection) -> Color {
1220        switch section.severity {
1221        case .low:
1222            return .blue
1223        case .medium:
1224            return Color(.statusWarning)
1225        case .high:
1226            return Color(.statusCritical)
1227        }
1228    }
1229
1230    private func binding(for section: DomainDiffSection) -> Binding<Bool> {
1231        Binding(
1232            get: { !collapsedSections.contains(section.id) },
1233            set: { isExpanded in
1234                if isExpanded {
1235                    collapsedSections.remove(section.id)
1236                } else {
1237                    collapsedSections.insert(section.id)
1238                }
1239            }
1240        )
1241    }
1242}
1243
1244struct TrackedDomainDetailHeaderView: View {
1245    let trackedDomain: TrackedDomain
1246
1247    var body: some View {
1248        VStack(alignment: .leading, spacing: 4) {
1249            if let note = trackedDomain.note?.nilIfEmpty {
1250                LabeledValueRow(row: InfoRowViewData(label: "Tracking Note", value: note, tone: .secondary))
1251            }
1252            HStack(spacing: 8) {
1253                if trackedDomain.isPinned {
1254                    Label("Pinned", systemImage: "pin.fill")
1255                }
1256                Text("Last refresh \(trackedDomain.updatedAt.formatted(date: .abbreviated, time: .shortened))")
1257            }
1258            .font(.system(.caption2, design: .monospaced))
1259            .foregroundStyle(Color(.appTextSecondary))
1260        }
1261    }
1262}
1263
1264struct SectionTitleView: View {
1265    @Environment(\.appDensity) private var appDensity
1266    let title: String
1267
1268    var body: some View {
1269        Text(title)
1270            .font(appDensity.font(.headline, design: .default, weight: .semibold))
1271            .foregroundStyle(.primary)
1272            .accessibilityAddTraits(.isHeader)
1273    }
1274}
1275
1276/// A card that wraps its content by default.
1277///
1278/// `allowsHorizontalScroll` used to default to `true`, so nine call sites put
1279/// their content behind a horizontal gesture instead of letting it wrap — a
1280/// WCAG 1.4.10 (Reflow) failure, and the mechanism behind clipped rows at large
1281/// text sizes. It also forced VoiceOver and Switch Control users onto a nested
1282/// scroll axis to reach data.
1283///
1284/// The default is now `false`. Where horizontal scrolling genuinely suits wide
1285/// tabular content, it is still opt-in — but it is suppressed at accessibility
1286/// text sizes, where wrapping always beats a hidden axis.
1287struct CardView<Content: View>: View {
1288    @Environment(\.appDensity) private var appDensity
1289    @Environment(\.dynamicTypeSize) private var dynamicTypeSize
1290    let allowsHorizontalScroll: Bool
1291    let content: Content
1292
1293    init(allowsHorizontalScroll: Bool = false, @ViewBuilder content: () -> Content) {
1294        self.allowsHorizontalScroll = allowsHorizontalScroll
1295        self.content = content()
1296    }
1297
1298    var body: some View {
1299        Group {
1300            if allowsHorizontalScroll, !dynamicTypeSize.isAccessibilitySize {
1301                ScrollView(.horizontal) {
1302                    cardContent
1303                        .scrollTargetLayout()
1304                }
1305                .scrollBounceBehavior(.basedOnSize, axes: .horizontal)
1306            } else {
1307                cardContent
1308                    .frame(maxWidth: .infinity, alignment: .leading)
1309            }
1310        }
1311        .frame(maxWidth: .infinity, alignment: .leading)
1312        .padding(appDensity.metrics.cardPadding)
1313        .background(Color(.appSurface))
1314        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
1315    }
1316
1317    private var cardContent: some View {
1318        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
1319            content
1320        }
1321    }
1322}
1323
1324struct LoadingCardView: View {
1325    let text: String
1326
1327    var body: some View {
1328        CardView {
1329            ProgressView(text)
1330                .appLoadingStyle()
1331                .frame(maxWidth: .infinity, alignment: .center)
1332        }
1333    }
1334}
1335
1336struct MessageCardView: View {
1337    let text: String
1338    let isError: Bool
1339
1340    var body: some View {
1341        CardView {
1342            MessageRowView(text: text, isError: isError)
1343        }
1344    }
1345}
1346
1347struct MessageRowView: View {
1348    @Environment(\.appDensity) private var appDensity
1349    let text: String
1350    let isError: Bool
1351
1352    var body: some View {
1353        Label(text, systemImage: isError ? "exclamationmark.triangle.fill" : "info.circle")
1354            .font(appDensity.font(.caption))
1355            .foregroundStyle(isError ? Color(.statusCritical) : .secondary)
1356            .lineLimit(nil)
1357            .fixedSize(horizontal: false, vertical: true)
1358    }
1359}
1360
1361struct SectionTrustMetadataView: View {
1362    @Environment(\.appDensity) private var appDensity
1363    let provenance: SectionProvenance?
1364    let confidence: ConfidenceLevel?
1365    let note: String?
1366
1367    init(provenance: SectionProvenance?, confidence: ConfidenceLevel?, note: String? = nil) {
1368        self.provenance = provenance
1369        self.confidence = confidence
1370        self.note = note
1371    }
1372
1373    var body: some View {
1374        if provenance != nil || confidence != nil || note != nil {
1375            VStack(alignment: .leading, spacing: 6) {
1376                HStack(spacing: 8) {
1377                    if let confidence {
1378                        Text("Confidence \(confidence.title)")
1379                            .font(appDensity.font(.caption2))
1380                            .foregroundStyle(Color(.appTextSecondary))
1381                    }
1382                    if let provenance {
1383                        Text(provenance.provider ?? provenance.source)
1384                            .font(appDensity.font(.caption2))
1385                            .foregroundStyle(Color(.appTextSecondary))
1386                        Text(provenance.resultSource.label)
1387                            .font(appDensity.font(.caption2))
1388                            .foregroundStyle(Color(.appTextSecondary))
1389                    }
1390                }
1391                DisclosureGroup("Details") {
1392                    VStack(alignment: .leading, spacing: 4) {
1393                        if let provenance {
1394                            LabeledValueRow(row: .init(label: "Method", value: provenance.source, tone: .secondary))
1395                            if let provider = provenance.provider {
1396                                LabeledValueRow(row: .init(label: "Provider", value: provider, tone: .secondary))
1397                            }
1398                            if let resolver = provenance.resolver {
1399                                LabeledValueRow(row: .init(label: "Resolver", value: resolver, tone: .secondary))
1400                            }
1401                            LabeledValueRow(row: .init(label: "Collected", value: provenance.collectedAt.formatted(date: .abbreviated, time: .shortened), tone: .secondary))
1402                            LabeledValueRow(row: .init(label: "Mode", value: provenance.resultSource.label, tone: .secondary))
1403                        }
1404                        if let note {
1405                            LabeledValueRow(row: .init(label: "Note", value: note, tone: .secondary))
1406                        }
1407                    }
1408                    .padding(.top, 4)
1409                }
1410                .font(appDensity.font(.caption))
1411                .tint(.secondary)
1412            }
1413        }
1414    }
1415}
1416
1417struct LabeledValueRow: View {
1418    @Environment(\.appDensity) private var appDensity
1419    @Environment(\.accessibilityDifferentiateWithoutColor) private var differentiateWithoutColor
1420    let row: InfoRowViewData
1421
1422    var body: some View {
1423        VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing - 1) {
1424            HStack(alignment: .top, spacing: 8) {
1425                VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing - 1) {
1426                    Text(row.label)
1427                        .font(appDensity.font(.caption2))
1428                        .foregroundStyle(Color(.appTextSecondary))
1429                    HStack(alignment: .firstTextBaseline, spacing: 4) {
1430                        if differentiateWithoutColor, let symbol = toneSymbol {
1431                            Image(systemName: symbol)
1432                                .font(appDensity.font(.caption2))
1433                                .foregroundStyle(ResultColors.color(for: row.tone))
1434                                .accessibilityHidden(true)
1435                        }
1436                        valueText
1437                    }
1438                }
1439                .frame(maxWidth: .infinity, alignment: .leading)
1440                .layoutPriority(1)
1441                Spacer(minLength: 6)
1442                if !row.value.isEmpty, row.value != "Unavailable" {
1443                    AppCopyButton(value: row.value, label: "Copy \(row.label)")
1444                }
1445            }
1446        }
1447        .frame(minHeight: appDensity.metrics.rowMinHeight, alignment: .topLeading)
1448    }
1449
1450    /// A leading symbol for warning/failure tones, shown only under Differentiate
1451    /// Without Color so tone is not conveyed by text colour alone. Hidden from
1452    /// VoiceOver — the value text already carries the meaning.
1453    private var toneSymbol: String? {
1454        switch row.tone {
1455        case .warning: return "exclamationmark.triangle.fill"
1456        case .failure: return "xmark.octagon.fill"
1457        default: return nil
1458        }
1459    }
1460
1461    @ViewBuilder
1462    private var valueText: some View {
1463        let base = Text(row.value)
1464            .font(appDensity.font(.caption))
1465            .foregroundStyle(ResultColors.color(for: row.tone))
1466
1467        switch row.speechStyle {
1468        case .plain:
1469            base
1470                .lineLimit(nil)
1471                .fixedSize(horizontal: false, vertical: true)
1472                .textSelection(.enabled)
1473        case .technical:
1474            // Record values and identifiers: keep punctuation audible (SPF/DMARC
1475            // separators are semantically load-bearing) and let VoiceOver use its
1476            // code-reading heuristics.
1477            base
1478                .speechAlwaysIncludesPunctuation()
1479                .accessibilityTextContentType(.sourceCode)
1480                .lineLimit(nil)
1481                .fixedSize(horizontal: false, vertical: true)
1482                .textSelection(.enabled)
1483        }
1484    }
1485}
1486
1487/// Maps a row's semantic tone onto the app palette.
1488///
1489/// See `Docs/ACCESSIBILITY.md` for the measured contrast ratios behind these
1490/// colours. Never reach for a literal (`Color(.statusCritical)`, `Color(.statusWarning)`, …) — the system
1491/// palette fails WCAG AA badly in light mode (systemYellow is 1.28:1 on white).
1492enum ResultColors {
1493    static func color(for tone: ResultTone) -> Color {
1494        switch tone {
1495        case .primary:
1496            return .primary
1497        case .secondary:
1498            return .secondary
1499        case .success:
1500            return Color(.statusPositive)
1501        case .warning:
1502            return Color(.statusWarning)
1503        case .failure:
1504            return Color(.statusCritical)
1505        }
1506    }
1507}
1508
1509extension DateFormatter {
1510    static let certDate: DateFormatter = {
1511        let formatter = DateFormatter()
1512        formatter.dateStyle = .medium
1513        formatter.timeStyle = .short
1514        return formatter
1515    }()
1516}
1517
1518extension View {
1519    func appLoadingStyle() -> some View {
1520        font(.system(.caption, design: .monospaced))
1521    }
1522}
1523
1524private extension String {
1525    var nilIfEmpty: String? {
1526        isEmpty ? nil : self
1527    }
1528}
1529
1530extension ChangeImpactClassification {
1531    var tone: AppStatusTone {
1532        switch self {
1533        case .informational: return .neutral
1534        case .warning: return .warning
1535        case .critical: return .critical
1536        }
1537    }
1538}
1539
1540extension TLSGrade {
1541    var tone: ResultTone {
1542        switch self {
1543        case .a: return .success
1544        case .f: return .failure
1545        default: return .warning
1546        }
1547    }
1548}
1549
1550extension EmailSecurityGrade {
1551    var tone: ResultTone {
1552        switch self {
1553        case .a: return .success
1554        case .f: return .failure
1555        default: return .warning
1556        }
1557    }
1558}
1559
1560#Preview {
1561    ContentView(viewModel: DomainViewModel())
1562}